commit bdd380e66db03110b1132a45f081bbe637e00360 Author: Matias Gonzalez Date: Mon Jun 13 15:22:22 2022 -0300 V1 diff --git a/README.md b/README.md new file mode 100644 index 0000000..249e8c4 --- /dev/null +++ b/README.md @@ -0,0 +1,45 @@ +# Instalación y backup de GITEA + +En esta documentación se detallará como realizar la instalación de GITEA mediante docker y también como realizar un backup del mismo o restaurarlo mendiando un archivo .sql. El tiempo estimado de descarga e instalación de la base de datos y el servicio GITEA mediante docker es de 3:30 minutos en una Raspberry. + + + +### Pre-requisitos 📋 + +_Para poder realizar la instalación de gitea es necesario tener instalado en nuestro terminal Docker y Docker Compose. Acceda a [Instalación de docker y docker compose](http://fabrica.faniot.ar:90/Soporte/docker-raspberry) para más detalles._ + + +### Instalación 🔧 + +_Se deberá ejecutar el archivo docker-compose.yml para que este comience el proceso de descarga e instalación de GITEA y la base de datos Postgres._ + + + +``` +docker-compose up -d +``` + + +_Una vez terminado el servicio quedará establecido en el puerto 3000 por defecto, puede cambiarse este puerto por otro editando el archivo docker-compose.yml._ + + +## Backup 💽 +_Para poder realizar o cargar un backcup es necesario haber instalado previamente el servidor gitea con su base de datos postgres mediante docker._ + +_Una vez descargado el archivo "backup-gitea.sh" deberá ejecutarlo en su terminal de la siguiente manera:_ + +``` +sudo sh backup-gitea.sh +``` + +_Una vez ejecutado siga las instrucciones provistas por el script para poder realizar la carga o descarga de su backup de la base de datos Postgres._ + +## Autores ✒️ + + +* **Matias Gonzalez** - desarrollo de script y documentación - [matias.gonzalez](http://fabrica.faniot.ar:90/matias.gonzalez) + + + + +--- diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..ea575a8 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,23 @@ +version: '3.5' +services: + grafana: + image: grafana/grafana + container_name: grafana + restart: on-failure + ports: + - "3000:3000" + volumes: + # Dados persistentes. + # sudo mkdir -p /srv/docker/grafana/data; chown 472:472 /srv/docker/grafana/data + - /etc/timezone:/etc/timezone:ro + - ./srv/docker/grafana/data:/var/lib/grafana + + influxdb: + image: influxdb:latest + volumes: + - /Users/anaisdotis-georgiou/temp/influxdb2:/var/lib/influxdb2:rw + + ports: + - "8086:8086" + + restart: always diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/MANIFEST.txt b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/MANIFEST.txt new file mode 100644 index 0000000..37d4f0b --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/MANIFEST.txt @@ -0,0 +1,48 @@ + +-----BEGIN PGP SIGNED MESSAGE----- +Hash: SHA512 + +{ + "manifestVersion": "2.0.0", + "signatureType": "community", + "signedByOrg": "grafana", + "signedByOrgName": "Grafana Labs", + "plugin": "aidanmountford-html-panel", + "version": "0.0.2", + "time": 1622740782947, + "keyId": "7e4d0c6a708866e7", + "files": { + "html_ctrl.js.map": "2caa41a34fb44fe6ac995e3c02fd3f8b90ed3ec1af4ac0e61591fc07c1c70cb9", + "polyfills.js.map": "bd92906901a9efe75ef42440dd3b880209a72a89fc2c14e2fd426118b7685e47", + "module.html": "891328f0269753ae1f11b943373e1572b85811a811289121f9b32289ce9b80a6", + "polyfills.js": "95ffd32d521681abd91d9caafe24a57f738b8ab0be76efc8d86ec9ddbd20ed3c", + "node_modules/brace/mode/javascript.js": "f8c8d44e800efbf80b582d8c6db982a9a48ffa0d23657e6e5bdd4899b2e57f2d", + "node_modules/brace/ext/language_tools.js": "7c1a9d963abde5494275bbdae5b29db37a4957f75c6506b7c131311948a30c80", + "node_modules/brace/index.js": "edd3c9f1853ff8272c2d2a116b31eb38746456622ab7914dfccd18c011914887", + "node_modules/brace/theme/tomorrow_night_bright.js": "0a4157986e2b120f2541e5a964d9b5311d83967bede7cac3ce5af0309c14f67d", + "node_modules/brace/worker/xml.js": "10068d244c1d0fd625022383db87b96f8ec8d56ccc931db8e8a718cc674e8131", + "node_modules/brace/worker/javascript.js": "5b0bb2f2c64a76de270922b44f9ab00c9e5f76b3e258d3b81ab7c8e975af76bf", + "module.js.map": "d16ef858d51f67f86cc58682c7c0b5f3100fa1fdd668c20b2bddef51f4901d21", + "rendering.js": "ab18abffcfc566008b92d2146c5926b5f90f7629f5720e1f53eee528075a4caf", + "html_ctrl.js": "1dea91ad0eba1ae6623b4bd7e1b574f9b1f974c78800df053c0094e047b0b462", + "plugin.json": "008bac96f07a194cc074351445a19c05bfbe8e7308825cb31f71336b80ff0847", + "rendering.js.map": "d9694ce64ed91c2a47e05508eb426492bdff4af101820a85af2ec20670938bcb", + "README.md": "96d52b6bf0070dabc20c729ac747a27058e3679953789bd50d692cdd68178c31", + "img/html-panel-logo-small.png": "2a3a73dc38347509ecd8f86c48b84d2841e2d026a56e792a44d6b2a363e5e4bc", + "img/html-panel-logo-large.png": "0b5dbc5e9ddbe2ff862a19d86e892eeeafbc916e74ccf7f7b91781e550c0239f", + "module.js": "30da21790a2b913b37f254eea02544f43de7437af333664a0e7db5ffcd377ae1", + "partials/blank.html": "6adc175599a335b096705123a42bd8b873ff0a69e8fe8ada62c1b10ac774b9e1", + "partials/editor_html.html": "d7fae040f0727da2273c9f0d3817dffc22596616e3cb1fbe8871050576ec56a6", + "partials/editor_events.html": "7ecd3ca6835a70b85751576db62da59b4d69beb69b43d0e8246ae03b90125493" + } +} +-----BEGIN PGP SIGNATURE----- +Version: OpenPGP.js v4.10.1 +Comment: https://openpgpjs.org + +wqEEARMKAAYFAmC5Dy8ACgkQfk0ManCIZuf3IgIJAUnxgbov9bdOMFFg0x5N +Hg69HgJdtibsEdQj8kuSrQcLTqdAFVtoFXaG8fpf9RFRL0tE81o4NL9zZ2cD +VoXlofZSAgd8Db9chuOGZI4R7tjmcGMhrFInc+NQwSsbx2HIM7ei7Kd25xIv +qe4tfbBW3f9UH73L0O8cIJCINPD4PS7A2LYang== +=dR0M +-----END PGP SIGNATURE----- diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/README.md b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/README.md new file mode 100644 index 0000000..7f75b8a --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/README.md @@ -0,0 +1,98 @@ +# Summary +Grafana panel for displaying metric sensitive or arbitary HTML. + +This only works with Grafana 3.X or later + +The control allows the specification of CSS, HTML and JS for +both initialisation and metric updates. + +This is based on the work by Marcus Calidus and the SVG plugin. + + + +## Installation + +It is possible to clone this repo directly into your plugins directory. +(var/lib/grafana/plugins) + +Afterwards restart grafana-server and the plugin should be automatically detected and used. + +``` +npm install +grunt +sudo service grafana-server restart +``` + + +## Clone into a directory of your choice + +If the plugin is cloned to a directory that is not the default plugins directory then you need to edit your grafana.ini config file (Default location is at /etc/grafana/grafana.ini) and add this: + +```ini +[plugin.svg] +path = /home/your/clone/dir/svg-panel +``` + +Note that if you clone it into the grafana plugins directory you do not need to add the above config option. That is only +if you want to place the plugin in a directory outside the standard plugins directory. Be aware that grafana-server +needs read access to the directory. + +# Options + +## HTML Data and CSS + +HTML & CSS is encapsulated in a shadow root and will therefore not "leak" outside the control. + +## Events +### onHandleMetric +this code is execute upon **every Rerfresh** + +``` +onHandleMetric(ctrl: MetricsPanelCtrl, svgnode: HTMLElement) +``` + +`ctrl` passes a grafana `MetricsPanelCtrl` object. This object contains all relevant data pertainig the current panel. +You may want to use the `ctrl.data` array property to access the current measurement data. + +`htmlnode` passes the HTMLElement of the html content on the panel. THis allows direct access to and editing of the html +content + +``` +htmlnode.innerHTML = "Hello World"; +``` + + +### onInit +this event is executed **once**, right after the first initializiation of the SVG. +``` +onHandleMetric(ctrl: MetricsPanelCtrl, svgnode: HTMLElement) +``` + +`ctrl` passes a grafana `MetricsPanelCtrl` object. This object contains all relevant data pertainig the current panel. +You may want to use the `ctrl.data` array property to access the current measurement data. + +`htmlnode` passes the HTMLElement of the html content on the panel. THis allows direct access to and editing of the html + +``` +htmlnode.innerHTML = "Hello World"; +``` + +# Changelog + +## 0.0.1 +* Initial build + + +# To do + +* Fix syntax highlighting for CSS and HTML +* Build "code snippet" library to allow commonly used HTML constructs to be stored and retrieved (including the relevant CSS and JS) + + +# Attributions + +## Marcus Calidus +SVG Grafana plugin on which this HTML plugin is based + +## Simran Singh +Icons used in this plugin diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/html_ctrl.js b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/html_ctrl.js new file mode 100644 index 0000000..4996437 --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/html_ctrl.js @@ -0,0 +1,491 @@ +'use strict'; + +System.register(['app/plugins/sdk', 'lodash', 'app/core/utils/kbn', 'app/core/time_series', './rendering', './node_modules/brace/index.js', './node_modules/brace/ext/language_tools.js', './node_modules/brace/theme/tomorrow_night_bright.js', './node_modules/brace/mode/javascript.js'], function (_export, _context) { + "use strict"; + + var MetricsPanelCtrl, _, kbn, TimeSeries, rendering, ace, _typeof, _createClass, GrafanaJSCompleter, HTMLCtrl; + + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + + return { + setters: [function (_appPluginsSdk) { + MetricsPanelCtrl = _appPluginsSdk.MetricsPanelCtrl; + }, function (_lodash) { + _ = _lodash.default; + }, function (_appCoreUtilsKbn) { + kbn = _appCoreUtilsKbn.default; + }, function (_appCoreTime_series) { + TimeSeries = _appCoreTime_series.default; + }, function (_rendering) { + rendering = _rendering.default; + }, function (_node_modulesBraceIndexJs) { + ace = _node_modulesBraceIndexJs.default; + }, function (_node_modulesBraceExtLanguage_toolsJs) {}, function (_node_modulesBraceThemeTomorrow_night_brightJs) {}, function (_node_modulesBraceModeJavascriptJs) {}], + execute: function () { + _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + + _createClass = function () { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + return function (Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps); + if (staticProps) defineProperties(Constructor, staticProps); + return Constructor; + }; + }(); + + GrafanaJSCompleter = function () { + function GrafanaJSCompleter($lang_tools, $control, $panel) { + _classCallCheck(this, GrafanaJSCompleter); + + this.$lang_tools = $lang_tools; + this.$control = $control; + this.$panel = $panel; + } + + _createClass(GrafanaJSCompleter, [{ + key: 'getCompletions', + value: function getCompletions(editor, session, pos, prefix, callback) { + var pos = editor.getCursorPosition(); + var line = editor.session.getLine(pos.row); + + prefix = line.substring(0, pos.column).match(/this\.\S*/g); + if (prefix) { + prefix = prefix[prefix.length - 1]; + prefix = prefix.substring(0, prefix.lastIndexOf('.')); + + var panelthis = this.$panel; + var evalObj = eval('panel' + prefix); + this.evaluatePrefix(evalObj, callback); + return; + } + + prefix = line.substring(0, pos.column).match(/ctrl\.\S*/g); + if (prefix) { + prefix = prefix[prefix.length - 1]; + prefix = prefix.substring(0, prefix.lastIndexOf('.')); + + var ctrl = this.$control; + var evalObj = eval(prefix); + this.evaluatePrefix(evalObj, callback); + return; + } + + prefix = line.substring(0, pos.column).match(/htmlnode\.\S*/g); + if (prefix) { + prefix = prefix[prefix.length - 1]; + prefix = prefix.substring(0, prefix.lastIndexOf('.')); + + var htmlnode = document.querySelector('.html-object'); + var evalObj = eval(prefix); + this.evaluatePrefix(evalObj, callback); + return; + } + + if (prefix == '') { + var wordList = ['ctrl', 'htmlnode', 'this']; + + callback(null, wordList.map(function (word) { + return { + caption: word, + value: word, + meta: 'Grafana keyword' + }; + })); + } + } + }, { + key: 'evaluatePrefix', + value: function evaluatePrefix(evalObj, callback) { + var wordList = []; + for (var key in evalObj) { + wordList.push(key); + } + callback(null, wordList.map(function (word) { + return { + caption: word + ': ' + (Array.isArray(evalObj[word]) ? 'Array[' + (evalObj[word] || []).length + ']' : _typeof(evalObj[word])), + value: word, + meta: "Grafana keyword" + }; + })); + return; + } + }]); + + return GrafanaJSCompleter; + }(); + + _export('HTMLCtrl', HTMLCtrl = function (_MetricsPanelCtrl) { + _inherits(HTMLCtrl, _MetricsPanelCtrl); + + function HTMLCtrl($scope, $injector, $rootScope) { + _classCallCheck(this, HTMLCtrl); + + var _this = _possibleConstructorReturn(this, (HTMLCtrl.__proto__ || Object.getPrototypeOf(HTMLCtrl)).call(this, $scope, $injector)); + + _this.$rootScope = $rootScope; + + var panelDefaults = { + links: [], + datasource: null, + maxDataPoints: 3, + interval: null, + targets: [{}], + cacheTimeout: null, + nullPointMode: 'connected', + aliasColors: {}, + format: 'short', + + css_data: '', + html_data: '', + js_code: '', + js_init_code: '' + }; + + _.defaults(_this.panel, panelDefaults); + + _this.events.on('render', _this.onRender.bind(_this)); + _this.events.on('refresh', _this.onRender.bind(_this)); + _this.events.on('data-received', _this.onDataReceived.bind(_this)); + _this.events.on('data-error', _this.onDataError.bind(_this)); + _this.events.on('data-snapshot-load', _this.onDataReceived.bind(_this)); + _this.events.on('init-edit-mode', _this.onInitEditMode.bind(_this)); + + _this.initialized = 0; + _this.editors = {}; + return _this; + } + + _createClass(HTMLCtrl, [{ + key: 'onInitEditMode', + value: function onInitEditMode() { + this.addEditorTab('HTML', 'public/plugins/aidanmountford-html-panel/partials/editor_html.html', 2); + this.addEditorTab('Events', 'public/plugins/aidanmountford-html-panel/partials/editor_events.html', 3); + this.unitFormats = kbn.getUnitFormats(); + this.aceLangTools = ace.acequire("ace/ext/language_tools"); + this.aceLangTools.addCompleter(new GrafanaJSCompleter(this.aceLangTools, this, this.panel)); + } + }, { + key: 'doShowAceHtml', + value: function doShowAceHtml(nodeId) { + setTimeout(function () { + if ($('#' + nodeId).length === 1) { + this.editors[nodeId] = ace.edit(nodeId); + $('#' + nodeId).attr('id', nodeId + '_initialized'); + this.editors[nodeId].setValue(this.panel[nodeId], 1); + this.editors[nodeId].getSession().on('change', function () { + var val = this.editors[nodeId].getSession().getValue(); + this.panel[nodeId] = val; + try { + this.resetHTML(); + this.render(); + } catch (err) { + console.error(err); + } + }.bind(this)); + this.editors[nodeId].setOptions({ + enableBasicAutocompletion: true, + enableLiveAutocompletion: true, + theme: 'ace/theme/tomorrow_night_bright', + showPrintMargin: false + }); + } + }.bind(this), 100); + return true; + } + }, { + key: 'doShowAceCSS', + value: function doShowAceCSS(nodeId) { + setTimeout(function () { + if ($('#' + nodeId).length === 1) { + this.editors[nodeId] = ace.edit(nodeId); + $('#' + nodeId).attr('id', nodeId + '_initialized'); + this.editors[nodeId].setValue(this.panel[nodeId], 1); + this.editors[nodeId].getSession().on('change', function () { + var val = this.editors[nodeId].getSession().getValue(); + this.panel[nodeId] = val; + try { + this.resetHTML(); + this.render(); + } catch (err) { + console.error(err); + } + }.bind(this)); + this.editors[nodeId].setOptions({ + enableBasicAutocompletion: true, + enableLiveAutocompletion: true, + theme: 'ace/theme/tomorrow_night_bright', + showPrintMargin: false + }); + } + }.bind(this), 100); + return true; + } + }, { + key: 'doShowAceJs', + value: function doShowAceJs(nodeId) { + setTimeout(function () { + if ($('#' + nodeId).length === 1) { + this.editors[nodeId] = ace.edit(nodeId); + $('#' + nodeId).attr('id', nodeId + '_initialized'); + this.editors[nodeId].setValue(this.panel[nodeId], 1); + this.editors[nodeId].getSession().on('change', function () { + var val = this.editors[nodeId].getSession().getValue(); + this.panel[nodeId] = val; + try { + this.setInitFunction(); + this.setHandleMetricFunction(); + this.render(); + } catch (err) { + console.error(err); + } + }.bind(this)); + this.editors[nodeId].setOptions({ + enableBasicAutocompletion: true, + enableLiveAutocompletion: true, + theme: 'ace/theme/tomorrow_night_bright', + mode: 'ace/mode/javascript', + showPrintMargin: false + }); + } + }.bind(this), 100); + return true; + } + }, { + key: 'setUnitFormat', + value: function setUnitFormat(subItem) { + this.panel.format = subItem.value; + this.render(); + } + }, { + key: 'onDataError', + value: function onDataError() { + this.data = []; + this.render(); + } + }, { + key: 'changeSeriesColor', + value: function changeSeriesColor(series, color) { + series.color = color; + this.panel.aliasColors[series.alias] = series.color; + this.render(); + } + }, { + key: 'setHandleMetricFunction', + value: function setHandleMetricFunction() { + this.panel.handleMetric = Function('ctrl', 'htmlnode', this.panel.js_code); + } + }, { + key: 'setInitFunction', + value: function setInitFunction() { + this.initialized = 0; + this.panel.doInit = Function('ctrl', 'htmlnode', this.panel.js_init_code); + } + }, { + key: 'onRender', + value: function onRender() { + if (!_.isFunction(this.panel.handleMetric)) { + this.setHandleMetricFunction(); + } + + if (!_.isFunction(this.panel.doInit)) { + this.setInitFunction(); + } + } + }, { + key: 'onDataReceived', + value: function onDataReceived(dataList) { + this.data = []; + + if (dataList.length > 0 && dataList[0].type === 'table') { + this.data = dataList.map(this.tableHandler.bind(this)); + this.table = this.data; // table should be regarded as deprecated + } else if (dataList.length > 0 && dataList[0].type === 'docs') { + this.data = dataList.map(this.docsHandler.bind(this)); + } else { + this.data = dataList.map(this.seriesHandler.bind(this)); + this.series = this.data; // series should be regarded as deprectated + } + + this.render(); + } + }, { + key: 'resetHTML', + value: function resetHTML() { + this.initialized = 0; + } + }, { + key: 'seriesHandler', + value: function seriesHandler(seriesData) { + var series = new TimeSeries({ + datapoints: seriesData.datapoints, + alias: seriesData.target + }); + + series.flotpairs = series.getFlotPairs(this.panel.nullPointMode); + return series; + } + }, { + key: 'docsHandler', + value: function docsHandler(seriesData) { + return seriesData; + } + }, { + key: 'tableHandler', + value: function tableHandler(tableData) { + + var columnNames = tableData.columns.map(function (column) { + return column.text; + }); + + var rows = tableData.rows.map(function (row) { + var datapoint = {}; + + row.forEach(function (value, columnIndex) { + var key = columnNames[columnIndex]; + datapoint[key] = value; + }); + + return datapoint; + }); + + return { columnNames: columnNames, rows: rows }; + } + }, { + key: 'getSeriesIdByAlias', + value: function getSeriesIdByAlias(aliasName) { + for (var i = 0; i < this.data.length; i++) { + if (this.data[i].alias == aliasName) { + return i; + } + } + return -1; + } + }, { + key: 'getSeriesElementByAlias', + value: function getSeriesElementByAlias(aliasName) { + var i = this.getSeriesIdByAlias(aliasName); + if (i >= 0) { + return this.data[i]; + } + return null; + } + }, { + key: 'getDecimalsForValue', + value: function getDecimalsForValue(value) { + if (_.isNumber(this.panel.decimals)) { + return { decimals: this.panel.decimals, scaledDecimals: null }; + } + + var delta = value / 2; + var dec = -Math.floor(Math.log(delta) / Math.LN10); + + var magn = Math.pow(10, -dec); + var norm = delta / magn; // norm is between 1.0 and 10.0 + var size; + + if (norm < 1.5) { + size = 1; + } else if (norm < 3) { + size = 2; + // special case for 2.5, requires an extra decimal + if (norm > 2.25) { + size = 2.5; + ++dec; + } + } else if (norm < 7.5) { + size = 5; + } else { + size = 10; + } + + size *= magn; + + // reduce starting decimals if not needed + if (Math.floor(value) === value) { + dec = 0; + } + + var result = {}; + result.decimals = Math.max(0, dec); + result.scaledDecimals = result.decimals - Math.floor(Math.log(size) / Math.LN10) + 2; + + return result; + } + }, { + key: 'formatValue', + value: function formatValue(value) { + var decimalInfo = this.getDecimalsForValue(value); + var formatFunc = kbn.valueFormats[this.panel.format]; + if (formatFunc) { + return formatFunc(value, decimalInfo.decimals, decimalInfo.scaledDecimals); + } + return value; + } + }, { + key: 'formatValueWithFormatter', + value: function formatValueWithFormatter(value, formatter) { + var decimalInfo = this.getDecimalsForValue(value); + var formatFunc = kbn.valueFormats[formatter]; + if (formatFunc) { + return formatFunc(value, decimalInfo.decimals, decimalInfo.scaledDecimals); + } + return value; + } + }, { + key: 'link', + value: function link(scope, elem, attrs, ctrl) { + rendering(scope, elem, attrs, ctrl); + } + }]); + + return HTMLCtrl; + }(MetricsPanelCtrl)); + + _export('HTMLCtrl', HTMLCtrl); + + HTMLCtrl.templateUrl = 'module.html'; + } + }; +}); +//# sourceMappingURL=html_ctrl.js.map diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/html_ctrl.js.map b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/html_ctrl.js.map new file mode 100644 index 0000000..0b4b7db --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/html_ctrl.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/html_ctrl.js"],"names":["MetricsPanelCtrl","_","kbn","TimeSeries","rendering","ace","GrafanaJSCompleter","$lang_tools","$control","$panel","editor","session","pos","prefix","callback","getCursorPosition","line","getLine","row","substring","column","match","length","lastIndexOf","panelthis","evalObj","eval","evaluatePrefix","ctrl","htmlnode","document","querySelector","wordList","map","word","caption","value","meta","key","push","Array","isArray","HTMLCtrl","$scope","$injector","$rootScope","panelDefaults","links","datasource","maxDataPoints","interval","targets","cacheTimeout","nullPointMode","aliasColors","format","css_data","html_data","js_code","js_init_code","defaults","panel","events","on","onRender","bind","onDataReceived","onDataError","onInitEditMode","initialized","editors","addEditorTab","unitFormats","getUnitFormats","aceLangTools","acequire","addCompleter","nodeId","setTimeout","$","edit","attr","setValue","getSession","val","getValue","resetHTML","render","err","console","error","setOptions","enableBasicAutocompletion","enableLiveAutocompletion","theme","showPrintMargin","setInitFunction","setHandleMetricFunction","mode","subItem","data","series","color","alias","handleMetric","Function","doInit","isFunction","dataList","type","tableHandler","table","docsHandler","seriesHandler","seriesData","datapoints","target","flotpairs","getFlotPairs","tableData","columnNames","columns","text","rows","datapoint","forEach","columnIndex","aliasName","i","getSeriesIdByAlias","isNumber","decimals","scaledDecimals","delta","dec","Math","floor","log","LN10","magn","pow","norm","size","result","max","decimalInfo","getDecimalsForValue","formatFunc","valueFormats","formatter","scope","elem","attrs","templateUrl"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAQA,4B,kBAAAA,gB;;AACDC,a;;AACAC,e;;AACAC,sB;;AACAC,qB;;AACAC,e;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMDC,8B;AACF,4CAAYC,WAAZ,EAAyBC,QAAzB,EAAmCC,MAAnC,EAA2C;AAAA;;AACvC,yBAAKF,WAAL,GAAmBA,WAAnB;AACA,yBAAKC,QAAL,GAAgBA,QAAhB;AACA,yBAAKC,MAAL,GAAcA,MAAd;AACH;;;;mDAEcC,M,EAAQC,O,EAASC,G,EAAKC,M,EAAQC,Q,EAAU;AACnD,4BAAIF,MAAMF,OAAOK,iBAAP,EAAV;AACA,4BAAIC,OAAON,OAAOC,OAAP,CAAeM,OAAf,CAAuBL,IAAIM,GAA3B,CAAX;;AAEAL,iCAASG,KAAKG,SAAL,CAAe,CAAf,EAAkBP,IAAIQ,MAAtB,EAA8BC,KAA9B,CAAoC,YAApC,CAAT;AACA,4BAAIR,MAAJ,EAAY;AACRA,qCAASA,OAAOA,OAAOS,MAAP,GAAgB,CAAvB,CAAT;AACAT,qCAASA,OAAOM,SAAP,CAAiB,CAAjB,EAAoBN,OAAOU,WAAP,CAAmB,GAAnB,CAApB,CAAT;;AAEA,gCAAIC,YAAY,KAAKf,MAArB;AACA,gCAAIgB,UAAUC,KAAK,UAAUb,MAAf,CAAd;AACA,iCAAKc,cAAL,CAAoBF,OAApB,EAA6BX,QAA7B;AACA;AACH;;AAEDD,iCAASG,KAAKG,SAAL,CAAe,CAAf,EAAkBP,IAAIQ,MAAtB,EAA8BC,KAA9B,CAAoC,YAApC,CAAT;AACA,4BAAIR,MAAJ,EAAY;AACRA,qCAASA,OAAOA,OAAOS,MAAP,GAAgB,CAAvB,CAAT;AACAT,qCAASA,OAAOM,SAAP,CAAiB,CAAjB,EAAoBN,OAAOU,WAAP,CAAmB,GAAnB,CAApB,CAAT;;AAEA,gCAAIK,OAAO,KAAKpB,QAAhB;AACA,gCAAIiB,UAAUC,KAAKb,MAAL,CAAd;AACA,iCAAKc,cAAL,CAAoBF,OAApB,EAA6BX,QAA7B;AACA;AACH;;AAEDD,iCAASG,KAAKG,SAAL,CAAe,CAAf,EAAkBP,IAAIQ,MAAtB,EAA8BC,KAA9B,CAAoC,gBAApC,CAAT;AACA,4BAAIR,MAAJ,EAAY;AACRA,qCAASA,OAAOA,OAAOS,MAAP,GAAgB,CAAvB,CAAT;AACAT,qCAASA,OAAOM,SAAP,CAAiB,CAAjB,EAAoBN,OAAOU,WAAP,CAAmB,GAAnB,CAApB,CAAT;;AAEA,gCAAIM,WAAWC,SAASC,aAAT,CAAuB,cAAvB,CAAf;AACA,gCAAIN,UAAUC,KAAKb,MAAL,CAAd;AACA,iCAAKc,cAAL,CAAoBF,OAApB,EAA6BX,QAA7B;AACA;AACH;;AAED,4BAAID,UAAU,EAAd,EAAkB;AACd,gCAAImB,WAAW,CAAC,MAAD,EAAS,UAAT,EAAqB,MAArB,CAAf;;AAEAlB,qCAAS,IAAT,EAAekB,SAASC,GAAT,CAAa,UAAUC,IAAV,EAAgB;AACxC,uCAAO;AACHC,6CAASD,IADN;AAEHE,2CAAOF,IAFJ;AAGHG,0CAAM;AAHH,iCAAP;AAKH,6BANc,CAAf;AAOH;AACJ;;;mDAEcZ,O,EAASX,Q,EAAU;AAC9B,4BAAIkB,WAAW,EAAf;AACA,6BAAK,IAAIM,GAAT,IAAgBb,OAAhB,EAAyB;AACrBO,qCAASO,IAAT,CAAcD,GAAd;AACH;AACDxB,iCAAS,IAAT,EAAekB,SAASC,GAAT,CAAa,UAAUC,IAAV,EAAgB;AACxC,mCAAO;AACHC,yCAASD,OAAO,IAAP,IAAeM,MAAMC,OAAN,CAAchB,QAAQS,IAAR,CAAd,IAA+B,WAAW,CAACT,QAAQS,IAAR,KAAiB,EAAlB,EAAsBZ,MAAjC,GAA0C,GAAzE,WAAsFG,QAAQS,IAAR,CAAtF,CAAf,CADN;AAEHE,uCAAOF,IAFJ;AAGHG,sCAAM;AAHH,6BAAP;AAKH,yBANc,CAAf;AAOA;AACH;;;;;;gCAIQK,Q;;;AAET,kCAAYC,MAAZ,EAAoBC,SAApB,EAA+BC,UAA/B,EAA2C;AAAA;;AAAA,oIACjCF,MADiC,EACzBC,SADyB;;AAEvC,0BAAKC,UAAL,GAAkBA,UAAlB;;AAEA,wBAAIC,gBAAgB;AAChBC,+BAAO,EADS;AAEhBC,oCAAY,IAFI;AAGhBC,uCAAe,CAHC;AAIhBC,kCAAU,IAJM;AAKhBC,iCAAS,CAAC,EAAD,CALO;AAMhBC,sCAAc,IANE;AAOhBC,uCAAe,WAPC;AAQhBC,qCAAa,EARG;AAShBC,gCAAQ,OATQ;;AAWhBC,kCAAU,EAXM;AAYhBC,mCAAW,EAZK;AAahBC,iCAAS,EAbO;AAchBC,sCAAc;AAdE,qBAApB;;AAiBA1D,sBAAE2D,QAAF,CAAW,MAAKC,KAAhB,EAAuBf,aAAvB;;AAEA,0BAAKgB,MAAL,CAAYC,EAAZ,CAAe,QAAf,EAAyB,MAAKC,QAAL,CAAcC,IAAd,OAAzB;AACA,0BAAKH,MAAL,CAAYC,EAAZ,CAAe,SAAf,EAA0B,MAAKC,QAAL,CAAcC,IAAd,OAA1B;AACA,0BAAKH,MAAL,CAAYC,EAAZ,CAAe,eAAf,EAAgC,MAAKG,cAAL,CAAoBD,IAApB,OAAhC;AACA,0BAAKH,MAAL,CAAYC,EAAZ,CAAe,YAAf,EAA6B,MAAKI,WAAL,CAAiBF,IAAjB,OAA7B;AACA,0BAAKH,MAAL,CAAYC,EAAZ,CAAe,oBAAf,EAAqC,MAAKG,cAAL,CAAoBD,IAApB,OAArC;AACA,0BAAKH,MAAL,CAAYC,EAAZ,CAAe,gBAAf,EAAiC,MAAKK,cAAL,CAAoBH,IAApB,OAAjC;;AAEA,0BAAKI,WAAL,GAAmB,CAAnB;AACA,0BAAKC,OAAL,GAAe,EAAf;AA/BuC;AAgC1C;;;;qDAEgB;AACb,6BAAKC,YAAL,CAAkB,MAAlB,EAA0B,oEAA1B,EAAgG,CAAhG;AACA,6BAAKA,YAAL,CAAkB,QAAlB,EAA4B,sEAA5B,EAAoG,CAApG;AACA,6BAAKC,WAAL,GAAmBtE,IAAIuE,cAAJ,EAAnB;AACA,6BAAKC,YAAL,GAAoBrE,IAAIsE,QAAJ,CAAa,wBAAb,CAApB;AACA,6BAAKD,YAAL,CAAkBE,YAAlB,CAA+B,IAAItE,kBAAJ,CAAuB,KAAKoE,YAA5B,EAA0C,IAA1C,EAAgD,KAAKb,KAArD,CAA/B;AACH;;;kDAEagB,M,EAAQ;AAClBC,mCAAW,YAAY;AACnB,gCAAIC,EAAE,MAAMF,MAAR,EAAgBvD,MAAhB,KAA2B,CAA/B,EAAkC;AAC9B,qCAAKgD,OAAL,CAAaO,MAAb,IAAuBxE,IAAI2E,IAAJ,CAASH,MAAT,CAAvB;AACAE,kCAAE,MAAMF,MAAR,EAAgBI,IAAhB,CAAqB,IAArB,EAA2BJ,SAAS,cAApC;AACA,qCAAKP,OAAL,CAAaO,MAAb,EAAqBK,QAArB,CAA8B,KAAKrB,KAAL,CAAWgB,MAAX,CAA9B,EAAkD,CAAlD;AACA,qCAAKP,OAAL,CAAaO,MAAb,EAAqBM,UAArB,GAAkCpB,EAAlC,CAAqC,QAArC,EAA+C,YAAY;AACvD,wCAAIqB,MAAM,KAAKd,OAAL,CAAaO,MAAb,EAAqBM,UAArB,GAAkCE,QAAlC,EAAV;AACA,yCAAKxB,KAAL,CAAWgB,MAAX,IAAqBO,GAArB;AACA,wCAAI;AACA,6CAAKE,SAAL;AACA,6CAAKC,MAAL;AACH,qCAHD,CAGE,OAAOC,GAAP,EAAY;AACVC,gDAAQC,KAAR,CAAcF,GAAd;AACH;AACJ,iCAT8C,CAS7CvB,IAT6C,CASxC,IATwC,CAA/C;AAUA,qCAAKK,OAAL,CAAaO,MAAb,EAAqBc,UAArB,CAAgC;AAC5BC,+DAA2B,IADC;AAE5BC,8DAA0B,IAFE;AAG5BC,2CAAO,iCAHqB;AAI5BC,qDAAiB;AAJW,iCAAhC;AAMH;AACJ,yBAtBU,CAsBT9B,IAtBS,CAsBJ,IAtBI,CAAX,EAsBc,GAtBd;AAuBA,+BAAO,IAAP;AACH;;;iDACYY,M,EAAQ;AACjBC,mCAAW,YAAY;AACnB,gCAAIC,EAAE,MAAMF,MAAR,EAAgBvD,MAAhB,KAA2B,CAA/B,EAAkC;AAC9B,qCAAKgD,OAAL,CAAaO,MAAb,IAAuBxE,IAAI2E,IAAJ,CAASH,MAAT,CAAvB;AACAE,kCAAE,MAAMF,MAAR,EAAgBI,IAAhB,CAAqB,IAArB,EAA2BJ,SAAS,cAApC;AACA,qCAAKP,OAAL,CAAaO,MAAb,EAAqBK,QAArB,CAA8B,KAAKrB,KAAL,CAAWgB,MAAX,CAA9B,EAAkD,CAAlD;AACA,qCAAKP,OAAL,CAAaO,MAAb,EAAqBM,UAArB,GAAkCpB,EAAlC,CAAqC,QAArC,EAA+C,YAAY;AACvD,wCAAIqB,MAAM,KAAKd,OAAL,CAAaO,MAAb,EAAqBM,UAArB,GAAkCE,QAAlC,EAAV;AACA,yCAAKxB,KAAL,CAAWgB,MAAX,IAAqBO,GAArB;AACA,wCAAI;AACA,6CAAKE,SAAL;AACA,6CAAKC,MAAL;AACH,qCAHD,CAGE,OAAOC,GAAP,EAAY;AACVC,gDAAQC,KAAR,CAAcF,GAAd;AACH;AACJ,iCAT8C,CAS7CvB,IAT6C,CASxC,IATwC,CAA/C;AAUA,qCAAKK,OAAL,CAAaO,MAAb,EAAqBc,UAArB,CAAgC;AAC5BC,+DAA2B,IADC;AAE5BC,8DAA0B,IAFE;AAG5BC,2CAAO,iCAHqB;AAI5BC,qDAAiB;AAJW,iCAAhC;AAMH;AACJ,yBAtBU,CAsBT9B,IAtBS,CAsBJ,IAtBI,CAAX,EAsBc,GAtBd;AAuBA,+BAAO,IAAP;AACH;;;gDACWY,M,EAAQ;AAChBC,mCAAW,YAAY;AACnB,gCAAIC,EAAE,MAAMF,MAAR,EAAgBvD,MAAhB,KAA2B,CAA/B,EAAkC;AAC9B,qCAAKgD,OAAL,CAAaO,MAAb,IAAuBxE,IAAI2E,IAAJ,CAASH,MAAT,CAAvB;AACAE,kCAAE,MAAMF,MAAR,EAAgBI,IAAhB,CAAqB,IAArB,EAA2BJ,SAAS,cAApC;AACA,qCAAKP,OAAL,CAAaO,MAAb,EAAqBK,QAArB,CAA8B,KAAKrB,KAAL,CAAWgB,MAAX,CAA9B,EAAkD,CAAlD;AACA,qCAAKP,OAAL,CAAaO,MAAb,EAAqBM,UAArB,GAAkCpB,EAAlC,CAAqC,QAArC,EAA+C,YAAY;AACvD,wCAAIqB,MAAM,KAAKd,OAAL,CAAaO,MAAb,EAAqBM,UAArB,GAAkCE,QAAlC,EAAV;AACA,yCAAKxB,KAAL,CAAWgB,MAAX,IAAqBO,GAArB;AACA,wCAAI;AACA,6CAAKY,eAAL;AACA,6CAAKC,uBAAL;AACA,6CAAKV,MAAL;AACH,qCAJD,CAIE,OAAOC,GAAP,EAAY;AACVC,gDAAQC,KAAR,CAAcF,GAAd;AACH;AACJ,iCAV8C,CAU7CvB,IAV6C,CAUxC,IAVwC,CAA/C;AAWA,qCAAKK,OAAL,CAAaO,MAAb,EAAqBc,UAArB,CAAgC;AAC5BC,+DAA2B,IADC;AAE5BC,8DAA0B,IAFE;AAG5BC,2CAAO,iCAHqB;AAI5BI,0CAAM,qBAJsB;AAK5BH,qDAAiB;AALW,iCAAhC;AAOH;AACJ,yBAxBU,CAwBT9B,IAxBS,CAwBJ,IAxBI,CAAX,EAwBc,GAxBd;AAyBA,+BAAO,IAAP;AACH;;;kDAEakC,O,EAAS;AACnB,6BAAKtC,KAAL,CAAWN,MAAX,GAAoB4C,QAAQ/D,KAA5B;AACA,6BAAKmD,MAAL;AACH;;;kDAEa;AACV,6BAAKa,IAAL,GAAY,EAAZ;AACA,6BAAKb,MAAL;AACH;;;sDAEiBc,M,EAAQC,K,EAAO;AAC7BD,+BAAOC,KAAP,GAAeA,KAAf;AACA,6BAAKzC,KAAL,CAAWP,WAAX,CAAuB+C,OAAOE,KAA9B,IAAuCF,OAAOC,KAA9C;AACA,6BAAKf,MAAL;AACH;;;8DAEyB;AACtB,6BAAK1B,KAAL,CAAW2C,YAAX,GAA0BC,SAAS,MAAT,EAAiB,UAAjB,EAA6B,KAAK5C,KAAL,CAAWH,OAAxC,CAA1B;AACH;;;sDAEiB;AACd,6BAAKW,WAAL,GAAmB,CAAnB;AACA,6BAAKR,KAAL,CAAW6C,MAAX,GAAoBD,SAAS,MAAT,EAAiB,UAAjB,EAA6B,KAAK5C,KAAL,CAAWF,YAAxC,CAApB;AACH;;;+CAEU;AACP,4BAAI,CAAC1D,EAAE0G,UAAF,CAAa,KAAK9C,KAAL,CAAW2C,YAAxB,CAAL,EAA4C;AACxC,iCAAKP,uBAAL;AACH;;AAED,4BAAI,CAAChG,EAAE0G,UAAF,CAAa,KAAK9C,KAAL,CAAW6C,MAAxB,CAAL,EAAsC;AAClC,iCAAKV,eAAL;AACH;AACJ;;;mDAEcY,Q,EAAU;AACrB,6BAAKR,IAAL,GAAY,EAAZ;;AAEA,4BAAIQ,SAAStF,MAAT,GAAkB,CAAlB,IAAuBsF,SAAS,CAAT,EAAYC,IAAZ,KAAqB,OAAhD,EAAyD;AACrD,iCAAKT,IAAL,GAAYQ,SAAS3E,GAAT,CAAa,KAAK6E,YAAL,CAAkB7C,IAAlB,CAAuB,IAAvB,CAAb,CAAZ;AACA,iCAAK8C,KAAL,GAAa,KAAKX,IAAlB,CAFqD,CAE7B;AAC3B,yBAHD,MAGO,IAAIQ,SAAStF,MAAT,GAAkB,CAAlB,IAAuBsF,SAAS,CAAT,EAAYC,IAAZ,KAAqB,MAAhD,EAAwD;AAC3D,iCAAKT,IAAL,GAAYQ,SAAS3E,GAAT,CAAa,KAAK+E,WAAL,CAAiB/C,IAAjB,CAAsB,IAAtB,CAAb,CAAZ;AACH,yBAFM,MAEA;AACH,iCAAKmC,IAAL,GAAYQ,SAAS3E,GAAT,CAAa,KAAKgF,aAAL,CAAmBhD,IAAnB,CAAwB,IAAxB,CAAb,CAAZ;AACA,iCAAKoC,MAAL,GAAc,KAAKD,IAAnB,CAFG,CAEsB;AAC5B;;AAED,6BAAKb,MAAL;AACH;;;gDAEW;AACR,6BAAKlB,WAAL,GAAmB,CAAnB;AACH;;;kDAEa6C,U,EAAY;AACtB,4BAAMb,SAAS,IAAIlG,UAAJ,CAAe;AAC1BgH,wCAAYD,WAAWC,UADG;AAE1BZ,mCAAOW,WAAWE;AAFQ,yBAAf,CAAf;;AAKAf,+BAAOgB,SAAP,GAAmBhB,OAAOiB,YAAP,CAAoB,KAAKzD,KAAL,CAAWR,aAA/B,CAAnB;AACA,+BAAOgD,MAAP;AACH;;;gDAGWa,U,EAAY;AACpB,+BAAOA,UAAP;AACH;;;iDAEYK,S,EAAW;;AAEpB,4BAAMC,cAAcD,UAAUE,OAAV,CAAkBxF,GAAlB,CAAsB;AAAA,mCAAUb,OAAOsG,IAAjB;AAAA,yBAAtB,CAApB;;AAEA,4BAAMC,OAAOJ,UAAUI,IAAV,CAAe1F,GAAf,CAAmB,eAAO;AACnC,gCAAM2F,YAAY,EAAlB;;AAEA1G,gCAAI2G,OAAJ,CAAY,UAACzF,KAAD,EAAQ0F,WAAR,EAAwB;AAChC,oCAAMxF,MAAMkF,YAAYM,WAAZ,CAAZ;AACAF,0CAAUtF,GAAV,IAAiBF,KAAjB;AACH,6BAHD;;AAKA,mCAAOwF,SAAP;AACH,yBATY,CAAb;;AAWA,+BAAO,EAACJ,aAAaA,WAAd,EAA2BG,MAAMA,IAAjC,EAAP;AACH;;;uDAEkBI,S,EAAW;AAC1B,6BAAK,IAAIC,IAAI,CAAb,EAAgBA,IAAI,KAAK5B,IAAL,CAAU9E,MAA9B,EAAsC0G,GAAtC,EAA2C;AACvC,gCAAI,KAAK5B,IAAL,CAAU4B,CAAV,EAAazB,KAAb,IAAsBwB,SAA1B,EAAqC;AACjC,uCAAOC,CAAP;AACH;AACJ;AACD,+BAAO,CAAC,CAAR;AACH;;;4DAEuBD,S,EAAW;AAC/B,4BAAIC,IAAI,KAAKC,kBAAL,CAAwBF,SAAxB,CAAR;AACA,4BAAIC,KAAK,CAAT,EAAY;AACR,mCAAO,KAAK5B,IAAL,CAAU4B,CAAV,CAAP;AACH;AACD,+BAAO,IAAP;AACH;;;wDAEmB5F,K,EAAO;AACvB,4BAAInC,EAAEiI,QAAF,CAAW,KAAKrE,KAAL,CAAWsE,QAAtB,CAAJ,EAAqC;AACjC,mCAAO,EAACA,UAAU,KAAKtE,KAAL,CAAWsE,QAAtB,EAAgCC,gBAAgB,IAAhD,EAAP;AACH;;AAED,4BAAIC,QAAQjG,QAAQ,CAApB;AACA,4BAAIkG,MAAM,CAACC,KAAKC,KAAL,CAAWD,KAAKE,GAAL,CAASJ,KAAT,IAAkBE,KAAKG,IAAlC,CAAX;;AAEA,4BAAIC,OAAOJ,KAAKK,GAAL,CAAS,EAAT,EAAa,CAACN,GAAd,CAAX;AACA,4BAAIO,OAAOR,QAAQM,IAAnB,CATuB,CASE;AACzB,4BAAIG,IAAJ;;AAEA,4BAAID,OAAO,GAAX,EAAgB;AACZC,mCAAO,CAAP;AACH,yBAFD,MAEO,IAAID,OAAO,CAAX,EAAc;AACjBC,mCAAO,CAAP;AACA;AACA,gCAAID,OAAO,IAAX,EAAiB;AACbC,uCAAO,GAAP;AACA,kCAAER,GAAF;AACH;AACJ,yBAPM,MAOA,IAAIO,OAAO,GAAX,EAAgB;AACnBC,mCAAO,CAAP;AACH,yBAFM,MAEA;AACHA,mCAAO,EAAP;AACH;;AAEDA,gCAAQH,IAAR;;AAEA;AACA,4BAAIJ,KAAKC,KAAL,CAAWpG,KAAX,MAAsBA,KAA1B,EAAiC;AAC7BkG,kCAAM,CAAN;AACH;;AAED,4BAAIS,SAAS,EAAb;AACAA,+BAAOZ,QAAP,GAAkBI,KAAKS,GAAL,CAAS,CAAT,EAAYV,GAAZ,CAAlB;AACAS,+BAAOX,cAAP,GAAwBW,OAAOZ,QAAP,GAAkBI,KAAKC,KAAL,CAAWD,KAAKE,GAAL,CAASK,IAAT,IAAiBP,KAAKG,IAAjC,CAAlB,GAA2D,CAAnF;;AAEA,+BAAOK,MAAP;AACH;;;gDAEW3G,K,EAAO;AACf,4BAAI6G,cAAc,KAAKC,mBAAL,CAAyB9G,KAAzB,CAAlB;AACA,4BAAI+G,aAAajJ,IAAIkJ,YAAJ,CAAiB,KAAKvF,KAAL,CAAWN,MAA5B,CAAjB;AACA,4BAAI4F,UAAJ,EAAgB;AACZ,mCAAOA,WAAW/G,KAAX,EAAkB6G,YAAYd,QAA9B,EAAwCc,YAAYb,cAApD,CAAP;AACH;AACD,+BAAOhG,KAAP;AACH;;;6DAEwBA,K,EAAOiH,S,EAAW;AACvC,4BAAIJ,cAAc,KAAKC,mBAAL,CAAyB9G,KAAzB,CAAlB;AACA,4BAAI+G,aAAajJ,IAAIkJ,YAAJ,CAAiBC,SAAjB,CAAjB;AACA,4BAAIF,UAAJ,EAAgB;AACZ,mCAAOA,WAAW/G,KAAX,EAAkB6G,YAAYd,QAA9B,EAAwCc,YAAYb,cAApD,CAAP;AACH;AACD,+BAAOhG,KAAP;AACH;;;yCAEIkH,K,EAAOC,I,EAAMC,K,EAAO5H,I,EAAM;AAC3BxB,kCAAUkJ,KAAV,EAAiBC,IAAjB,EAAuBC,KAAvB,EAA8B5H,IAA9B;AACH;;;;cAnSyB5B,gB;;;;AAuS9B0C,qBAAS+G,WAAT,GAAuB,aAAvB","file":"html_ctrl.js","sourcesContent":["import {MetricsPanelCtrl} from 'app/plugins/sdk';\nimport _ from 'lodash';\nimport kbn from 'app/core/utils/kbn';\nimport TimeSeries from 'app/core/time_series';\nimport rendering from './rendering';\nimport ace from './node_modules/brace/index.js';\nimport './node_modules/brace/ext/language_tools.js';\nimport './node_modules/brace/theme/tomorrow_night_bright.js';\nimport './node_modules/brace/mode/javascript.js';\n//import './node_modules/brace/mode/plain_text.js';\n\nclass GrafanaJSCompleter {\n constructor($lang_tools, $control, $panel) {\n this.$lang_tools = $lang_tools;\n this.$control = $control;\n this.$panel = $panel;\n }\n\n getCompletions(editor, session, pos, prefix, callback) {\n var pos = editor.getCursorPosition();\n var line = editor.session.getLine(pos.row);\n\n prefix = line.substring(0, pos.column).match(/this\\.\\S*/g);\n if (prefix) {\n prefix = prefix[prefix.length - 1];\n prefix = prefix.substring(0, prefix.lastIndexOf('.'));\n\n var panelthis = this.$panel;\n var evalObj = eval('panel' + prefix);\n this.evaluatePrefix(evalObj, callback);\n return;\n }\n\n prefix = line.substring(0, pos.column).match(/ctrl\\.\\S*/g);\n if (prefix) {\n prefix = prefix[prefix.length - 1];\n prefix = prefix.substring(0, prefix.lastIndexOf('.'));\n\n var ctrl = this.$control;\n var evalObj = eval(prefix);\n this.evaluatePrefix(evalObj, callback);\n return;\n }\n\n prefix = line.substring(0, pos.column).match(/htmlnode\\.\\S*/g);\n if (prefix) {\n prefix = prefix[prefix.length - 1];\n prefix = prefix.substring(0, prefix.lastIndexOf('.'));\n\n var htmlnode = document.querySelector('.html-object');\n var evalObj = eval(prefix);\n this.evaluatePrefix(evalObj, callback);\n return;\n }\n\n if (prefix == '') {\n var wordList = ['ctrl', 'htmlnode', 'this'];\n\n callback(null, wordList.map(function (word) {\n return {\n caption: word,\n value: word,\n meta: 'Grafana keyword'\n };\n }));\n }\n }\n\n evaluatePrefix(evalObj, callback) {\n var wordList = [];\n for (var key in evalObj) {\n wordList.push(key);\n }\n callback(null, wordList.map(function (word) {\n return {\n caption: word + ': ' + (Array.isArray(evalObj[word]) ? 'Array[' + (evalObj[word] || []).length + ']' : typeof evalObj[word]),\n value: word,\n meta: \"Grafana keyword\"\n };\n }));\n return;\n }\n}\n\n\nexport class HTMLCtrl extends MetricsPanelCtrl {\n\n constructor($scope, $injector, $rootScope) {\n super($scope, $injector);\n this.$rootScope = $rootScope;\n\n var panelDefaults = {\n links: [],\n datasource: null,\n maxDataPoints: 3,\n interval: null,\n targets: [{}],\n cacheTimeout: null,\n nullPointMode: 'connected',\n aliasColors: {},\n format: 'short',\n\n css_data: '',\n html_data: '',\n js_code: '',\n js_init_code: '',\n };\n\n _.defaults(this.panel, panelDefaults);\n\n this.events.on('render', this.onRender.bind(this));\n this.events.on('refresh', this.onRender.bind(this));\n this.events.on('data-received', this.onDataReceived.bind(this));\n this.events.on('data-error', this.onDataError.bind(this));\n this.events.on('data-snapshot-load', this.onDataReceived.bind(this));\n this.events.on('init-edit-mode', this.onInitEditMode.bind(this));\n\n this.initialized = 0;\n this.editors = {};\n }\n\n onInitEditMode() {\n this.addEditorTab('HTML', 'public/plugins/aidanmountford-html-panel/partials/editor_html.html', 2);\n this.addEditorTab('Events', 'public/plugins/aidanmountford-html-panel/partials/editor_events.html', 3);\n this.unitFormats = kbn.getUnitFormats();\n this.aceLangTools = ace.acequire(\"ace/ext/language_tools\");\n this.aceLangTools.addCompleter(new GrafanaJSCompleter(this.aceLangTools, this, this.panel));\n }\n\n doShowAceHtml(nodeId) {\n setTimeout(function () {\n if ($('#' + nodeId).length === 1) {\n this.editors[nodeId] = ace.edit(nodeId);\n $('#' + nodeId).attr('id', nodeId + '_initialized');\n this.editors[nodeId].setValue(this.panel[nodeId], 1);\n this.editors[nodeId].getSession().on('change', function () {\n var val = this.editors[nodeId].getSession().getValue();\n this.panel[nodeId] = val;\n try {\n this.resetHTML();\n this.render();\n } catch (err) {\n console.error(err);\n }\n }.bind(this));\n this.editors[nodeId].setOptions({\n enableBasicAutocompletion: true,\n enableLiveAutocompletion: true,\n theme: 'ace/theme/tomorrow_night_bright',\n showPrintMargin: false\n });\n }\n }.bind(this), 100);\n return true;\n }\n doShowAceCSS(nodeId) {\n setTimeout(function () {\n if ($('#' + nodeId).length === 1) {\n this.editors[nodeId] = ace.edit(nodeId);\n $('#' + nodeId).attr('id', nodeId + '_initialized');\n this.editors[nodeId].setValue(this.panel[nodeId], 1);\n this.editors[nodeId].getSession().on('change', function () {\n var val = this.editors[nodeId].getSession().getValue();\n this.panel[nodeId] = val;\n try {\n this.resetHTML();\n this.render();\n } catch (err) {\n console.error(err);\n }\n }.bind(this));\n this.editors[nodeId].setOptions({\n enableBasicAutocompletion: true,\n enableLiveAutocompletion: true,\n theme: 'ace/theme/tomorrow_night_bright',\n showPrintMargin: false\n });\n }\n }.bind(this), 100);\n return true;\n }\n doShowAceJs(nodeId) {\n setTimeout(function () {\n if ($('#' + nodeId).length === 1) {\n this.editors[nodeId] = ace.edit(nodeId);\n $('#' + nodeId).attr('id', nodeId + '_initialized');\n this.editors[nodeId].setValue(this.panel[nodeId], 1);\n this.editors[nodeId].getSession().on('change', function () {\n var val = this.editors[nodeId].getSession().getValue();\n this.panel[nodeId] = val;\n try {\n this.setInitFunction();\n this.setHandleMetricFunction();\n this.render();\n } catch (err) {\n console.error(err);\n }\n }.bind(this));\n this.editors[nodeId].setOptions({\n enableBasicAutocompletion: true,\n enableLiveAutocompletion: true,\n theme: 'ace/theme/tomorrow_night_bright',\n mode: 'ace/mode/javascript',\n showPrintMargin: false\n });\n }\n }.bind(this), 100);\n return true;\n }\n\n setUnitFormat(subItem) {\n this.panel.format = subItem.value;\n this.render();\n }\n\n onDataError() {\n this.data = [];\n this.render();\n }\n\n changeSeriesColor(series, color) {\n series.color = color;\n this.panel.aliasColors[series.alias] = series.color;\n this.render();\n }\n\n setHandleMetricFunction() {\n this.panel.handleMetric = Function('ctrl', 'htmlnode', this.panel.js_code);\n }\n\n setInitFunction() {\n this.initialized = 0;\n this.panel.doInit = Function('ctrl', 'htmlnode', this.panel.js_init_code);\n }\n\n onRender() {\n if (!_.isFunction(this.panel.handleMetric)) {\n this.setHandleMetricFunction();\n }\n\n if (!_.isFunction(this.panel.doInit)) {\n this.setInitFunction();\n }\n }\n\n onDataReceived(dataList) {\n this.data = [];\n\n if (dataList.length > 0 && dataList[0].type === 'table') {\n this.data = dataList.map(this.tableHandler.bind(this));\n this.table = this.data; // table should be regarded as deprecated\n } else if (dataList.length > 0 && dataList[0].type === 'docs') {\n this.data = dataList.map(this.docsHandler.bind(this));\n } else {\n this.data = dataList.map(this.seriesHandler.bind(this));\n this.series = this.data; // series should be regarded as deprectated\n }\n\n this.render();\n }\n\n resetHTML() {\n this.initialized = 0;\n }\n\n seriesHandler(seriesData) {\n const series = new TimeSeries({\n datapoints: seriesData.datapoints,\n alias: seriesData.target\n });\n\n series.flotpairs = series.getFlotPairs(this.panel.nullPointMode);\n return series;\n }\n\n\n docsHandler(seriesData) {\n return seriesData;\n }\n\n tableHandler(tableData) {\n\n const columnNames = tableData.columns.map(column => column.text);\n\n const rows = tableData.rows.map(row => {\n const datapoint = {};\n\n row.forEach((value, columnIndex) => {\n const key = columnNames[columnIndex];\n datapoint[key] = value;\n });\n\n return datapoint;\n });\n\n return {columnNames: columnNames, rows: rows};\n }\n\n getSeriesIdByAlias(aliasName) {\n for (var i = 0; i < this.data.length; i++) {\n if (this.data[i].alias == aliasName) {\n return i;\n }\n }\n return -1;\n }\n\n getSeriesElementByAlias(aliasName) {\n var i = this.getSeriesIdByAlias(aliasName);\n if (i >= 0) {\n return this.data[i];\n }\n return null;\n }\n\n getDecimalsForValue(value) {\n if (_.isNumber(this.panel.decimals)) {\n return {decimals: this.panel.decimals, scaledDecimals: null};\n }\n\n var delta = value / 2;\n var dec = -Math.floor(Math.log(delta) / Math.LN10);\n\n var magn = Math.pow(10, -dec);\n var norm = delta / magn; // norm is between 1.0 and 10.0\n var size;\n\n if (norm < 1.5) {\n size = 1;\n } else if (norm < 3) {\n size = 2;\n // special case for 2.5, requires an extra decimal\n if (norm > 2.25) {\n size = 2.5;\n ++dec;\n }\n } else if (norm < 7.5) {\n size = 5;\n } else {\n size = 10;\n }\n\n size *= magn;\n\n // reduce starting decimals if not needed\n if (Math.floor(value) === value) {\n dec = 0;\n }\n\n var result = {};\n result.decimals = Math.max(0, dec);\n result.scaledDecimals = result.decimals - Math.floor(Math.log(size) / Math.LN10) + 2;\n\n return result;\n }\n\n formatValue(value) {\n var decimalInfo = this.getDecimalsForValue(value);\n var formatFunc = kbn.valueFormats[this.panel.format];\n if (formatFunc) {\n return formatFunc(value, decimalInfo.decimals, decimalInfo.scaledDecimals);\n }\n return value;\n }\n\n formatValueWithFormatter(value, formatter) {\n var decimalInfo = this.getDecimalsForValue(value);\n var formatFunc = kbn.valueFormats[formatter];\n if (formatFunc) {\n return formatFunc(value, decimalInfo.decimals, decimalInfo.scaledDecimals);\n }\n return value;\n }\n\n link(scope, elem, attrs, ctrl) {\n rendering(scope, elem, attrs, ctrl);\n }\n\n}\n\nHTMLCtrl.templateUrl = 'module.html';\n"]} \ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/img/html-panel-logo-large.png b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/img/html-panel-logo-large.png new file mode 100644 index 0000000..da83da0 Binary files /dev/null and b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/img/html-panel-logo-large.png differ diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/img/html-panel-logo-small.png b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/img/html-panel-logo-small.png new file mode 100644 index 0000000..b762946 Binary files /dev/null and b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/img/html-panel-logo-small.png differ diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/module.html b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/module.html new file mode 100644 index 0000000..416d7e0 --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/module.html @@ -0,0 +1,15 @@ +
+
+
+ + + + +
+
+
+
+
+
+
+ diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/module.js b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/module.js new file mode 100644 index 0000000..c87fdc6 --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/module.js @@ -0,0 +1,19 @@ +'use strict'; + +System.register(['./polyfills.js', 'lodash', './html_ctrl'], function (_export, _context) { + "use strict"; + + var _, HTMLCtrl; + + return { + setters: [function (_polyfillsJs) {}, function (_lodash) { + _ = _lodash.default; + }, function (_html_ctrl) { + HTMLCtrl = _html_ctrl.HTMLCtrl; + }], + execute: function () { + _export('PanelCtrl', HTMLCtrl); + } + }; +}); +//# sourceMappingURL=module.js.map diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/module.js.map b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/module.js.map new file mode 100644 index 0000000..42f2db4 --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/module.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/module.js"],"names":["_","HTMLCtrl"],"mappings":";;;;;;;;;AACOA,a;;AACEC,oB,cAAAA,Q;;;iCAGLA,Q","file":"module.js","sourcesContent":["import './polyfills.js';\nimport _ from 'lodash';\nimport { HTMLCtrl } from './html_ctrl';\n\nexport {\n HTMLCtrl as PanelCtrl\n};\n"]} \ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/node_modules/brace/ext/language_tools.js b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/node_modules/brace/ext/language_tools.js new file mode 100644 index 0000000..1d6b1e8 --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/node_modules/brace/ext/language_tools.js @@ -0,0 +1,1956 @@ +ace.define("ace/snippets",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/lib/lang","ace/range","ace/anchor","ace/keyboard/hash_handler","ace/tokenizer","ace/lib/dom","ace/editor"], function(acequire, exports, module) { +"use strict"; +var oop = acequire("./lib/oop"); +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var lang = acequire("./lib/lang"); +var Range = acequire("./range").Range; +var Anchor = acequire("./anchor").Anchor; +var HashHandler = acequire("./keyboard/hash_handler").HashHandler; +var Tokenizer = acequire("./tokenizer").Tokenizer; +var comparePoints = Range.comparePoints; + +var SnippetManager = function() { + this.snippetMap = {}; + this.snippetNameMap = {}; +}; + +(function() { + oop.implement(this, EventEmitter); + + this.getTokenizer = function() { + function TabstopToken(str, _, stack) { + str = str.substr(1); + if (/^\d+$/.test(str) && !stack.inFormatString) + return [{tabstopId: parseInt(str, 10)}]; + return [{text: str}]; + } + function escape(ch) { + return "(?:[^\\\\" + ch + "]|\\\\.)"; + } + SnippetManager.$tokenizer = new Tokenizer({ + start: [ + {regex: /:/, onMatch: function(val, state, stack) { + if (stack.length && stack[0].expectIf) { + stack[0].expectIf = false; + stack[0].elseBranch = stack[0]; + return [stack[0]]; + } + return ":"; + }}, + {regex: /\\./, onMatch: function(val, state, stack) { + var ch = val[1]; + if (ch == "}" && stack.length) { + val = ch; + }else if ("`$\\".indexOf(ch) != -1) { + val = ch; + } else if (stack.inFormatString) { + if (ch == "n") + val = "\n"; + else if (ch == "t") + val = "\n"; + else if ("ulULE".indexOf(ch) != -1) { + val = {changeCase: ch, local: ch > "a"}; + } + } + + return [val]; + }}, + {regex: /}/, onMatch: function(val, state, stack) { + return [stack.length ? stack.shift() : val]; + }}, + {regex: /\$(?:\d+|\w+)/, onMatch: TabstopToken}, + {regex: /\$\{[\dA-Z_a-z]+/, onMatch: function(str, state, stack) { + var t = TabstopToken(str.substr(1), state, stack); + stack.unshift(t[0]); + return t; + }, next: "snippetVar"}, + {regex: /\n/, token: "newline", merge: false} + ], + snippetVar: [ + {regex: "\\|" + escape("\\|") + "*\\|", onMatch: function(val, state, stack) { + stack[0].choices = val.slice(1, -1).split(","); + }, next: "start"}, + {regex: "/(" + escape("/") + "+)/(?:(" + escape("/") + "*)/)(\\w*):?", + onMatch: function(val, state, stack) { + var ts = stack[0]; + ts.fmtString = val; + + val = this.splitRegex.exec(val); + ts.guard = val[1]; + ts.fmt = val[2]; + ts.flag = val[3]; + return ""; + }, next: "start"}, + {regex: "`" + escape("`") + "*`", onMatch: function(val, state, stack) { + stack[0].code = val.splice(1, -1); + return ""; + }, next: "start"}, + {regex: "\\?", onMatch: function(val, state, stack) { + if (stack[0]) + stack[0].expectIf = true; + }, next: "start"}, + {regex: "([^:}\\\\]|\\\\.)*:?", token: "", next: "start"} + ], + formatString: [ + {regex: "/(" + escape("/") + "+)/", token: "regex"}, + {regex: "", onMatch: function(val, state, stack) { + stack.inFormatString = true; + }, next: "start"} + ] + }); + SnippetManager.prototype.getTokenizer = function() { + return SnippetManager.$tokenizer; + }; + return SnippetManager.$tokenizer; + }; + + this.tokenizeTmSnippet = function(str, startState) { + return this.getTokenizer().getLineTokens(str, startState).tokens.map(function(x) { + return x.value || x; + }); + }; + + this.$getDefaultValue = function(editor, name) { + if (/^[A-Z]\d+$/.test(name)) { + var i = name.substr(1); + return (this.variables[name[0] + "__"] || {})[i]; + } + if (/^\d+$/.test(name)) { + return (this.variables.__ || {})[name]; + } + name = name.replace(/^TM_/, ""); + + if (!editor) + return; + var s = editor.session; + switch(name) { + case "CURRENT_WORD": + var r = s.getWordRange(); + case "SELECTION": + case "SELECTED_TEXT": + return s.getTextRange(r); + case "CURRENT_LINE": + return s.getLine(editor.getCursorPosition().row); + case "PREV_LINE": // not possible in textmate + return s.getLine(editor.getCursorPosition().row - 1); + case "LINE_INDEX": + return editor.getCursorPosition().column; + case "LINE_NUMBER": + return editor.getCursorPosition().row + 1; + case "SOFT_TABS": + return s.getUseSoftTabs() ? "YES" : "NO"; + case "TAB_SIZE": + return s.getTabSize(); + case "FILENAME": + case "FILEPATH": + return ""; + case "FULLNAME": + return "Ace"; + } + }; + this.variables = {}; + this.getVariableValue = function(editor, varName) { + if (this.variables.hasOwnProperty(varName)) + return this.variables[varName](editor, varName) || ""; + return this.$getDefaultValue(editor, varName) || ""; + }; + this.tmStrFormat = function(str, ch, editor) { + var flag = ch.flag || ""; + var re = ch.guard; + re = new RegExp(re, flag.replace(/[^gi]/, "")); + var fmtTokens = this.tokenizeTmSnippet(ch.fmt, "formatString"); + var _self = this; + var formatted = str.replace(re, function() { + _self.variables.__ = arguments; + var fmtParts = _self.resolveVariables(fmtTokens, editor); + var gChangeCase = "E"; + for (var i = 0; i < fmtParts.length; i++) { + var ch = fmtParts[i]; + if (typeof ch == "object") { + fmtParts[i] = ""; + if (ch.changeCase && ch.local) { + var next = fmtParts[i + 1]; + if (next && typeof next == "string") { + if (ch.changeCase == "u") + fmtParts[i] = next[0].toUpperCase(); + else + fmtParts[i] = next[0].toLowerCase(); + fmtParts[i + 1] = next.substr(1); + } + } else if (ch.changeCase) { + gChangeCase = ch.changeCase; + } + } else if (gChangeCase == "U") { + fmtParts[i] = ch.toUpperCase(); + } else if (gChangeCase == "L") { + fmtParts[i] = ch.toLowerCase(); + } + } + return fmtParts.join(""); + }); + this.variables.__ = null; + return formatted; + }; + + this.resolveVariables = function(snippet, editor) { + var result = []; + for (var i = 0; i < snippet.length; i++) { + var ch = snippet[i]; + if (typeof ch == "string") { + result.push(ch); + } else if (typeof ch != "object") { + continue; + } else if (ch.skip) { + gotoNext(ch); + } else if (ch.processed < i) { + continue; + } else if (ch.text) { + var value = this.getVariableValue(editor, ch.text); + if (value && ch.fmtString) + value = this.tmStrFormat(value, ch); + ch.processed = i; + if (ch.expectIf == null) { + if (value) { + result.push(value); + gotoNext(ch); + } + } else { + if (value) { + ch.skip = ch.elseBranch; + } else + gotoNext(ch); + } + } else if (ch.tabstopId != null) { + result.push(ch); + } else if (ch.changeCase != null) { + result.push(ch); + } + } + function gotoNext(ch) { + var i1 = snippet.indexOf(ch, i + 1); + if (i1 != -1) + i = i1; + } + return result; + }; + + this.insertSnippetForSelection = function(editor, snippetText) { + var cursor = editor.getCursorPosition(); + var line = editor.session.getLine(cursor.row); + var tabString = editor.session.getTabString(); + var indentString = line.match(/^\s*/)[0]; + + if (cursor.column < indentString.length) + indentString = indentString.slice(0, cursor.column); + + snippetText = snippetText.replace(/\r/g, ""); + var tokens = this.tokenizeTmSnippet(snippetText); + tokens = this.resolveVariables(tokens, editor); + tokens = tokens.map(function(x) { + if (x == "\n") + return x + indentString; + if (typeof x == "string") + return x.replace(/\t/g, tabString); + return x; + }); + var tabstops = []; + tokens.forEach(function(p, i) { + if (typeof p != "object") + return; + var id = p.tabstopId; + var ts = tabstops[id]; + if (!ts) { + ts = tabstops[id] = []; + ts.index = id; + ts.value = ""; + } + if (ts.indexOf(p) !== -1) + return; + ts.push(p); + var i1 = tokens.indexOf(p, i + 1); + if (i1 === -1) + return; + + var value = tokens.slice(i + 1, i1); + var isNested = value.some(function(t) {return typeof t === "object";}); + if (isNested && !ts.value) { + ts.value = value; + } else if (value.length && (!ts.value || typeof ts.value !== "string")) { + ts.value = value.join(""); + } + }); + tabstops.forEach(function(ts) {ts.length = 0;}); + var expanding = {}; + function copyValue(val) { + var copy = []; + for (var i = 0; i < val.length; i++) { + var p = val[i]; + if (typeof p == "object") { + if (expanding[p.tabstopId]) + continue; + var j = val.lastIndexOf(p, i - 1); + p = copy[j] || {tabstopId: p.tabstopId}; + } + copy[i] = p; + } + return copy; + } + for (var i = 0; i < tokens.length; i++) { + var p = tokens[i]; + if (typeof p != "object") + continue; + var id = p.tabstopId; + var i1 = tokens.indexOf(p, i + 1); + if (expanding[id]) { + if (expanding[id] === p) + expanding[id] = null; + continue; + } + + var ts = tabstops[id]; + var arg = typeof ts.value == "string" ? [ts.value] : copyValue(ts.value); + arg.unshift(i + 1, Math.max(0, i1 - i)); + arg.push(p); + expanding[id] = p; + tokens.splice.apply(tokens, arg); + + if (ts.indexOf(p) === -1) + ts.push(p); + } + var row = 0, column = 0; + var text = ""; + tokens.forEach(function(t) { + if (typeof t === "string") { + var lines = t.split("\n"); + if (lines.length > 1){ + column = lines[lines.length - 1].length; + row += lines.length - 1; + } else + column += t.length; + text += t; + } else { + if (!t.start) + t.start = {row: row, column: column}; + else + t.end = {row: row, column: column}; + } + }); + var range = editor.getSelectionRange(); + var end = editor.session.replace(range, text); + + var tabstopManager = new TabstopManager(editor); + var selectionId = editor.inVirtualSelectionMode && editor.selection.index; + tabstopManager.addTabstops(tabstops, range.start, end, selectionId); + }; + + this.insertSnippet = function(editor, snippetText) { + var self = this; + if (editor.inVirtualSelectionMode) + return self.insertSnippetForSelection(editor, snippetText); + + editor.forEachSelection(function() { + self.insertSnippetForSelection(editor, snippetText); + }, null, {keepOrder: true}); + + if (editor.tabstopManager) + editor.tabstopManager.tabNext(); + }; + + this.$getScope = function(editor) { + var scope = editor.session.$mode.$id || ""; + scope = scope.split("/").pop(); + if (scope === "html" || scope === "php") { + if (scope === "php" && !editor.session.$mode.inlinePhp) + scope = "html"; + var c = editor.getCursorPosition(); + var state = editor.session.getState(c.row); + if (typeof state === "object") { + state = state[0]; + } + if (state.substring) { + if (state.substring(0, 3) == "js-") + scope = "javascript"; + else if (state.substring(0, 4) == "css-") + scope = "css"; + else if (state.substring(0, 4) == "php-") + scope = "php"; + } + } + + return scope; + }; + + this.getActiveScopes = function(editor) { + var scope = this.$getScope(editor); + var scopes = [scope]; + var snippetMap = this.snippetMap; + if (snippetMap[scope] && snippetMap[scope].includeScopes) { + scopes.push.apply(scopes, snippetMap[scope].includeScopes); + } + scopes.push("_"); + return scopes; + }; + + this.expandWithTab = function(editor, options) { + var self = this; + var result = editor.forEachSelection(function() { + return self.expandSnippetForSelection(editor, options); + }, null, {keepOrder: true}); + if (result && editor.tabstopManager) + editor.tabstopManager.tabNext(); + return result; + }; + + this.expandSnippetForSelection = function(editor, options) { + var cursor = editor.getCursorPosition(); + var line = editor.session.getLine(cursor.row); + var before = line.substring(0, cursor.column); + var after = line.substr(cursor.column); + + var snippetMap = this.snippetMap; + var snippet; + this.getActiveScopes(editor).some(function(scope) { + var snippets = snippetMap[scope]; + if (snippets) + snippet = this.findMatchingSnippet(snippets, before, after); + return !!snippet; + }, this); + if (!snippet) + return false; + if (options && options.dryRun) + return true; + editor.session.doc.removeInLine(cursor.row, + cursor.column - snippet.replaceBefore.length, + cursor.column + snippet.replaceAfter.length + ); + + this.variables.M__ = snippet.matchBefore; + this.variables.T__ = snippet.matchAfter; + this.insertSnippetForSelection(editor, snippet.content); + + this.variables.M__ = this.variables.T__ = null; + return true; + }; + + this.findMatchingSnippet = function(snippetList, before, after) { + for (var i = snippetList.length; i--;) { + var s = snippetList[i]; + if (s.startRe && !s.startRe.test(before)) + continue; + if (s.endRe && !s.endRe.test(after)) + continue; + if (!s.startRe && !s.endRe) + continue; + + s.matchBefore = s.startRe ? s.startRe.exec(before) : [""]; + s.matchAfter = s.endRe ? s.endRe.exec(after) : [""]; + s.replaceBefore = s.triggerRe ? s.triggerRe.exec(before)[0] : ""; + s.replaceAfter = s.endTriggerRe ? s.endTriggerRe.exec(after)[0] : ""; + return s; + } + }; + + this.snippetMap = {}; + this.snippetNameMap = {}; + this.register = function(snippets, scope) { + var snippetMap = this.snippetMap; + var snippetNameMap = this.snippetNameMap; + var self = this; + + if (!snippets) + snippets = []; + + function wrapRegexp(src) { + if (src && !/^\^?\(.*\)\$?$|^\\b$/.test(src)) + src = "(?:" + src + ")"; + + return src || ""; + } + function guardedRegexp(re, guard, opening) { + re = wrapRegexp(re); + guard = wrapRegexp(guard); + if (opening) { + re = guard + re; + if (re && re[re.length - 1] != "$") + re = re + "$"; + } else { + re = re + guard; + if (re && re[0] != "^") + re = "^" + re; + } + return new RegExp(re); + } + + function addSnippet(s) { + if (!s.scope) + s.scope = scope || "_"; + scope = s.scope; + if (!snippetMap[scope]) { + snippetMap[scope] = []; + snippetNameMap[scope] = {}; + } + + var map = snippetNameMap[scope]; + if (s.name) { + var old = map[s.name]; + if (old) + self.unregister(old); + map[s.name] = s; + } + snippetMap[scope].push(s); + + if (s.tabTrigger && !s.trigger) { + if (!s.guard && /^\w/.test(s.tabTrigger)) + s.guard = "\\b"; + s.trigger = lang.escapeRegExp(s.tabTrigger); + } + + if (!s.trigger && !s.guard && !s.endTrigger && !s.endGuard) + return; + + s.startRe = guardedRegexp(s.trigger, s.guard, true); + s.triggerRe = new RegExp(s.trigger, "", true); + + s.endRe = guardedRegexp(s.endTrigger, s.endGuard, true); + s.endTriggerRe = new RegExp(s.endTrigger, "", true); + } + + if (snippets && snippets.content) + addSnippet(snippets); + else if (Array.isArray(snippets)) + snippets.forEach(addSnippet); + + this._signal("registerSnippets", {scope: scope}); + }; + this.unregister = function(snippets, scope) { + var snippetMap = this.snippetMap; + var snippetNameMap = this.snippetNameMap; + + function removeSnippet(s) { + var nameMap = snippetNameMap[s.scope||scope]; + if (nameMap && nameMap[s.name]) { + delete nameMap[s.name]; + var map = snippetMap[s.scope||scope]; + var i = map && map.indexOf(s); + if (i >= 0) + map.splice(i, 1); + } + } + if (snippets.content) + removeSnippet(snippets); + else if (Array.isArray(snippets)) + snippets.forEach(removeSnippet); + }; + this.parseSnippetFile = function(str) { + str = str.replace(/\r/g, ""); + var list = [], snippet = {}; + var re = /^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm; + var m; + while (m = re.exec(str)) { + if (m[1]) { + try { + snippet = JSON.parse(m[1]); + list.push(snippet); + } catch (e) {} + } if (m[4]) { + snippet.content = m[4].replace(/^\t/gm, ""); + list.push(snippet); + snippet = {}; + } else { + var key = m[2], val = m[3]; + if (key == "regex") { + var guardRe = /\/((?:[^\/\\]|\\.)*)|$/g; + snippet.guard = guardRe.exec(val)[1]; + snippet.trigger = guardRe.exec(val)[1]; + snippet.endTrigger = guardRe.exec(val)[1]; + snippet.endGuard = guardRe.exec(val)[1]; + } else if (key == "snippet") { + snippet.tabTrigger = val.match(/^\S*/)[0]; + if (!snippet.name) + snippet.name = val; + } else { + snippet[key] = val; + } + } + } + return list; + }; + this.getSnippetByName = function(name, editor) { + var snippetMap = this.snippetNameMap; + var snippet; + this.getActiveScopes(editor).some(function(scope) { + var snippets = snippetMap[scope]; + if (snippets) + snippet = snippets[name]; + return !!snippet; + }, this); + return snippet; + }; + +}).call(SnippetManager.prototype); + + +var TabstopManager = function(editor) { + if (editor.tabstopManager) + return editor.tabstopManager; + editor.tabstopManager = this; + this.$onChange = this.onChange.bind(this); + this.$onChangeSelection = lang.delayedCall(this.onChangeSelection.bind(this)).schedule; + this.$onChangeSession = this.onChangeSession.bind(this); + this.$onAfterExec = this.onAfterExec.bind(this); + this.attach(editor); +}; +(function() { + this.attach = function(editor) { + this.index = 0; + this.ranges = []; + this.tabstops = []; + this.$openTabstops = null; + this.selectedTabstop = null; + + this.editor = editor; + this.editor.on("change", this.$onChange); + this.editor.on("changeSelection", this.$onChangeSelection); + this.editor.on("changeSession", this.$onChangeSession); + this.editor.commands.on("afterExec", this.$onAfterExec); + this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler); + }; + this.detach = function() { + this.tabstops.forEach(this.removeTabstopMarkers, this); + this.ranges = null; + this.tabstops = null; + this.selectedTabstop = null; + this.editor.removeListener("change", this.$onChange); + this.editor.removeListener("changeSelection", this.$onChangeSelection); + this.editor.removeListener("changeSession", this.$onChangeSession); + this.editor.commands.removeListener("afterExec", this.$onAfterExec); + this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler); + this.editor.tabstopManager = null; + this.editor = null; + }; + + this.onChange = function(delta) { + var changeRange = delta; + var isRemove = delta.action[0] == "r"; + var start = delta.start; + var end = delta.end; + var startRow = start.row; + var endRow = end.row; + var lineDif = endRow - startRow; + var colDiff = end.column - start.column; + + if (isRemove) { + lineDif = -lineDif; + colDiff = -colDiff; + } + if (!this.$inChange && isRemove) { + var ts = this.selectedTabstop; + var changedOutside = ts && !ts.some(function(r) { + return comparePoints(r.start, start) <= 0 && comparePoints(r.end, end) >= 0; + }); + if (changedOutside) + return this.detach(); + } + var ranges = this.ranges; + for (var i = 0; i < ranges.length; i++) { + var r = ranges[i]; + if (r.end.row < start.row) + continue; + + if (isRemove && comparePoints(start, r.start) < 0 && comparePoints(end, r.end) > 0) { + this.removeRange(r); + i--; + continue; + } + + if (r.start.row == startRow && r.start.column > start.column) + r.start.column += colDiff; + if (r.end.row == startRow && r.end.column >= start.column) + r.end.column += colDiff; + if (r.start.row >= startRow) + r.start.row += lineDif; + if (r.end.row >= startRow) + r.end.row += lineDif; + + if (comparePoints(r.start, r.end) > 0) + this.removeRange(r); + } + if (!ranges.length) + this.detach(); + }; + this.updateLinkedFields = function() { + var ts = this.selectedTabstop; + if (!ts || !ts.hasLinkedRanges) + return; + this.$inChange = true; + var session = this.editor.session; + var text = session.getTextRange(ts.firstNonLinked); + for (var i = ts.length; i--;) { + var range = ts[i]; + if (!range.linked) + continue; + var fmt = exports.snippetManager.tmStrFormat(text, range.original); + session.replace(range, fmt); + } + this.$inChange = false; + }; + this.onAfterExec = function(e) { + if (e.command && !e.command.readOnly) + this.updateLinkedFields(); + }; + this.onChangeSelection = function() { + if (!this.editor) + return; + var lead = this.editor.selection.lead; + var anchor = this.editor.selection.anchor; + var isEmpty = this.editor.selection.isEmpty(); + for (var i = this.ranges.length; i--;) { + if (this.ranges[i].linked) + continue; + var containsLead = this.ranges[i].contains(lead.row, lead.column); + var containsAnchor = isEmpty || this.ranges[i].contains(anchor.row, anchor.column); + if (containsLead && containsAnchor) + return; + } + this.detach(); + }; + this.onChangeSession = function() { + this.detach(); + }; + this.tabNext = function(dir) { + var max = this.tabstops.length; + var index = this.index + (dir || 1); + index = Math.min(Math.max(index, 1), max); + if (index == max) + index = 0; + this.selectTabstop(index); + if (index === 0) + this.detach(); + }; + this.selectTabstop = function(index) { + this.$openTabstops = null; + var ts = this.tabstops[this.index]; + if (ts) + this.addTabstopMarkers(ts); + this.index = index; + ts = this.tabstops[this.index]; + if (!ts || !ts.length) + return; + + this.selectedTabstop = ts; + if (!this.editor.inVirtualSelectionMode) { + var sel = this.editor.multiSelect; + sel.toSingleRange(ts.firstNonLinked.clone()); + for (var i = ts.length; i--;) { + if (ts.hasLinkedRanges && ts[i].linked) + continue; + sel.addRange(ts[i].clone(), true); + } + if (sel.ranges[0]) + sel.addRange(sel.ranges[0].clone()); + } else { + this.editor.selection.setRange(ts.firstNonLinked); + } + + this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler); + }; + this.addTabstops = function(tabstops, start, end) { + if (!this.$openTabstops) + this.$openTabstops = []; + if (!tabstops[0]) { + var p = Range.fromPoints(end, end); + moveRelative(p.start, start); + moveRelative(p.end, start); + tabstops[0] = [p]; + tabstops[0].index = 0; + } + + var i = this.index; + var arg = [i + 1, 0]; + var ranges = this.ranges; + tabstops.forEach(function(ts, index) { + var dest = this.$openTabstops[index] || ts; + + for (var i = ts.length; i--;) { + var p = ts[i]; + var range = Range.fromPoints(p.start, p.end || p.start); + movePoint(range.start, start); + movePoint(range.end, start); + range.original = p; + range.tabstop = dest; + ranges.push(range); + if (dest != ts) + dest.unshift(range); + else + dest[i] = range; + if (p.fmtString) { + range.linked = true; + dest.hasLinkedRanges = true; + } else if (!dest.firstNonLinked) + dest.firstNonLinked = range; + } + if (!dest.firstNonLinked) + dest.hasLinkedRanges = false; + if (dest === ts) { + arg.push(dest); + this.$openTabstops[index] = dest; + } + this.addTabstopMarkers(dest); + }, this); + + if (arg.length > 2) { + if (this.tabstops.length) + arg.push(arg.splice(2, 1)[0]); + this.tabstops.splice.apply(this.tabstops, arg); + } + }; + + this.addTabstopMarkers = function(ts) { + var session = this.editor.session; + ts.forEach(function(range) { + if (!range.markerId) + range.markerId = session.addMarker(range, "ace_snippet-marker", "text"); + }); + }; + this.removeTabstopMarkers = function(ts) { + var session = this.editor.session; + ts.forEach(function(range) { + session.removeMarker(range.markerId); + range.markerId = null; + }); + }; + this.removeRange = function(range) { + var i = range.tabstop.indexOf(range); + range.tabstop.splice(i, 1); + i = this.ranges.indexOf(range); + this.ranges.splice(i, 1); + this.editor.session.removeMarker(range.markerId); + if (!range.tabstop.length) { + i = this.tabstops.indexOf(range.tabstop); + if (i != -1) + this.tabstops.splice(i, 1); + if (!this.tabstops.length) + this.detach(); + } + }; + + this.keyboardHandler = new HashHandler(); + this.keyboardHandler.bindKeys({ + "Tab": function(ed) { + if (exports.snippetManager && exports.snippetManager.expandWithTab(ed)) { + return; + } + + ed.tabstopManager.tabNext(1); + }, + "Shift-Tab": function(ed) { + ed.tabstopManager.tabNext(-1); + }, + "Esc": function(ed) { + ed.tabstopManager.detach(); + }, + "Return": function(ed) { + return false; + } + }); +}).call(TabstopManager.prototype); + + + +var changeTracker = {}; +changeTracker.onChange = Anchor.prototype.onChange; +changeTracker.setPosition = function(row, column) { + this.pos.row = row; + this.pos.column = column; +}; +changeTracker.update = function(pos, delta, $insertRight) { + this.$insertRight = $insertRight; + this.pos = pos; + this.onChange(delta); +}; + +var movePoint = function(point, diff) { + if (point.row == 0) + point.column += diff.column; + point.row += diff.row; +}; + +var moveRelative = function(point, start) { + if (point.row == start.row) + point.column -= start.column; + point.row -= start.row; +}; + + +acequire("./lib/dom").importCssString("\ +.ace_snippet-marker {\ + -moz-box-sizing: border-box;\ + box-sizing: border-box;\ + background: rgba(194, 193, 208, 0.09);\ + border: 1px dotted rgba(211, 208, 235, 0.62);\ + position: absolute;\ +}"); + +exports.snippetManager = new SnippetManager(); + + +var Editor = acequire("./editor").Editor; +(function() { + this.insertSnippet = function(content, options) { + return exports.snippetManager.insertSnippet(this, content, options); + }; + this.expandSnippet = function(options) { + return exports.snippetManager.expandWithTab(this, options); + }; +}).call(Editor.prototype); + +}); + +ace.define("ace/autocomplete/popup",["require","exports","module","ace/virtual_renderer","ace/editor","ace/range","ace/lib/event","ace/lib/lang","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; + +var Renderer = acequire("../virtual_renderer").VirtualRenderer; +var Editor = acequire("../editor").Editor; +var Range = acequire("../range").Range; +var event = acequire("../lib/event"); +var lang = acequire("../lib/lang"); +var dom = acequire("../lib/dom"); + +var $singleLineEditor = function(el) { + var renderer = new Renderer(el); + + renderer.$maxLines = 4; + + var editor = new Editor(renderer); + + editor.setHighlightActiveLine(false); + editor.setShowPrintMargin(false); + editor.renderer.setShowGutter(false); + editor.renderer.setHighlightGutterLine(false); + + editor.$mouseHandler.$focusWaitTimout = 0; + editor.$highlightTagPending = true; + + return editor; +}; + +var AcePopup = function(parentNode) { + var el = dom.createElement("div"); + var popup = new $singleLineEditor(el); + + if (parentNode) + parentNode.appendChild(el); + el.style.display = "none"; + popup.renderer.content.style.cursor = "default"; + popup.renderer.setStyle("ace_autocomplete"); + + popup.setOption("displayIndentGuides", false); + popup.setOption("dragDelay", 150); + + var noop = function(){}; + + popup.focus = noop; + popup.$isFocused = true; + + popup.renderer.$cursorLayer.restartTimer = noop; + popup.renderer.$cursorLayer.element.style.opacity = 0; + + popup.renderer.$maxLines = 8; + popup.renderer.$keepTextAreaAtCursor = false; + + popup.setHighlightActiveLine(false); + popup.session.highlight(""); + popup.session.$searchHighlight.clazz = "ace_highlight-marker"; + + popup.on("mousedown", function(e) { + var pos = e.getDocumentPosition(); + popup.selection.moveToPosition(pos); + selectionMarker.start.row = selectionMarker.end.row = pos.row; + e.stop(); + }); + + var lastMouseEvent; + var hoverMarker = new Range(-1,0,-1,Infinity); + var selectionMarker = new Range(-1,0,-1,Infinity); + selectionMarker.id = popup.session.addMarker(selectionMarker, "ace_active-line", "fullLine"); + popup.setSelectOnHover = function(val) { + if (!val) { + hoverMarker.id = popup.session.addMarker(hoverMarker, "ace_line-hover", "fullLine"); + } else if (hoverMarker.id) { + popup.session.removeMarker(hoverMarker.id); + hoverMarker.id = null; + } + }; + popup.setSelectOnHover(false); + popup.on("mousemove", function(e) { + if (!lastMouseEvent) { + lastMouseEvent = e; + return; + } + if (lastMouseEvent.x == e.x && lastMouseEvent.y == e.y) { + return; + } + lastMouseEvent = e; + lastMouseEvent.scrollTop = popup.renderer.scrollTop; + var row = lastMouseEvent.getDocumentPosition().row; + if (hoverMarker.start.row != row) { + if (!hoverMarker.id) + popup.setRow(row); + setHoverMarker(row); + } + }); + popup.renderer.on("beforeRender", function() { + if (lastMouseEvent && hoverMarker.start.row != -1) { + lastMouseEvent.$pos = null; + var row = lastMouseEvent.getDocumentPosition().row; + if (!hoverMarker.id) + popup.setRow(row); + setHoverMarker(row, true); + } + }); + popup.renderer.on("afterRender", function() { + var row = popup.getRow(); + var t = popup.renderer.$textLayer; + var selected = t.element.childNodes[row - t.config.firstRow]; + if (selected == t.selectedNode) + return; + if (t.selectedNode) + dom.removeCssClass(t.selectedNode, "ace_selected"); + t.selectedNode = selected; + if (selected) + dom.addCssClass(selected, "ace_selected"); + }); + var hideHoverMarker = function() { setHoverMarker(-1); }; + var setHoverMarker = function(row, suppressRedraw) { + if (row !== hoverMarker.start.row) { + hoverMarker.start.row = hoverMarker.end.row = row; + if (!suppressRedraw) + popup.session._emit("changeBackMarker"); + popup._emit("changeHoverMarker"); + } + }; + popup.getHoveredRow = function() { + return hoverMarker.start.row; + }; + + event.addListener(popup.container, "mouseout", hideHoverMarker); + popup.on("hide", hideHoverMarker); + popup.on("changeSelection", hideHoverMarker); + + popup.session.doc.getLength = function() { + return popup.data.length; + }; + popup.session.doc.getLine = function(i) { + var data = popup.data[i]; + if (typeof data == "string") + return data; + return (data && data.value) || ""; + }; + + var bgTokenizer = popup.session.bgTokenizer; + bgTokenizer.$tokenizeRow = function(row) { + var data = popup.data[row]; + var tokens = []; + if (!data) + return tokens; + if (typeof data == "string") + data = {value: data}; + if (!data.caption) + data.caption = data.value || data.name; + + var last = -1; + var flag, c; + for (var i = 0; i < data.caption.length; i++) { + c = data.caption[i]; + flag = data.matchMask & (1 << i) ? 1 : 0; + if (last !== flag) { + tokens.push({type: data.className || "" + ( flag ? "completion-highlight" : ""), value: c}); + last = flag; + } else { + tokens[tokens.length - 1].value += c; + } + } + + if (data.meta) { + var maxW = popup.renderer.$size.scrollerWidth / popup.renderer.layerConfig.characterWidth; + var metaData = data.meta; + if (metaData.length + data.caption.length > maxW - 2) { + metaData = metaData.substr(0, maxW - data.caption.length - 3) + "\u2026"; + } + tokens.push({type: "rightAlignedText", value: metaData}); + } + return tokens; + }; + bgTokenizer.$updateOnChange = noop; + bgTokenizer.start = noop; + + popup.session.$computeWidth = function() { + return this.screenWidth = 0; + }; + + popup.$blockScrolling = Infinity; + popup.isOpen = false; + popup.isTopdown = false; + popup.autoSelect = true; + + popup.data = []; + popup.setData = function(list) { + popup.setValue(lang.stringRepeat("\n", list.length), -1); + popup.data = list || []; + popup.setRow(0); + }; + popup.getData = function(row) { + return popup.data[row]; + }; + + popup.getRow = function() { + return selectionMarker.start.row; + }; + popup.setRow = function(line) { + line = Math.max(this.autoSelect ? 0 : -1, Math.min(this.data.length, line)); + if (selectionMarker.start.row != line) { + popup.selection.clearSelection(); + selectionMarker.start.row = selectionMarker.end.row = line || 0; + popup.session._emit("changeBackMarker"); + popup.moveCursorTo(line || 0, 0); + if (popup.isOpen) + popup._signal("select"); + } + }; + + popup.on("changeSelection", function() { + if (popup.isOpen) + popup.setRow(popup.selection.lead.row); + popup.renderer.scrollCursorIntoView(); + }); + + popup.hide = function() { + this.container.style.display = "none"; + this._signal("hide"); + popup.isOpen = false; + }; + popup.show = function(pos, lineHeight, topdownOnly) { + var el = this.container; + var screenHeight = window.innerHeight; + var screenWidth = window.innerWidth; + var renderer = this.renderer; + var maxH = renderer.$maxLines * lineHeight * 1.4; + var top = pos.top + this.$borderSize; + var allowTopdown = top > screenHeight / 2 && !topdownOnly; + if (allowTopdown && top + lineHeight + maxH > screenHeight) { + renderer.$maxPixelHeight = top - 2 * this.$borderSize; + el.style.top = ""; + el.style.bottom = screenHeight - top + "px"; + popup.isTopdown = false; + } else { + top += lineHeight; + renderer.$maxPixelHeight = screenHeight - top - 0.2 * lineHeight; + el.style.top = top + "px"; + el.style.bottom = ""; + popup.isTopdown = true; + } + + el.style.display = ""; + this.renderer.$textLayer.checkForSizeChanges(); + + var left = pos.left; + if (left + el.offsetWidth > screenWidth) + left = screenWidth - el.offsetWidth; + + el.style.left = left + "px"; + + this._signal("show"); + lastMouseEvent = null; + popup.isOpen = true; + }; + + popup.getTextLeftOffset = function() { + return this.$borderSize + this.renderer.$padding + this.$imageSize; + }; + + popup.$imageSize = 0; + popup.$borderSize = 1; + + return popup; +}; + +dom.importCssString("\ +.ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line {\ + background-color: #CAD6FA;\ + z-index: 1;\ +}\ +.ace_editor.ace_autocomplete .ace_line-hover {\ + border: 1px solid #abbffe;\ + margin-top: -1px;\ + background: rgba(233,233,253,0.4);\ +}\ +.ace_editor.ace_autocomplete .ace_line-hover {\ + position: absolute;\ + z-index: 2;\ +}\ +.ace_editor.ace_autocomplete .ace_scroller {\ + background: none;\ + border: none;\ + box-shadow: none;\ +}\ +.ace_rightAlignedText {\ + color: gray;\ + display: inline-block;\ + position: absolute;\ + right: 4px;\ + text-align: right;\ + z-index: -1;\ +}\ +.ace_editor.ace_autocomplete .ace_completion-highlight{\ + color: #000;\ + text-shadow: 0 0 0.01em;\ +}\ +.ace_editor.ace_autocomplete {\ + width: 280px;\ + z-index: 200000;\ + background: #fbfbfb;\ + color: #444;\ + border: 1px lightgray solid;\ + position: fixed;\ + box-shadow: 2px 3px 5px rgba(0,0,0,.2);\ + line-height: 1.4;\ +}"); + +exports.AcePopup = AcePopup; + +}); + +ace.define("ace/autocomplete/util",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +exports.parForEach = function(array, fn, callback) { + var completed = 0; + var arLength = array.length; + if (arLength === 0) + callback(); + for (var i = 0; i < arLength; i++) { + fn(array[i], function(result, err) { + completed++; + if (completed === arLength) + callback(result, err); + }); + } +}; + +var ID_REGEX = /[a-zA-Z_0-9\$\-\u00A2-\uFFFF]/; + +exports.retrievePrecedingIdentifier = function(text, pos, regex) { + regex = regex || ID_REGEX; + var buf = []; + for (var i = pos-1; i >= 0; i--) { + if (regex.test(text[i])) + buf.push(text[i]); + else + break; + } + return buf.reverse().join(""); +}; + +exports.retrieveFollowingIdentifier = function(text, pos, regex) { + regex = regex || ID_REGEX; + var buf = []; + for (var i = pos; i < text.length; i++) { + if (regex.test(text[i])) + buf.push(text[i]); + else + break; + } + return buf; +}; + +exports.getCompletionPrefix = function (editor) { + var pos = editor.getCursorPosition(); + var line = editor.session.getLine(pos.row); + var prefix; + editor.completers.forEach(function(completer) { + if (completer.identifierRegexps) { + completer.identifierRegexps.forEach(function(identifierRegex) { + if (!prefix && identifierRegex) + prefix = this.retrievePrecedingIdentifier(line, pos.column, identifierRegex); + }.bind(this)); + } + }.bind(this)); + return prefix || this.retrievePrecedingIdentifier(line, pos.column); +}; + +}); + +ace.define("ace/autocomplete",["require","exports","module","ace/keyboard/hash_handler","ace/autocomplete/popup","ace/autocomplete/util","ace/lib/event","ace/lib/lang","ace/lib/dom","ace/snippets"], function(acequire, exports, module) { +"use strict"; + +var HashHandler = acequire("./keyboard/hash_handler").HashHandler; +var AcePopup = acequire("./autocomplete/popup").AcePopup; +var util = acequire("./autocomplete/util"); +var event = acequire("./lib/event"); +var lang = acequire("./lib/lang"); +var dom = acequire("./lib/dom"); +var snippetManager = acequire("./snippets").snippetManager; + +var Autocomplete = function() { + this.autoInsert = false; + this.autoSelect = true; + this.exactMatch = false; + this.gatherCompletionsId = 0; + this.keyboardHandler = new HashHandler(); + this.keyboardHandler.bindKeys(this.commands); + + this.blurListener = this.blurListener.bind(this); + this.changeListener = this.changeListener.bind(this); + this.mousedownListener = this.mousedownListener.bind(this); + this.mousewheelListener = this.mousewheelListener.bind(this); + + this.changeTimer = lang.delayedCall(function() { + this.updateCompletions(true); + }.bind(this)); + + this.tooltipTimer = lang.delayedCall(this.updateDocTooltip.bind(this), 50); +}; + +(function() { + + this.$init = function() { + this.popup = new AcePopup(document.body || document.documentElement); + this.popup.on("click", function(e) { + this.insertMatch(); + e.stop(); + }.bind(this)); + this.popup.focus = this.editor.focus.bind(this.editor); + this.popup.on("show", this.tooltipTimer.bind(null, null)); + this.popup.on("select", this.tooltipTimer.bind(null, null)); + this.popup.on("changeHoverMarker", this.tooltipTimer.bind(null, null)); + return this.popup; + }; + + this.getPopup = function() { + return this.popup || this.$init(); + }; + + this.openPopup = function(editor, prefix, keepPopupPosition) { + if (!this.popup) + this.$init(); + + this.popup.autoSelect = this.autoSelect; + + this.popup.setData(this.completions.filtered); + + editor.keyBinding.addKeyboardHandler(this.keyboardHandler); + + var renderer = editor.renderer; + this.popup.setRow(this.autoSelect ? 0 : -1); + if (!keepPopupPosition) { + this.popup.setTheme(editor.getTheme()); + this.popup.setFontSize(editor.getFontSize()); + + var lineHeight = renderer.layerConfig.lineHeight; + + var pos = renderer.$cursorLayer.getPixelPosition(this.base, true); + pos.left -= this.popup.getTextLeftOffset(); + + var rect = editor.container.getBoundingClientRect(); + pos.top += rect.top - renderer.layerConfig.offset; + pos.left += rect.left - editor.renderer.scrollLeft; + pos.left += renderer.gutterWidth; + + this.popup.show(pos, lineHeight); + } else if (keepPopupPosition && !prefix) { + this.detach(); + } + }; + + this.detach = function() { + this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler); + this.editor.off("changeSelection", this.changeListener); + this.editor.off("blur", this.blurListener); + this.editor.off("mousedown", this.mousedownListener); + this.editor.off("mousewheel", this.mousewheelListener); + this.changeTimer.cancel(); + this.hideDocTooltip(); + + this.gatherCompletionsId += 1; + if (this.popup && this.popup.isOpen) + this.popup.hide(); + + if (this.base) + this.base.detach(); + this.activated = false; + this.completions = this.base = null; + }; + + this.changeListener = function(e) { + var cursor = this.editor.selection.lead; + if (cursor.row != this.base.row || cursor.column < this.base.column) { + this.detach(); + } + if (this.activated) + this.changeTimer.schedule(); + else + this.detach(); + }; + + this.blurListener = function(e) { + var el = document.activeElement; + var text = this.editor.textInput.getElement(); + var fromTooltip = e.relatedTarget && this.tooltipNode && this.tooltipNode.contains(e.relatedTarget); + var container = this.popup && this.popup.container; + if (el != text && el.parentNode != container && !fromTooltip + && el != this.tooltipNode && e.relatedTarget != text + ) { + this.detach(); + } + }; + + this.mousedownListener = function(e) { + this.detach(); + }; + + this.mousewheelListener = function(e) { + this.detach(); + }; + + this.goTo = function(where) { + var row = this.popup.getRow(); + var max = this.popup.session.getLength() - 1; + + switch(where) { + case "up": row = row <= 0 ? max : row - 1; break; + case "down": row = row >= max ? -1 : row + 1; break; + case "start": row = 0; break; + case "end": row = max; break; + } + + this.popup.setRow(row); + }; + + this.insertMatch = function(data, options) { + if (!data) + data = this.popup.getData(this.popup.getRow()); + if (!data) + return false; + + if (data.completer && data.completer.insertMatch) { + data.completer.insertMatch(this.editor, data); + } else { + if (this.completions.filterText) { + var ranges = this.editor.selection.getAllRanges(); + for (var i = 0, range; range = ranges[i]; i++) { + range.start.column -= this.completions.filterText.length; + this.editor.session.remove(range); + } + } + if (data.snippet) + snippetManager.insertSnippet(this.editor, data.snippet); + else + this.editor.execCommand("insertstring", data.value || data); + } + this.detach(); + }; + + + this.commands = { + "Up": function(editor) { editor.completer.goTo("up"); }, + "Down": function(editor) { editor.completer.goTo("down"); }, + "Ctrl-Up|Ctrl-Home": function(editor) { editor.completer.goTo("start"); }, + "Ctrl-Down|Ctrl-End": function(editor) { editor.completer.goTo("end"); }, + + "Esc": function(editor) { editor.completer.detach(); }, + "Return": function(editor) { return editor.completer.insertMatch(); }, + "Shift-Return": function(editor) { editor.completer.insertMatch(null, {deleteSuffix: true}); }, + "Tab": function(editor) { + var result = editor.completer.insertMatch(); + if (!result && !editor.tabstopManager) + editor.completer.goTo("down"); + else + return result; + }, + + "PageUp": function(editor) { editor.completer.popup.gotoPageUp(); }, + "PageDown": function(editor) { editor.completer.popup.gotoPageDown(); } + }; + + this.gatherCompletions = function(editor, callback) { + var session = editor.getSession(); + var pos = editor.getCursorPosition(); + + var prefix = util.getCompletionPrefix(editor); + + this.base = session.doc.createAnchor(pos.row, pos.column - prefix.length); + this.base.$insertRight = true; + + var matches = []; + var total = editor.completers.length; + editor.completers.forEach(function(completer, i) { + completer.getCompletions(editor, session, pos, prefix, function(err, results) { + if (!err && results) + matches = matches.concat(results); + callback(null, { + prefix: util.getCompletionPrefix(editor), + matches: matches, + finished: (--total === 0) + }); + }); + }); + return true; + }; + + this.showPopup = function(editor) { + if (this.editor) + this.detach(); + + this.activated = true; + + this.editor = editor; + if (editor.completer != this) { + if (editor.completer) + editor.completer.detach(); + editor.completer = this; + } + + editor.on("changeSelection", this.changeListener); + editor.on("blur", this.blurListener); + editor.on("mousedown", this.mousedownListener); + editor.on("mousewheel", this.mousewheelListener); + + this.updateCompletions(); + }; + + this.updateCompletions = function(keepPopupPosition) { + if (keepPopupPosition && this.base && this.completions) { + var pos = this.editor.getCursorPosition(); + var prefix = this.editor.session.getTextRange({start: this.base, end: pos}); + if (prefix == this.completions.filterText) + return; + this.completions.setFilter(prefix); + if (!this.completions.filtered.length) + return this.detach(); + if (this.completions.filtered.length == 1 + && this.completions.filtered[0].value == prefix + && !this.completions.filtered[0].snippet) + return this.detach(); + this.openPopup(this.editor, prefix, keepPopupPosition); + return; + } + var _id = this.gatherCompletionsId; + this.gatherCompletions(this.editor, function(err, results) { + var detachIfFinished = function() { + if (!results.finished) return; + return this.detach(); + }.bind(this); + + var prefix = results.prefix; + var matches = results && results.matches; + + if (!matches || !matches.length) + return detachIfFinished(); + if (prefix.indexOf(results.prefix) !== 0 || _id != this.gatherCompletionsId) + return; + + this.completions = new FilteredList(matches); + + if (this.exactMatch) + this.completions.exactMatch = true; + + this.completions.setFilter(prefix); + var filtered = this.completions.filtered; + if (!filtered.length) + return detachIfFinished(); + if (filtered.length == 1 && filtered[0].value == prefix && !filtered[0].snippet) + return detachIfFinished(); + if (this.autoInsert && filtered.length == 1 && results.finished) + return this.insertMatch(filtered[0]); + + this.openPopup(this.editor, prefix, keepPopupPosition); + }.bind(this)); + }; + + this.cancelContextMenu = function() { + this.editor.$mouseHandler.cancelContextMenu(); + }; + + this.updateDocTooltip = function() { + var popup = this.popup; + var all = popup.data; + var selected = all && (all[popup.getHoveredRow()] || all[popup.getRow()]); + var doc = null; + if (!selected || !this.editor || !this.popup.isOpen) + return this.hideDocTooltip(); + this.editor.completers.some(function(completer) { + if (completer.getDocTooltip) + doc = completer.getDocTooltip(selected); + return doc; + }); + if (!doc) + doc = selected; + + if (typeof doc == "string") + doc = {docText: doc}; + if (!doc || !(doc.docHTML || doc.docText)) + return this.hideDocTooltip(); + this.showDocTooltip(doc); + }; + + this.showDocTooltip = function(item) { + if (!this.tooltipNode) { + this.tooltipNode = dom.createElement("div"); + this.tooltipNode.className = "ace_tooltip ace_doc-tooltip"; + this.tooltipNode.style.margin = 0; + this.tooltipNode.style.pointerEvents = "auto"; + this.tooltipNode.tabIndex = -1; + this.tooltipNode.onblur = this.blurListener.bind(this); + this.tooltipNode.onclick = this.onTooltipClick.bind(this); + } + + var tooltipNode = this.tooltipNode; + if (item.docHTML) { + tooltipNode.innerHTML = item.docHTML; + } else if (item.docText) { + tooltipNode.textContent = item.docText; + } + + if (!tooltipNode.parentNode) + document.body.appendChild(tooltipNode); + var popup = this.popup; + var rect = popup.container.getBoundingClientRect(); + tooltipNode.style.top = popup.container.style.top; + tooltipNode.style.bottom = popup.container.style.bottom; + + if (window.innerWidth - rect.right < 320) { + tooltipNode.style.right = window.innerWidth - rect.left + "px"; + tooltipNode.style.left = ""; + } else { + tooltipNode.style.left = (rect.right + 1) + "px"; + tooltipNode.style.right = ""; + } + tooltipNode.style.display = "block"; + }; + + this.hideDocTooltip = function() { + this.tooltipTimer.cancel(); + if (!this.tooltipNode) return; + var el = this.tooltipNode; + if (!this.editor.isFocused() && document.activeElement == el) + this.editor.focus(); + this.tooltipNode = null; + if (el.parentNode) + el.parentNode.removeChild(el); + }; + + this.onTooltipClick = function(e) { + var a = e.target; + while (a && a != this.tooltipNode) { + if (a.nodeName == "A" && a.href) { + a.rel = "noreferrer"; + a.target = "_blank"; + break; + } + a = a.parentNode; + } + }; + +}).call(Autocomplete.prototype); + +Autocomplete.startCommand = { + name: "startAutocomplete", + exec: function(editor) { + if (!editor.completer) + editor.completer = new Autocomplete(); + editor.completer.autoInsert = false; + editor.completer.autoSelect = true; + editor.completer.showPopup(editor); + editor.completer.cancelContextMenu(); + }, + bindKey: "Ctrl-Space|Ctrl-Shift-Space|Alt-Space" +}; + +var FilteredList = function(array, filterText) { + this.all = array; + this.filtered = array; + this.filterText = filterText || ""; + this.exactMatch = false; +}; +(function(){ + this.setFilter = function(str) { + if (str.length > this.filterText && str.lastIndexOf(this.filterText, 0) === 0) + var matches = this.filtered; + else + var matches = this.all; + + this.filterText = str; + matches = this.filterCompletions(matches, this.filterText); + matches = matches.sort(function(a, b) { + return b.exactMatch - a.exactMatch || b.score - a.score; + }); + var prev = null; + matches = matches.filter(function(item){ + var caption = item.snippet || item.caption || item.value; + if (caption === prev) return false; + prev = caption; + return true; + }); + + this.filtered = matches; + }; + this.filterCompletions = function(items, needle) { + var results = []; + var upper = needle.toUpperCase(); + var lower = needle.toLowerCase(); + loop: for (var i = 0, item; item = items[i]; i++) { + var caption = item.value || item.caption || item.snippet; + if (!caption) continue; + var lastIndex = -1; + var matchMask = 0; + var penalty = 0; + var index, distance; + + if (this.exactMatch) { + if (needle !== caption.substr(0, needle.length)) + continue loop; + }else{ + for (var j = 0; j < needle.length; j++) { + var i1 = caption.indexOf(lower[j], lastIndex + 1); + var i2 = caption.indexOf(upper[j], lastIndex + 1); + index = (i1 >= 0) ? ((i2 < 0 || i1 < i2) ? i1 : i2) : i2; + if (index < 0) + continue loop; + distance = index - lastIndex - 1; + if (distance > 0) { + if (lastIndex === -1) + penalty += 10; + penalty += distance; + } + matchMask = matchMask | (1 << index); + lastIndex = index; + } + } + item.matchMask = matchMask; + item.exactMatch = penalty ? 0 : 1; + item.score = (item.score || 0) - penalty; + results.push(item); + } + return results; + }; +}).call(FilteredList.prototype); + +exports.Autocomplete = Autocomplete; +exports.FilteredList = FilteredList; + +}); + +ace.define("ace/autocomplete/text_completer",["require","exports","module","ace/range"], function(acequire, exports, module) { + var Range = acequire("../range").Range; + + var splitRegex = /[^a-zA-Z_0-9\$\-\u00C0-\u1FFF\u2C00-\uD7FF\w]+/; + + function getWordIndex(doc, pos) { + var textBefore = doc.getTextRange(Range.fromPoints({row: 0, column:0}, pos)); + return textBefore.split(splitRegex).length - 1; + } + function wordDistance(doc, pos) { + var prefixPos = getWordIndex(doc, pos); + var words = doc.getValue().split(splitRegex); + var wordScores = Object.create(null); + + var currentWord = words[prefixPos]; + + words.forEach(function(word, idx) { + if (!word || word === currentWord) return; + + var distance = Math.abs(prefixPos - idx); + var score = words.length - distance; + if (wordScores[word]) { + wordScores[word] = Math.max(score, wordScores[word]); + } else { + wordScores[word] = score; + } + }); + return wordScores; + } + + exports.getCompletions = function(editor, session, pos, prefix, callback) { + var wordScore = wordDistance(session, pos, prefix); + var wordList = Object.keys(wordScore); + callback(null, wordList.map(function(word) { + return { + caption: word, + value: word, + score: wordScore[word], + meta: "local" + }; + })); + }; +}); + +ace.define("ace/ext/language_tools",["require","exports","module","ace/snippets","ace/autocomplete","ace/config","ace/lib/lang","ace/autocomplete/util","ace/autocomplete/text_completer","ace/editor","ace/config"], function(acequire, exports, module) { +"use strict"; + +var snippetManager = acequire("../snippets").snippetManager; +var Autocomplete = acequire("../autocomplete").Autocomplete; +var config = acequire("../config"); +var lang = acequire("../lib/lang"); +var util = acequire("../autocomplete/util"); + +var textCompleter = acequire("../autocomplete/text_completer"); +var keyWordCompleter = { + getCompletions: function(editor, session, pos, prefix, callback) { + if (session.$mode.completer) { + return session.$mode.completer.getCompletions(editor, session, pos, prefix, callback); + } + var state = editor.session.getState(pos.row); + var completions = session.$mode.getCompletions(state, session, pos, prefix); + callback(null, completions); + } +}; + +var snippetCompleter = { + getCompletions: function(editor, session, pos, prefix, callback) { + var snippetMap = snippetManager.snippetMap; + var completions = []; + snippetManager.getActiveScopes(editor).forEach(function(scope) { + var snippets = snippetMap[scope] || []; + for (var i = snippets.length; i--;) { + var s = snippets[i]; + var caption = s.name || s.tabTrigger; + if (!caption) + continue; + completions.push({ + caption: caption, + snippet: s.content, + meta: s.tabTrigger && !s.name ? s.tabTrigger + "\u21E5 " : "snippet", + type: "snippet" + }); + } + }, this); + callback(null, completions); + }, + getDocTooltip: function(item) { + if (item.type == "snippet" && !item.docHTML) { + item.docHTML = [ + "", lang.escapeHTML(item.caption), "", "
", + lang.escapeHTML(item.snippet) + ].join(""); + } + } +}; + +var completers = [snippetCompleter, textCompleter, keyWordCompleter]; +exports.setCompleters = function(val) { + completers.length = 0; + if (val) completers.push.apply(completers, val); +}; +exports.addCompleter = function(completer) { + completers.push(completer); +}; +exports.textCompleter = textCompleter; +exports.keyWordCompleter = keyWordCompleter; +exports.snippetCompleter = snippetCompleter; + +var expandSnippet = { + name: "expandSnippet", + exec: function(editor) { + return snippetManager.expandWithTab(editor); + }, + bindKey: "Tab" +}; + +var onChangeMode = function(e, editor) { + loadSnippetsForMode(editor.session.$mode); +}; + +var loadSnippetsForMode = function(mode) { + var id = mode.$id; + if (!snippetManager.files) + snippetManager.files = {}; + loadSnippetFile(id); + if (mode.modes) + mode.modes.forEach(loadSnippetsForMode); +}; + +var loadSnippetFile = function(id) { + if (!id || snippetManager.files[id]) + return; + var snippetFilePath = id.replace("mode", "snippets"); + snippetManager.files[id] = {}; + config.loadModule(snippetFilePath, function(m) { + if (m) { + snippetManager.files[id] = m; + if (!m.snippets && m.snippetText) + m.snippets = snippetManager.parseSnippetFile(m.snippetText); + snippetManager.register(m.snippets || [], m.scope); + if (m.includeScopes) { + snippetManager.snippetMap[m.scope].includeScopes = m.includeScopes; + m.includeScopes.forEach(function(x) { + loadSnippetFile("ace/mode/" + x); + }); + } + } + }); +}; + +var doLiveAutocomplete = function(e) { + var editor = e.editor; + var hasCompleter = editor.completer && editor.completer.activated; + if (e.command.name === "backspace") { + if (hasCompleter && !util.getCompletionPrefix(editor)) + editor.completer.detach(); + } + else if (e.command.name === "insertstring") { + var prefix = util.getCompletionPrefix(editor); + if (prefix && !hasCompleter) { + if (!editor.completer) { + editor.completer = new Autocomplete(); + } + editor.completer.autoInsert = false; + editor.completer.showPopup(editor); + } + } +}; + +var Editor = acequire("../editor").Editor; +acequire("../config").defineOptions(Editor.prototype, "editor", { + enableBasicAutocompletion: { + set: function(val) { + if (val) { + if (!this.completers) + this.completers = Array.isArray(val)? val: completers; + this.commands.addCommand(Autocomplete.startCommand); + } else { + this.commands.removeCommand(Autocomplete.startCommand); + } + }, + value: false + }, + enableLiveAutocompletion: { + set: function(val) { + if (val) { + if (!this.completers) + this.completers = Array.isArray(val)? val: completers; + this.commands.on('afterExec', doLiveAutocomplete); + } else { + this.commands.removeListener('afterExec', doLiveAutocomplete); + } + }, + value: false + }, + enableSnippets: { + set: function(val) { + if (val) { + this.commands.addCommand(expandSnippet); + this.on("changeMode", onChangeMode); + onChangeMode(null, this); + } else { + this.commands.removeCommand(expandSnippet); + this.off("changeMode", onChangeMode); + } + }, + value: false + } +}); +}); + (function() { + ace.acequire(["ace/ext/language_tools"], function() {}); + })(); + \ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/node_modules/brace/index.js b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/node_modules/brace/index.js new file mode 100644 index 0000000..5999cf6 --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/node_modules/brace/index.js @@ -0,0 +1,20272 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Distributed under the BSD license: + * + * Copyright (c) 2010, Ajax.org B.V. + * 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 Ajax.org B.V. 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 AJAX.ORG B.V. 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. + * + * ***** END LICENSE BLOCK ***** */ + +/** + * Define a module along with a payload + * @param module a name for the payload + * @param payload a function to call with (acequire, exports, module) params + */ + +(function() { + +var ACE_NAMESPACE = "ace"; + +var global = (function() { return this; })(); +if (!global && typeof window != "undefined") global = window; // strict mode + + +if (!ACE_NAMESPACE && typeof acequirejs !== "undefined") + return; + + +var define = function(module, deps, payload) { + if (typeof module !== "string") { + if (define.original) + define.original.apply(this, arguments); + else { + console.error("dropping module because define wasn\'t a string."); + console.trace(); + } + return; + } + if (arguments.length == 2) + payload = deps; + if (!define.modules[module]) { + define.payloads[module] = payload; + define.modules[module] = null; + } +}; + +define.modules = {}; +define.payloads = {}; + +/** + * Get at functionality define()ed using the function above + */ +var _acequire = function(parentId, module, callback) { + if (typeof module === "string") { + var payload = lookup(parentId, module); + if (payload != undefined) { + callback && callback(); + return payload; + } + } else if (Object.prototype.toString.call(module) === "[object Array]") { + var params = []; + for (var i = 0, l = module.length; i < l; ++i) { + var dep = lookup(parentId, module[i]); + if (dep == undefined && acequire.original) + return; + params.push(dep); + } + return callback && callback.apply(null, params) || true; + } +}; + +var acequire = function(module, callback) { + var packagedModule = _acequire("", module, callback); + if (packagedModule == undefined && acequire.original) + return acequire.original.apply(this, arguments); + return packagedModule; +}; + +var normalizeModule = function(parentId, moduleName) { + // normalize plugin acequires + if (moduleName.indexOf("!") !== -1) { + var chunks = moduleName.split("!"); + return normalizeModule(parentId, chunks[0]) + "!" + normalizeModule(parentId, chunks[1]); + } + // normalize relative acequires + if (moduleName.charAt(0) == ".") { + var base = parentId.split("/").slice(0, -1).join("/"); + moduleName = base + "/" + moduleName; + + while(moduleName.indexOf(".") !== -1 && previous != moduleName) { + var previous = moduleName; + moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); + } + } + return moduleName; +}; + +/** + * Internal function to lookup moduleNames and resolve them by calling the + * definition function if needed. + */ +var lookup = function(parentId, moduleName) { + moduleName = normalizeModule(parentId, moduleName); + + var module = define.modules[moduleName]; + if (!module) { + module = define.payloads[moduleName]; + if (typeof module === 'function') { + var exports = {}; + var mod = { + id: moduleName, + uri: '', + exports: exports, + packaged: true + }; + + var req = function(module, callback) { + return _acequire(moduleName, module, callback); + }; + + var returnValue = module(req, exports, mod); + exports = returnValue || mod.exports; + define.modules[moduleName] = exports; + delete define.payloads[moduleName]; + } + module = define.modules[moduleName] = exports || module; + } + return module; +}; + +function exportAce(ns) { + var root = global; + if (ns) { + if (!global[ns]) + global[ns] = {}; + root = global[ns]; + } + + if (!root.define || !root.define.packaged) { + define.original = root.define; + root.define = define; + root.define.packaged = true; + } + + if (!root.acequire || !root.acequire.packaged) { + acequire.original = root.acequire; + root.acequire = acequire; + root.acequire.packaged = true; + } +} + +exportAce(ACE_NAMESPACE); + +})(); + +ace.define("ace/lib/regexp",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + + var real = { + exec: RegExp.prototype.exec, + test: RegExp.prototype.test, + match: String.prototype.match, + replace: String.prototype.replace, + split: String.prototype.split + }, + compliantExecNpcg = real.exec.call(/()??/, "")[1] === undefined, // check `exec` handling of nonparticipating capturing groups + compliantLastIndexIncrement = function () { + var x = /^/g; + real.test.call(x, ""); + return !x.lastIndex; + }(); + + if (compliantLastIndexIncrement && compliantExecNpcg) + return; + RegExp.prototype.exec = function (str) { + var match = real.exec.apply(this, arguments), + name, r2; + if ( typeof(str) == 'string' && match) { + if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) { + r2 = RegExp(this.source, real.replace.call(getNativeFlags(this), "g", "")); + real.replace.call(str.slice(match.index), r2, function () { + for (var i = 1; i < arguments.length - 2; i++) { + if (arguments[i] === undefined) + match[i] = undefined; + } + }); + } + if (this._xregexp && this._xregexp.captureNames) { + for (var i = 1; i < match.length; i++) { + name = this._xregexp.captureNames[i - 1]; + if (name) + match[name] = match[i]; + } + } + if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index)) + this.lastIndex--; + } + return match; + }; + if (!compliantLastIndexIncrement) { + RegExp.prototype.test = function (str) { + var match = real.exec.call(this, str); + if (match && this.global && !match[0].length && (this.lastIndex > match.index)) + this.lastIndex--; + return !!match; + }; + } + + function getNativeFlags (regex) { + return (regex.global ? "g" : "") + + (regex.ignoreCase ? "i" : "") + + (regex.multiline ? "m" : "") + + (regex.extended ? "x" : "") + // Proposed for ES4; included in AS3 + (regex.sticky ? "y" : ""); + } + + function indexOf (array, item, from) { + if (Array.prototype.indexOf) // Use the native array method if available + return array.indexOf(item, from); + for (var i = from || 0; i < array.length; i++) { + if (array[i] === item) + return i; + } + return -1; + } + +}); + +ace.define("ace/lib/es5-shim",["require","exports","module"], function(acequire, exports, module) { + +function Empty() {} + +if (!Function.prototype.bind) { + Function.prototype.bind = function bind(that) { // .length is 1 + var target = this; + if (typeof target != "function") { + throw new TypeError("Function.prototype.bind called on incompatible " + target); + } + var args = slice.call(arguments, 1); // for normal call + var bound = function () { + + if (this instanceof bound) { + + var result = target.apply( + this, + args.concat(slice.call(arguments)) + ); + if (Object(result) === result) { + return result; + } + return this; + + } else { + return target.apply( + that, + args.concat(slice.call(arguments)) + ); + + } + + }; + if(target.prototype) { + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + return bound; + }; +} +var call = Function.prototype.call; +var prototypeOfArray = Array.prototype; +var prototypeOfObject = Object.prototype; +var slice = prototypeOfArray.slice; +var _toString = call.bind(prototypeOfObject.toString); +var owns = call.bind(prototypeOfObject.hasOwnProperty); +var defineGetter; +var defineSetter; +var lookupGetter; +var lookupSetter; +var supportsAccessors; +if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) { + defineGetter = call.bind(prototypeOfObject.__defineGetter__); + defineSetter = call.bind(prototypeOfObject.__defineSetter__); + lookupGetter = call.bind(prototypeOfObject.__lookupGetter__); + lookupSetter = call.bind(prototypeOfObject.__lookupSetter__); +} +if ([1,2].splice(0).length != 2) { + if(function() { // test IE < 9 to splice bug - see issue #138 + function makeArray(l) { + var a = new Array(l+2); + a[0] = a[1] = 0; + return a; + } + var array = [], lengthBefore; + + array.splice.apply(array, makeArray(20)); + array.splice.apply(array, makeArray(26)); + + lengthBefore = array.length; //46 + array.splice(5, 0, "XXX"); // add one element + + lengthBefore + 1 == array.length + + if (lengthBefore + 1 == array.length) { + return true;// has right splice implementation without bugs + } + }()) {//IE 6/7 + var array_splice = Array.prototype.splice; + Array.prototype.splice = function(start, deleteCount) { + if (!arguments.length) { + return []; + } else { + return array_splice.apply(this, [ + start === void 0 ? 0 : start, + deleteCount === void 0 ? (this.length - start) : deleteCount + ].concat(slice.call(arguments, 2))) + } + }; + } else {//IE8 + Array.prototype.splice = function(pos, removeCount){ + var length = this.length; + if (pos > 0) { + if (pos > length) + pos = length; + } else if (pos == void 0) { + pos = 0; + } else if (pos < 0) { + pos = Math.max(length + pos, 0); + } + + if (!(pos+removeCount < length)) + removeCount = length - pos; + + var removed = this.slice(pos, pos+removeCount); + var insert = slice.call(arguments, 2); + var add = insert.length; + if (pos === length) { + if (add) { + this.push.apply(this, insert); + } + } else { + var remove = Math.min(removeCount, length - pos); + var tailOldPos = pos + remove; + var tailNewPos = tailOldPos + add - remove; + var tailCount = length - tailOldPos; + var lengthAfterRemove = length - remove; + + if (tailNewPos < tailOldPos) { // case A + for (var i = 0; i < tailCount; ++i) { + this[tailNewPos+i] = this[tailOldPos+i]; + } + } else if (tailNewPos > tailOldPos) { // case B + for (i = tailCount; i--; ) { + this[tailNewPos+i] = this[tailOldPos+i]; + } + } // else, add == remove (nothing to do) + + if (add && pos === lengthAfterRemove) { + this.length = lengthAfterRemove; // truncate array + this.push.apply(this, insert); + } else { + this.length = lengthAfterRemove + add; // reserves space + for (i = 0; i < add; ++i) { + this[pos+i] = insert[i]; + } + } + } + return removed; + }; + } +} +if (!Array.isArray) { + Array.isArray = function isArray(obj) { + return _toString(obj) == "[object Array]"; + }; +} +var boxedString = Object("a"), + splitString = boxedString[0] != "a" || !(0 in boxedString); + +if (!Array.prototype.forEach) { + Array.prototype.forEach = function forEach(fun /*, thisp*/) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + thisp = arguments[1], + i = -1, + length = self.length >>> 0; + if (_toString(fun) != "[object Function]") { + throw new TypeError(); // TODO message + } + + while (++i < length) { + if (i in self) { + fun.call(thisp, self[i], i, object); + } + } + }; +} +if (!Array.prototype.map) { + Array.prototype.map = function map(fun /*, thisp*/) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0, + result = Array(length), + thisp = arguments[1]; + if (_toString(fun) != "[object Function]") { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self) + result[i] = fun.call(thisp, self[i], i, object); + } + return result; + }; +} +if (!Array.prototype.filter) { + Array.prototype.filter = function filter(fun /*, thisp */) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0, + result = [], + value, + thisp = arguments[1]; + if (_toString(fun) != "[object Function]") { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self) { + value = self[i]; + if (fun.call(thisp, value, i, object)) { + result.push(value); + } + } + } + return result; + }; +} +if (!Array.prototype.every) { + Array.prototype.every = function every(fun /*, thisp */) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0, + thisp = arguments[1]; + if (_toString(fun) != "[object Function]") { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self && !fun.call(thisp, self[i], i, object)) { + return false; + } + } + return true; + }; +} +if (!Array.prototype.some) { + Array.prototype.some = function some(fun /*, thisp */) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0, + thisp = arguments[1]; + if (_toString(fun) != "[object Function]") { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self && fun.call(thisp, self[i], i, object)) { + return true; + } + } + return false; + }; +} +if (!Array.prototype.reduce) { + Array.prototype.reduce = function reduce(fun /*, initial*/) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0; + if (_toString(fun) != "[object Function]") { + throw new TypeError(fun + " is not a function"); + } + if (!length && arguments.length == 1) { + throw new TypeError("reduce of empty array with no initial value"); + } + + var i = 0; + var result; + if (arguments.length >= 2) { + result = arguments[1]; + } else { + do { + if (i in self) { + result = self[i++]; + break; + } + if (++i >= length) { + throw new TypeError("reduce of empty array with no initial value"); + } + } while (true); + } + + for (; i < length; i++) { + if (i in self) { + result = fun.call(void 0, result, self[i], i, object); + } + } + + return result; + }; +} +if (!Array.prototype.reduceRight) { + Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0; + if (_toString(fun) != "[object Function]") { + throw new TypeError(fun + " is not a function"); + } + if (!length && arguments.length == 1) { + throw new TypeError("reduceRight of empty array with no initial value"); + } + + var result, i = length - 1; + if (arguments.length >= 2) { + result = arguments[1]; + } else { + do { + if (i in self) { + result = self[i--]; + break; + } + if (--i < 0) { + throw new TypeError("reduceRight of empty array with no initial value"); + } + } while (true); + } + + do { + if (i in this) { + result = fun.call(void 0, result, self[i], i, object); + } + } while (i--); + + return result; + }; +} +if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) { + Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { + var self = splitString && _toString(this) == "[object String]" ? + this.split("") : + toObject(this), + length = self.length >>> 0; + + if (!length) { + return -1; + } + + var i = 0; + if (arguments.length > 1) { + i = toInteger(arguments[1]); + } + i = i >= 0 ? i : Math.max(0, length + i); + for (; i < length; i++) { + if (i in self && self[i] === sought) { + return i; + } + } + return -1; + }; +} +if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) { + Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { + var self = splitString && _toString(this) == "[object String]" ? + this.split("") : + toObject(this), + length = self.length >>> 0; + + if (!length) { + return -1; + } + var i = length - 1; + if (arguments.length > 1) { + i = Math.min(i, toInteger(arguments[1])); + } + i = i >= 0 ? i : length - Math.abs(i); + for (; i >= 0; i--) { + if (i in self && sought === self[i]) { + return i; + } + } + return -1; + }; +} +if (!Object.getPrototypeOf) { + Object.getPrototypeOf = function getPrototypeOf(object) { + return object.__proto__ || ( + object.constructor ? + object.constructor.prototype : + prototypeOfObject + ); + }; +} +if (!Object.getOwnPropertyDescriptor) { + var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " + + "non-object: "; + Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) { + if ((typeof object != "object" && typeof object != "function") || object === null) + throw new TypeError(ERR_NON_OBJECT + object); + if (!owns(object, property)) + return; + + var descriptor, getter, setter; + descriptor = { enumerable: true, configurable: true }; + if (supportsAccessors) { + var prototype = object.__proto__; + object.__proto__ = prototypeOfObject; + + var getter = lookupGetter(object, property); + var setter = lookupSetter(object, property); + object.__proto__ = prototype; + + if (getter || setter) { + if (getter) descriptor.get = getter; + if (setter) descriptor.set = setter; + return descriptor; + } + } + descriptor.value = object[property]; + return descriptor; + }; +} +if (!Object.getOwnPropertyNames) { + Object.getOwnPropertyNames = function getOwnPropertyNames(object) { + return Object.keys(object); + }; +} +if (!Object.create) { + var createEmpty; + if (Object.prototype.__proto__ === null) { + createEmpty = function () { + return { "__proto__": null }; + }; + } else { + createEmpty = function () { + var empty = {}; + for (var i in empty) + empty[i] = null; + empty.constructor = + empty.hasOwnProperty = + empty.propertyIsEnumerable = + empty.isPrototypeOf = + empty.toLocaleString = + empty.toString = + empty.valueOf = + empty.__proto__ = null; + return empty; + } + } + + Object.create = function create(prototype, properties) { + var object; + if (prototype === null) { + object = createEmpty(); + } else { + if (typeof prototype != "object") + throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); + var Type = function () {}; + Type.prototype = prototype; + object = new Type(); + object.__proto__ = prototype; + } + if (properties !== void 0) + Object.defineProperties(object, properties); + return object; + }; +} + +function doesDefinePropertyWork(object) { + try { + Object.defineProperty(object, "sentinel", {}); + return "sentinel" in object; + } catch (exception) { + } +} +if (Object.defineProperty) { + var definePropertyWorksOnObject = doesDefinePropertyWork({}); + var definePropertyWorksOnDom = typeof document == "undefined" || + doesDefinePropertyWork(document.createElement("div")); + if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) { + var definePropertyFallback = Object.defineProperty; + } +} + +if (!Object.defineProperty || definePropertyFallback) { + var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: "; + var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: " + var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " + + "on this javascript engine"; + + Object.defineProperty = function defineProperty(object, property, descriptor) { + if ((typeof object != "object" && typeof object != "function") || object === null) + throw new TypeError(ERR_NON_OBJECT_TARGET + object); + if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) + throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor); + if (definePropertyFallback) { + try { + return definePropertyFallback.call(Object, object, property, descriptor); + } catch (exception) { + } + } + if (owns(descriptor, "value")) { + + if (supportsAccessors && (lookupGetter(object, property) || + lookupSetter(object, property))) + { + var prototype = object.__proto__; + object.__proto__ = prototypeOfObject; + delete object[property]; + object[property] = descriptor.value; + object.__proto__ = prototype; + } else { + object[property] = descriptor.value; + } + } else { + if (!supportsAccessors) + throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); + if (owns(descriptor, "get")) + defineGetter(object, property, descriptor.get); + if (owns(descriptor, "set")) + defineSetter(object, property, descriptor.set); + } + + return object; + }; +} +if (!Object.defineProperties) { + Object.defineProperties = function defineProperties(object, properties) { + for (var property in properties) { + if (owns(properties, property)) + Object.defineProperty(object, property, properties[property]); + } + return object; + }; +} +if (!Object.seal) { + Object.seal = function seal(object) { + return object; + }; +} +if (!Object.freeze) { + Object.freeze = function freeze(object) { + return object; + }; +} +try { + Object.freeze(function () {}); +} catch (exception) { + Object.freeze = (function freeze(freezeObject) { + return function freeze(object) { + if (typeof object == "function") { + return object; + } else { + return freezeObject(object); + } + }; + })(Object.freeze); +} +if (!Object.preventExtensions) { + Object.preventExtensions = function preventExtensions(object) { + return object; + }; +} +if (!Object.isSealed) { + Object.isSealed = function isSealed(object) { + return false; + }; +} +if (!Object.isFrozen) { + Object.isFrozen = function isFrozen(object) { + return false; + }; +} +if (!Object.isExtensible) { + Object.isExtensible = function isExtensible(object) { + if (Object(object) === object) { + throw new TypeError(); // TODO message + } + var name = ''; + while (owns(object, name)) { + name += '?'; + } + object[name] = true; + var returnValue = owns(object, name); + delete object[name]; + return returnValue; + }; +} +if (!Object.keys) { + var hasDontEnumBug = true, + dontEnums = [ + "toString", + "toLocaleString", + "valueOf", + "hasOwnProperty", + "isPrototypeOf", + "propertyIsEnumerable", + "constructor" + ], + dontEnumsLength = dontEnums.length; + + for (var key in {"toString": null}) { + hasDontEnumBug = false; + } + + Object.keys = function keys(object) { + + if ( + (typeof object != "object" && typeof object != "function") || + object === null + ) { + throw new TypeError("Object.keys called on a non-object"); + } + + var keys = []; + for (var name in object) { + if (owns(object, name)) { + keys.push(name); + } + } + + if (hasDontEnumBug) { + for (var i = 0, ii = dontEnumsLength; i < ii; i++) { + var dontEnum = dontEnums[i]; + if (owns(object, dontEnum)) { + keys.push(dontEnum); + } + } + } + return keys; + }; + +} +if (!Date.now) { + Date.now = function now() { + return new Date().getTime(); + }; +} +var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + + "\u2029\uFEFF"; +if (!String.prototype.trim || ws.trim()) { + ws = "[" + ws + "]"; + var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), + trimEndRegexp = new RegExp(ws + ws + "*$"); + String.prototype.trim = function trim() { + return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, ""); + }; +} + +function toInteger(n) { + n = +n; + if (n !== n) { // isNaN + n = 0; + } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) { + n = (n > 0 || -1) * Math.floor(Math.abs(n)); + } + return n; +} + +function isPrimitive(input) { + var type = typeof input; + return ( + input === null || + type === "undefined" || + type === "boolean" || + type === "number" || + type === "string" + ); +} + +function toPrimitive(input) { + var val, valueOf, toString; + if (isPrimitive(input)) { + return input; + } + valueOf = input.valueOf; + if (typeof valueOf === "function") { + val = valueOf.call(input); + if (isPrimitive(val)) { + return val; + } + } + toString = input.toString; + if (typeof toString === "function") { + val = toString.call(input); + if (isPrimitive(val)) { + return val; + } + } + throw new TypeError(); +} +var toObject = function (o) { + if (o == null) { // this matches both null and undefined + throw new TypeError("can't convert "+o+" to object"); + } + return Object(o); +}; + +}); + +ace.define("ace/lib/fixoldbrowsers",["require","exports","module","ace/lib/regexp","ace/lib/es5-shim"], function(acequire, exports, module) { +"use strict"; + +acequire("./regexp"); +acequire("./es5-shim"); + +}); + +ace.define("ace/lib/dom",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +var XHTML_NS = "http://www.w3.org/1999/xhtml"; + +exports.getDocumentHead = function(doc) { + if (!doc) + doc = document; + return doc.head || doc.getElementsByTagName("head")[0] || doc.documentElement; +}; + +exports.createElement = function(tag, ns) { + return document.createElementNS ? + document.createElementNS(ns || XHTML_NS, tag) : + document.createElement(tag); +}; + +exports.hasCssClass = function(el, name) { + var classes = (el.className + "").split(/\s+/g); + return classes.indexOf(name) !== -1; +}; +exports.addCssClass = function(el, name) { + if (!exports.hasCssClass(el, name)) { + el.className += " " + name; + } +}; +exports.removeCssClass = function(el, name) { + var classes = el.className.split(/\s+/g); + while (true) { + var index = classes.indexOf(name); + if (index == -1) { + break; + } + classes.splice(index, 1); + } + el.className = classes.join(" "); +}; + +exports.toggleCssClass = function(el, name) { + var classes = el.className.split(/\s+/g), add = true; + while (true) { + var index = classes.indexOf(name); + if (index == -1) { + break; + } + add = false; + classes.splice(index, 1); + } + if (add) + classes.push(name); + + el.className = classes.join(" "); + return add; +}; +exports.setCssClass = function(node, className, include) { + if (include) { + exports.addCssClass(node, className); + } else { + exports.removeCssClass(node, className); + } +}; + +exports.hasCssString = function(id, doc) { + var index = 0, sheets; + doc = doc || document; + + if (doc.createStyleSheet && (sheets = doc.styleSheets)) { + while (index < sheets.length) + if (sheets[index++].owningElement.id === id) return true; + } else if ((sheets = doc.getElementsByTagName("style"))) { + while (index < sheets.length) + if (sheets[index++].id === id) return true; + } + + return false; +}; + +exports.importCssString = function importCssString(cssText, id, doc) { + doc = doc || document; + if (id && exports.hasCssString(id, doc)) + return null; + + var style; + + if (id) + cssText += "\n/*# sourceURL=ace/css/" + id + " */"; + + if (doc.createStyleSheet) { + style = doc.createStyleSheet(); + style.cssText = cssText; + if (id) + style.owningElement.id = id; + } else { + style = exports.createElement("style"); + style.appendChild(doc.createTextNode(cssText)); + if (id) + style.id = id; + + exports.getDocumentHead(doc).appendChild(style); + } +}; + +exports.importCssStylsheet = function(uri, doc) { + if (doc.createStyleSheet) { + doc.createStyleSheet(uri); + } else { + var link = exports.createElement('link'); + link.rel = 'stylesheet'; + link.href = uri; + + exports.getDocumentHead(doc).appendChild(link); + } +}; + +exports.getInnerWidth = function(element) { + return ( + parseInt(exports.computedStyle(element, "paddingLeft"), 10) + + parseInt(exports.computedStyle(element, "paddingRight"), 10) + + element.clientWidth + ); +}; + +exports.getInnerHeight = function(element) { + return ( + parseInt(exports.computedStyle(element, "paddingTop"), 10) + + parseInt(exports.computedStyle(element, "paddingBottom"), 10) + + element.clientHeight + ); +}; + +exports.scrollbarWidth = function(document) { + var inner = exports.createElement("ace_inner"); + inner.style.width = "100%"; + inner.style.minWidth = "0px"; + inner.style.height = "200px"; + inner.style.display = "block"; + + var outer = exports.createElement("ace_outer"); + var style = outer.style; + + style.position = "absolute"; + style.left = "-10000px"; + style.overflow = "hidden"; + style.width = "200px"; + style.minWidth = "0px"; + style.height = "150px"; + style.display = "block"; + + outer.appendChild(inner); + + var body = document.documentElement; + body.appendChild(outer); + + var noScrollbar = inner.offsetWidth; + + style.overflow = "scroll"; + var withScrollbar = inner.offsetWidth; + + if (noScrollbar == withScrollbar) { + withScrollbar = outer.clientWidth; + } + + body.removeChild(outer); + + return noScrollbar-withScrollbar; +}; + +if (typeof document == "undefined") { + exports.importCssString = function() {}; + return; +} + +if (window.pageYOffset !== undefined) { + exports.getPageScrollTop = function() { + return window.pageYOffset; + }; + + exports.getPageScrollLeft = function() { + return window.pageXOffset; + }; +} +else { + exports.getPageScrollTop = function() { + return document.body.scrollTop; + }; + + exports.getPageScrollLeft = function() { + return document.body.scrollLeft; + }; +} + +if (window.getComputedStyle) + exports.computedStyle = function(element, style) { + if (style) + return (window.getComputedStyle(element, "") || {})[style] || ""; + return window.getComputedStyle(element, "") || {}; + }; +else + exports.computedStyle = function(element, style) { + if (style) + return element.currentStyle[style]; + return element.currentStyle; + }; +exports.setInnerHtml = function(el, innerHtml) { + var element = el.cloneNode(false);//document.createElement("div"); + element.innerHTML = innerHtml; + el.parentNode.replaceChild(element, el); + return element; +}; + +if ("textContent" in document.documentElement) { + exports.setInnerText = function(el, innerText) { + el.textContent = innerText; + }; + + exports.getInnerText = function(el) { + return el.textContent; + }; +} +else { + exports.setInnerText = function(el, innerText) { + el.innerText = innerText; + }; + + exports.getInnerText = function(el) { + return el.innerText; + }; +} + +exports.getParentWindow = function(document) { + return document.defaultView || document.parentWindow; +}; + +}); + +ace.define("ace/lib/oop",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +exports.inherits = function(ctor, superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); +}; + +exports.mixin = function(obj, mixin) { + for (var key in mixin) { + obj[key] = mixin[key]; + } + return obj; +}; + +exports.implement = function(proto, mixin) { + exports.mixin(proto, mixin); +}; + +}); + +ace.define("ace/lib/keys",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop"], function(acequire, exports, module) { +"use strict"; + +acequire("./fixoldbrowsers"); + +var oop = acequire("./oop"); +var Keys = (function() { + var ret = { + MODIFIER_KEYS: { + 16: 'Shift', 17: 'Ctrl', 18: 'Alt', 224: 'Meta' + }, + + KEY_MODS: { + "ctrl": 1, "alt": 2, "option" : 2, "shift": 4, + "super": 8, "meta": 8, "command": 8, "cmd": 8 + }, + + FUNCTION_KEYS : { + 8 : "Backspace", + 9 : "Tab", + 13 : "Return", + 19 : "Pause", + 27 : "Esc", + 32 : "Space", + 33 : "PageUp", + 34 : "PageDown", + 35 : "End", + 36 : "Home", + 37 : "Left", + 38 : "Up", + 39 : "Right", + 40 : "Down", + 44 : "Print", + 45 : "Insert", + 46 : "Delete", + 96 : "Numpad0", + 97 : "Numpad1", + 98 : "Numpad2", + 99 : "Numpad3", + 100: "Numpad4", + 101: "Numpad5", + 102: "Numpad6", + 103: "Numpad7", + 104: "Numpad8", + 105: "Numpad9", + '-13': "NumpadEnter", + 112: "F1", + 113: "F2", + 114: "F3", + 115: "F4", + 116: "F5", + 117: "F6", + 118: "F7", + 119: "F8", + 120: "F9", + 121: "F10", + 122: "F11", + 123: "F12", + 144: "Numlock", + 145: "Scrolllock" + }, + + PRINTABLE_KEYS: { + 32: ' ', 48: '0', 49: '1', 50: '2', 51: '3', 52: '4', 53: '5', + 54: '6', 55: '7', 56: '8', 57: '9', 59: ';', 61: '=', 65: 'a', + 66: 'b', 67: 'c', 68: 'd', 69: 'e', 70: 'f', 71: 'g', 72: 'h', + 73: 'i', 74: 'j', 75: 'k', 76: 'l', 77: 'm', 78: 'n', 79: 'o', + 80: 'p', 81: 'q', 82: 'r', 83: 's', 84: 't', 85: 'u', 86: 'v', + 87: 'w', 88: 'x', 89: 'y', 90: 'z', 107: '+', 109: '-', 110: '.', + 186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`', + 219: '[', 220: '\\',221: ']', 222: "'", 111: '/', 106: '*' + } + }; + var name, i; + for (i in ret.FUNCTION_KEYS) { + name = ret.FUNCTION_KEYS[i].toLowerCase(); + ret[name] = parseInt(i, 10); + } + for (i in ret.PRINTABLE_KEYS) { + name = ret.PRINTABLE_KEYS[i].toLowerCase(); + ret[name] = parseInt(i, 10); + } + oop.mixin(ret, ret.MODIFIER_KEYS); + oop.mixin(ret, ret.PRINTABLE_KEYS); + oop.mixin(ret, ret.FUNCTION_KEYS); + ret.enter = ret["return"]; + ret.escape = ret.esc; + ret.del = ret["delete"]; + ret[173] = '-'; + + (function() { + var mods = ["cmd", "ctrl", "alt", "shift"]; + for (var i = Math.pow(2, mods.length); i--;) { + ret.KEY_MODS[i] = mods.filter(function(x) { + return i & ret.KEY_MODS[x]; + }).join("-") + "-"; + } + })(); + + ret.KEY_MODS[0] = ""; + ret.KEY_MODS[-1] = "input-"; + + return ret; +})(); +oop.mixin(exports, Keys); + +exports.keyCodeToString = function(keyCode) { + var keyString = Keys[keyCode]; + if (typeof keyString != "string") + keyString = String.fromCharCode(keyCode); + return keyString.toLowerCase(); +}; + +}); + +ace.define("ace/lib/useragent",["require","exports","module"], function(acequire, exports, module) { +"use strict"; +exports.OS = { + LINUX: "LINUX", + MAC: "MAC", + WINDOWS: "WINDOWS" +}; +exports.getOS = function() { + if (exports.isMac) { + return exports.OS.MAC; + } else if (exports.isLinux) { + return exports.OS.LINUX; + } else { + return exports.OS.WINDOWS; + } +}; +if (typeof navigator != "object") + return; + +var os = (navigator.platform.match(/mac|win|linux/i) || ["other"])[0].toLowerCase(); +var ua = navigator.userAgent; +exports.isWin = (os == "win"); +exports.isMac = (os == "mac"); +exports.isLinux = (os == "linux"); +exports.isIE = + (navigator.appName == "Microsoft Internet Explorer" || navigator.appName.indexOf("MSAppHost") >= 0) + ? parseFloat((ua.match(/(?:MSIE |Trident\/[0-9]+[\.0-9]+;.*rv:)([0-9]+[\.0-9]+)/)||[])[1]) + : parseFloat((ua.match(/(?:Trident\/[0-9]+[\.0-9]+;.*rv:)([0-9]+[\.0-9]+)/)||[])[1]); // for ie + +exports.isOldIE = exports.isIE && exports.isIE < 9; +exports.isGecko = exports.isMozilla = (window.Controllers || window.controllers) && window.navigator.product === "Gecko"; +exports.isOldGecko = exports.isGecko && parseInt((ua.match(/rv:(\d+)/)||[])[1], 10) < 4; +exports.isOpera = window.opera && Object.prototype.toString.call(window.opera) == "[object Opera]"; +exports.isWebKit = parseFloat(ua.split("WebKit/")[1]) || undefined; + +exports.isChrome = parseFloat(ua.split(" Chrome/")[1]) || undefined; + +exports.isAIR = ua.indexOf("AdobeAIR") >= 0; + +exports.isIPad = ua.indexOf("iPad") >= 0; + +exports.isChromeOS = ua.indexOf(" CrOS ") >= 0; + +exports.isIOS = /iPad|iPhone|iPod/.test(ua) && !window.MSStream; + +if (exports.isIOS) exports.isMac = true; + +}); + +ace.define("ace/lib/event",["require","exports","module","ace/lib/keys","ace/lib/useragent"], function(acequire, exports, module) { +"use strict"; + +var keys = acequire("./keys"); +var useragent = acequire("./useragent"); + +var pressedKeys = null; +var ts = 0; + +exports.addListener = function(elem, type, callback) { + if (elem.addEventListener) { + return elem.addEventListener(type, callback, false); + } + if (elem.attachEvent) { + var wrapper = function() { + callback.call(elem, window.event); + }; + callback._wrapper = wrapper; + elem.attachEvent("on" + type, wrapper); + } +}; + +exports.removeListener = function(elem, type, callback) { + if (elem.removeEventListener) { + return elem.removeEventListener(type, callback, false); + } + if (elem.detachEvent) { + elem.detachEvent("on" + type, callback._wrapper || callback); + } +}; +exports.stopEvent = function(e) { + exports.stopPropagation(e); + exports.preventDefault(e); + return false; +}; + +exports.stopPropagation = function(e) { + if (e.stopPropagation) + e.stopPropagation(); + else + e.cancelBubble = true; +}; + +exports.preventDefault = function(e) { + if (e.preventDefault) + e.preventDefault(); + else + e.returnValue = false; +}; +exports.getButton = function(e) { + if (e.type == "dblclick") + return 0; + if (e.type == "contextmenu" || (useragent.isMac && (e.ctrlKey && !e.altKey && !e.shiftKey))) + return 2; + if (e.preventDefault) { + return e.button; + } + else { + return {1:0, 2:2, 4:1}[e.button]; + } +}; + +exports.capture = function(el, eventHandler, releaseCaptureHandler) { + function onMouseUp(e) { + eventHandler && eventHandler(e); + releaseCaptureHandler && releaseCaptureHandler(e); + + exports.removeListener(document, "mousemove", eventHandler, true); + exports.removeListener(document, "mouseup", onMouseUp, true); + exports.removeListener(document, "dragstart", onMouseUp, true); + } + + exports.addListener(document, "mousemove", eventHandler, true); + exports.addListener(document, "mouseup", onMouseUp, true); + exports.addListener(document, "dragstart", onMouseUp, true); + + return onMouseUp; +}; + +exports.addTouchMoveListener = function (el, callback) { + var startx, starty; + exports.addListener(el, "touchstart", function (e) { + var touches = e.touches; + var touchObj = touches[0]; + startx = touchObj.clientX; + starty = touchObj.clientY; + }); + exports.addListener(el, "touchmove", function (e) { + var touches = e.touches; + if (touches.length > 1) return; + + var touchObj = touches[0]; + + e.wheelX = startx - touchObj.clientX; + e.wheelY = starty - touchObj.clientY; + + startx = touchObj.clientX; + starty = touchObj.clientY; + + callback(e); + }); +}; + +exports.addMouseWheelListener = function(el, callback) { + if ("onmousewheel" in el) { + exports.addListener(el, "mousewheel", function(e) { + var factor = 8; + if (e.wheelDeltaX !== undefined) { + e.wheelX = -e.wheelDeltaX / factor; + e.wheelY = -e.wheelDeltaY / factor; + } else { + e.wheelX = 0; + e.wheelY = -e.wheelDelta / factor; + } + callback(e); + }); + } else if ("onwheel" in el) { + exports.addListener(el, "wheel", function(e) { + var factor = 0.35; + switch (e.deltaMode) { + case e.DOM_DELTA_PIXEL: + e.wheelX = e.deltaX * factor || 0; + e.wheelY = e.deltaY * factor || 0; + break; + case e.DOM_DELTA_LINE: + case e.DOM_DELTA_PAGE: + e.wheelX = (e.deltaX || 0) * 5; + e.wheelY = (e.deltaY || 0) * 5; + break; + } + + callback(e); + }); + } else { + exports.addListener(el, "DOMMouseScroll", function(e) { + if (e.axis && e.axis == e.HORIZONTAL_AXIS) { + e.wheelX = (e.detail || 0) * 5; + e.wheelY = 0; + } else { + e.wheelX = 0; + e.wheelY = (e.detail || 0) * 5; + } + callback(e); + }); + } +}; + +exports.addMultiMouseDownListener = function(elements, timeouts, eventHandler, callbackName) { + var clicks = 0; + var startX, startY, timer; + var eventNames = { + 2: "dblclick", + 3: "tripleclick", + 4: "quadclick" + }; + + function onMousedown(e) { + if (exports.getButton(e) !== 0) { + clicks = 0; + } else if (e.detail > 1) { + clicks++; + if (clicks > 4) + clicks = 1; + } else { + clicks = 1; + } + if (useragent.isIE) { + var isNewClick = Math.abs(e.clientX - startX) > 5 || Math.abs(e.clientY - startY) > 5; + if (!timer || isNewClick) + clicks = 1; + if (timer) + clearTimeout(timer); + timer = setTimeout(function() {timer = null;}, timeouts[clicks - 1] || 600); + + if (clicks == 1) { + startX = e.clientX; + startY = e.clientY; + } + } + + e._clicks = clicks; + + eventHandler[callbackName]("mousedown", e); + + if (clicks > 4) + clicks = 0; + else if (clicks > 1) + return eventHandler[callbackName](eventNames[clicks], e); + } + function onDblclick(e) { + clicks = 2; + if (timer) + clearTimeout(timer); + timer = setTimeout(function() {timer = null;}, timeouts[clicks - 1] || 600); + eventHandler[callbackName]("mousedown", e); + eventHandler[callbackName](eventNames[clicks], e); + } + if (!Array.isArray(elements)) + elements = [elements]; + elements.forEach(function(el) { + exports.addListener(el, "mousedown", onMousedown); + if (useragent.isOldIE) + exports.addListener(el, "dblclick", onDblclick); + }); +}; + +var getModifierHash = useragent.isMac && useragent.isOpera && !("KeyboardEvent" in window) + ? function(e) { + return 0 | (e.metaKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.ctrlKey ? 8 : 0); + } + : function(e) { + return 0 | (e.ctrlKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.metaKey ? 8 : 0); + }; + +exports.getModifierString = function(e) { + return keys.KEY_MODS[getModifierHash(e)]; +}; + +function normalizeCommandKeys(callback, e, keyCode) { + var hashId = getModifierHash(e); + + if (!useragent.isMac && pressedKeys) { + if (e.getModifierState && (e.getModifierState("OS") || e.getModifierState("Win"))) + hashId |= 8; + if (pressedKeys.altGr) { + if ((3 & hashId) != 3) + pressedKeys.altGr = 0; + else + return; + } + if (keyCode === 18 || keyCode === 17) { + var location = "location" in e ? e.location : e.keyLocation; + if (keyCode === 17 && location === 1) { + if (pressedKeys[keyCode] == 1) + ts = e.timeStamp; + } else if (keyCode === 18 && hashId === 3 && location === 2) { + var dt = e.timeStamp - ts; + if (dt < 50) + pressedKeys.altGr = true; + } + } + } + + if (keyCode in keys.MODIFIER_KEYS) { + keyCode = -1; + } + if (hashId & 8 && (keyCode >= 91 && keyCode <= 93)) { + keyCode = -1; + } + + if (!hashId && keyCode === 13) { + var location = "location" in e ? e.location : e.keyLocation; + if (location === 3) { + callback(e, hashId, -keyCode); + if (e.defaultPrevented) + return; + } + } + + if (useragent.isChromeOS && hashId & 8) { + callback(e, hashId, keyCode); + if (e.defaultPrevented) + return; + else + hashId &= ~8; + } + if (!hashId && !(keyCode in keys.FUNCTION_KEYS) && !(keyCode in keys.PRINTABLE_KEYS)) { + return false; + } + + return callback(e, hashId, keyCode); +} + + +exports.addCommandKeyListener = function(el, callback) { + var addListener = exports.addListener; + if (useragent.isOldGecko || (useragent.isOpera && !("KeyboardEvent" in window))) { + var lastKeyDownKeyCode = null; + addListener(el, "keydown", function(e) { + lastKeyDownKeyCode = e.keyCode; + }); + addListener(el, "keypress", function(e) { + return normalizeCommandKeys(callback, e, lastKeyDownKeyCode); + }); + } else { + var lastDefaultPrevented = null; + + addListener(el, "keydown", function(e) { + pressedKeys[e.keyCode] = (pressedKeys[e.keyCode] || 0) + 1; + var result = normalizeCommandKeys(callback, e, e.keyCode); + lastDefaultPrevented = e.defaultPrevented; + return result; + }); + + addListener(el, "keypress", function(e) { + if (lastDefaultPrevented && (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey)) { + exports.stopEvent(e); + lastDefaultPrevented = null; + } + }); + + addListener(el, "keyup", function(e) { + pressedKeys[e.keyCode] = null; + }); + + if (!pressedKeys) { + resetPressedKeys(); + addListener(window, "focus", resetPressedKeys); + } + } +}; +function resetPressedKeys() { + pressedKeys = Object.create(null); +} + +if (typeof window == "object" && window.postMessage && !useragent.isOldIE) { + var postMessageId = 1; + exports.nextTick = function(callback, win) { + win = win || window; + var messageName = "zero-timeout-message-" + postMessageId; + exports.addListener(win, "message", function listener(e) { + if (e.data == messageName) { + exports.stopPropagation(e); + exports.removeListener(win, "message", listener); + callback(); + } + }); + win.postMessage(messageName, "*"); + }; +} + + +exports.nextFrame = typeof window == "object" && (window.requestAnimationFrame + || window.mozRequestAnimationFrame + || window.webkitRequestAnimationFrame + || window.msRequestAnimationFrame + || window.oRequestAnimationFrame); + +if (exports.nextFrame) + exports.nextFrame = exports.nextFrame.bind(window); +else + exports.nextFrame = function(callback) { + setTimeout(callback, 17); + }; +}); + +ace.define("ace/lib/lang",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +exports.last = function(a) { + return a[a.length - 1]; +}; + +exports.stringReverse = function(string) { + return string.split("").reverse().join(""); +}; + +exports.stringRepeat = function (string, count) { + var result = ''; + while (count > 0) { + if (count & 1) + result += string; + + if (count >>= 1) + string += string; + } + return result; +}; + +var trimBeginRegexp = /^\s\s*/; +var trimEndRegexp = /\s\s*$/; + +exports.stringTrimLeft = function (string) { + return string.replace(trimBeginRegexp, ''); +}; + +exports.stringTrimRight = function (string) { + return string.replace(trimEndRegexp, ''); +}; + +exports.copyObject = function(obj) { + var copy = {}; + for (var key in obj) { + copy[key] = obj[key]; + } + return copy; +}; + +exports.copyArray = function(array){ + var copy = []; + for (var i=0, l=array.length; i PLACEHOLDER.length) + data = data.substr(9); + else if (data.substr(0, 4) == PLACEHOLDER.substr(0, 4)) + data = data.substr(4, data.length - PLACEHOLDER.length + 1); + else if (data.charAt(data.length - 1) == PLACEHOLDER.charAt(0)) + data = data.slice(0, -1); + if (data == PLACEHOLDER.charAt(0)) { + } else if (data.charAt(data.length - 1) == PLACEHOLDER.charAt(0)) + data = data.slice(0, -1); + + if (data) + host.onTextInput(data); + } + if (copied) { + copied = false; + } + if (afterContextMenu) + afterContextMenu = false; + }; + var onInput = function(e) { + if (inComposition) + return; + var data = text.value; + sendText(data); + resetValue(); + }; + + var handleClipboardData = function(e, data, forceIEMime) { + var clipboardData = e.clipboardData || window.clipboardData; + if (!clipboardData || BROKEN_SETDATA) + return; + var mime = USE_IE_MIME_TYPE || forceIEMime ? "Text" : "text/plain"; + try { + if (data) { + return clipboardData.setData(mime, data) !== false; + } else { + return clipboardData.getData(mime); + } + } catch(e) { + if (!forceIEMime) + return handleClipboardData(e, data, true); + } + }; + + var doCopy = function(e, isCut) { + var data = host.getCopyText(); + if (!data) + return event.preventDefault(e); + + if (handleClipboardData(e, data)) { + if (useragent.isIOS) { + cut = isCut; + text.value = "\n aa" + data + "a a\n"; + text.setSelectionRange(4, 4 + data.length); + copied = { + value: data + }; + } + isCut ? host.onCut() : host.onCopy(); + if (!useragent.isIOS) event.preventDefault(e); + } else { + copied = true; + text.value = data; + text.select(); + setTimeout(function(){ + copied = false; + resetValue(); + resetSelection(); + isCut ? host.onCut() : host.onCopy(); + }); + } + }; + + var onCut = function(e) { + doCopy(e, true); + }; + + var onCopy = function(e) { + doCopy(e, false); + }; + + var onPaste = function(e) { + var data = handleClipboardData(e); + if (typeof data == "string") { + if (data) + host.onPaste(data, e); + if (useragent.isIE) + setTimeout(resetSelection); + event.preventDefault(e); + } + else { + text.value = ""; + pasted = true; + } + }; + + event.addCommandKeyListener(text, host.onCommandKey.bind(host)); + + event.addListener(text, "select", onSelect); + + event.addListener(text, "input", onInput); + + event.addListener(text, "cut", onCut); + event.addListener(text, "copy", onCopy); + event.addListener(text, "paste", onPaste); + var onCompositionStart = function(e) { + if (inComposition || !host.onCompositionStart || host.$readOnly) + return; + inComposition = {}; + inComposition.canUndo = host.session.$undoManager; + host.onCompositionStart(); + setTimeout(onCompositionUpdate, 0); + host.on("mousedown", onCompositionEnd); + if (inComposition.canUndo && !host.selection.isEmpty()) { + host.insert(""); + host.session.markUndoGroup(); + host.selection.clearSelection(); + } + host.session.markUndoGroup(); + }; + + var onCompositionUpdate = function() { + if (!inComposition || !host.onCompositionUpdate || host.$readOnly) + return; + var val = text.value.replace(/\x01/g, ""); + if (inComposition.lastValue === val) return; + + host.onCompositionUpdate(val); + if (inComposition.lastValue) + host.undo(); + if (inComposition.canUndo) + inComposition.lastValue = val; + if (inComposition.lastValue) { + var r = host.selection.getRange(); + host.insert(inComposition.lastValue); + host.session.markUndoGroup(); + inComposition.range = host.selection.getRange(); + host.selection.setRange(r); + host.selection.clearSelection(); + } + }; + + var onCompositionEnd = function(e) { + if (!host.onCompositionEnd || host.$readOnly) return; + var c = inComposition; + inComposition = false; + var timer = setTimeout(function() { + timer = null; + var str = text.value.replace(/\x01/g, ""); + if (inComposition) + return; + else if (str == c.lastValue) + resetValue(); + else if (!c.lastValue && str) { + resetValue(); + sendText(str); + } + }); + inputHandler = function compositionInputHandler(str) { + if (timer) + clearTimeout(timer); + str = str.replace(/\x01/g, ""); + if (str == c.lastValue) + return ""; + if (c.lastValue && timer) + host.undo(); + return str; + }; + host.onCompositionEnd(); + host.removeListener("mousedown", onCompositionEnd); + if (e.type == "compositionend" && c.range) { + host.selection.setRange(c.range); + } + var needsOnInput = + (!!useragent.isChrome && useragent.isChrome >= 53) || + (!!useragent.isWebKit && useragent.isWebKit >= 603); + + if (needsOnInput) { + onInput(); + } + }; + + + + var syncComposition = lang.delayedCall(onCompositionUpdate, 50); + + event.addListener(text, "compositionstart", onCompositionStart); + if (useragent.isGecko) { + event.addListener(text, "text", function(){syncComposition.schedule();}); + } else { + event.addListener(text, "keyup", function(){syncComposition.schedule();}); + event.addListener(text, "keydown", function(){syncComposition.schedule();}); + } + event.addListener(text, "compositionend", onCompositionEnd); + + this.getElement = function() { + return text; + }; + + this.setReadOnly = function(readOnly) { + text.readOnly = readOnly; + }; + + this.onContextMenu = function(e) { + afterContextMenu = true; + resetSelection(host.selection.isEmpty()); + host._emit("nativecontextmenu", {target: host, domEvent: e}); + this.moveToMouse(e, true); + }; + + this.moveToMouse = function(e, bringToFront) { + if (!tempStyle) + tempStyle = text.style.cssText; + text.style.cssText = (bringToFront ? "z-index:100000;" : "") + + "height:" + text.style.height + ";" + + (useragent.isIE ? "opacity:0.1;" : ""); + + var rect = host.container.getBoundingClientRect(); + var style = dom.computedStyle(host.container); + var top = rect.top + (parseInt(style.borderTopWidth) || 0); + var left = rect.left + (parseInt(rect.borderLeftWidth) || 0); + var maxTop = rect.bottom - top - text.clientHeight -2; + var move = function(e) { + text.style.left = e.clientX - left - 2 + "px"; + text.style.top = Math.min(e.clientY - top - 2, maxTop) + "px"; + }; + move(e); + + if (e.type != "mousedown") + return; + + if (host.renderer.$keepTextAreaAtCursor) + host.renderer.$keepTextAreaAtCursor = null; + + clearTimeout(closeTimeout); + if (useragent.isWin) + event.capture(host.container, move, onContextMenuClose); + }; + + this.onContextMenuClose = onContextMenuClose; + var closeTimeout; + function onContextMenuClose() { + clearTimeout(closeTimeout); + closeTimeout = setTimeout(function () { + if (tempStyle) { + text.style.cssText = tempStyle; + tempStyle = ''; + } + if (host.renderer.$keepTextAreaAtCursor == null) { + host.renderer.$keepTextAreaAtCursor = true; + host.renderer.$moveTextAreaToCursor(); + } + }, 0); + } + + var onContextMenu = function(e) { + host.textInput.onContextMenu(e); + onContextMenuClose(); + }; + event.addListener(text, "mouseup", onContextMenu); + event.addListener(text, "mousedown", function(e) { + e.preventDefault(); + onContextMenuClose(); + }); + event.addListener(host.renderer.scroller, "contextmenu", onContextMenu); + event.addListener(text, "contextmenu", onContextMenu); + + if (useragent.isIOS) { + var typingResetTimeout = null; + var typing = false; + + parentNode.addEventListener("keydown", function (e) { + if (typingResetTimeout) clearTimeout(typingResetTimeout); + typing = true; + }); + + parentNode.addEventListener("keyup", function (e) { + typingResetTimeout = setTimeout(function () { + typing = false; + }, 100); + }); + var detectArrowKeys = function(e) { + if (document.activeElement !== text) return; + if (typing) return; + + if (cut) { + return setTimeout(function () { + cut = false; + }, 100); + } + var selectionStart = text.selectionStart; + var selectionEnd = text.selectionEnd; + text.setSelectionRange(4, 5); + if (selectionStart == selectionEnd) { + switch (selectionStart) { + case 0: host.onCommandKey(null, 0, KEYS.up); break; + case 1: host.onCommandKey(null, 0, KEYS.home); break; + case 2: host.onCommandKey(null, MODS.option, KEYS.left); break; + case 4: host.onCommandKey(null, 0, KEYS.left); break; + case 5: host.onCommandKey(null, 0, KEYS.right); break; + case 7: host.onCommandKey(null, MODS.option, KEYS.right); break; + case 8: host.onCommandKey(null, 0, KEYS.end); break; + case 9: host.onCommandKey(null, 0, KEYS.down); break; + } + } else { + switch (selectionEnd) { + case 6: host.onCommandKey(null, MODS.shift, KEYS.right); break; + case 7: host.onCommandKey(null, MODS.shift | MODS.option, KEYS.right); break; + case 8: host.onCommandKey(null, MODS.shift, KEYS.end); break; + case 9: host.onCommandKey(null, MODS.shift, KEYS.down); break; + } + switch (selectionStart) { + case 0: host.onCommandKey(null, MODS.shift, KEYS.up); break; + case 1: host.onCommandKey(null, MODS.shift, KEYS.home); break; + case 2: host.onCommandKey(null, MODS.shift | MODS.option, KEYS.left); break; + case 3: host.onCommandKey(null, MODS.shift, KEYS.left); break; + } + } + }; + document.addEventListener("selectionchange", detectArrowKeys); + host.on("destroy", function() { + document.removeEventListener("selectionchange", detectArrowKeys); + }); + } +}; + +exports.TextInput = TextInput; +}); + +ace.define("ace/keyboard/textinput",["require","exports","module","ace/lib/event","ace/lib/useragent","ace/lib/dom","ace/lib/lang","ace/keyboard/textinput_ios"], function(acequire, exports, module) { +"use strict"; + +var event = acequire("../lib/event"); +var useragent = acequire("../lib/useragent"); +var dom = acequire("../lib/dom"); +var lang = acequire("../lib/lang"); +var BROKEN_SETDATA = useragent.isChrome < 18; +var USE_IE_MIME_TYPE = useragent.isIE; + +var TextInputIOS = acequire("./textinput_ios").TextInput; +var TextInput = function(parentNode, host) { + if (useragent.isIOS) + return TextInputIOS.call(this, parentNode, host); + + var text = dom.createElement("textarea"); + text.className = "ace_text-input"; + + text.setAttribute("wrap", "off"); + text.setAttribute("autocorrect", "off"); + text.setAttribute("autocapitalize", "off"); + text.setAttribute("spellcheck", false); + + text.style.opacity = "0"; + parentNode.insertBefore(text, parentNode.firstChild); + + var PLACEHOLDER = "\u2028\u2028"; + + var copied = false; + var pasted = false; + var inComposition = false; + var tempStyle = ''; + var isSelectionEmpty = true; + try { var isFocused = document.activeElement === text; } catch(e) {} + + event.addListener(text, "blur", function(e) { + host.onBlur(e); + isFocused = false; + }); + event.addListener(text, "focus", function(e) { + isFocused = true; + host.onFocus(e); + resetSelection(); + }); + this.focus = function() { + if (tempStyle) return text.focus(); + var top = text.style.top; + text.style.position = "fixed"; + text.style.top = "0px"; + text.focus(); + setTimeout(function() { + text.style.position = ""; + if (text.style.top == "0px") + text.style.top = top; + }, 0); + }; + this.blur = function() { + text.blur(); + }; + this.isFocused = function() { + return isFocused; + }; + var syncSelection = lang.delayedCall(function() { + isFocused && resetSelection(isSelectionEmpty); + }); + var syncValue = lang.delayedCall(function() { + if (!inComposition) { + text.value = PLACEHOLDER; + isFocused && resetSelection(); + } + }); + + function resetSelection(isEmpty) { + if (inComposition) + return; + inComposition = true; + + if (inputHandler) { + var selectionStart = 0; + var selectionEnd = isEmpty ? 0 : text.value.length - 1; + } else { + var selectionStart = isEmpty ? 2 : 1; + var selectionEnd = 2; + } + try { + text.setSelectionRange(selectionStart, selectionEnd); + } catch(e){} + + inComposition = false; + } + + function resetValue() { + if (inComposition) + return; + text.value = PLACEHOLDER; + if (useragent.isWebKit) + syncValue.schedule(); + } + + useragent.isWebKit || host.addEventListener('changeSelection', function() { + if (host.selection.isEmpty() != isSelectionEmpty) { + isSelectionEmpty = !isSelectionEmpty; + syncSelection.schedule(); + } + }); + + resetValue(); + if (isFocused) + host.onFocus(); + + + var isAllSelected = function(text) { + return text.selectionStart === 0 && text.selectionEnd === text.value.length; + }; + + var onSelect = function(e) { + if (copied) { + copied = false; + } else if (isAllSelected(text)) { + host.selectAll(); + resetSelection(); + } else if (inputHandler) { + resetSelection(host.selection.isEmpty()); + } + }; + + var inputHandler = null; + this.setInputHandler = function(cb) {inputHandler = cb;}; + this.getInputHandler = function() {return inputHandler;}; + var afterContextMenu = false; + + var sendText = function(data) { + if (inputHandler) { + data = inputHandler(data); + inputHandler = null; + } + if (pasted) { + resetSelection(); + if (data) + host.onPaste(data); + pasted = false; + } else if (data == PLACEHOLDER.charAt(0)) { + if (afterContextMenu) + host.execCommand("del", {source: "ace"}); + else // some versions of android do not fire keydown when pressing backspace + host.execCommand("backspace", {source: "ace"}); + } else { + if (data.substring(0, 2) == PLACEHOLDER) + data = data.substr(2); + else if (data.charAt(0) == PLACEHOLDER.charAt(0)) + data = data.substr(1); + else if (data.charAt(data.length - 1) == PLACEHOLDER.charAt(0)) + data = data.slice(0, -1); + if (data.charAt(data.length - 1) == PLACEHOLDER.charAt(0)) + data = data.slice(0, -1); + + if (data) + host.onTextInput(data); + } + if (afterContextMenu) + afterContextMenu = false; + }; + var onInput = function(e) { + if (inComposition) + return; + var data = text.value; + sendText(data); + resetValue(); + }; + + var handleClipboardData = function(e, data, forceIEMime) { + var clipboardData = e.clipboardData || window.clipboardData; + if (!clipboardData || BROKEN_SETDATA) + return; + var mime = USE_IE_MIME_TYPE || forceIEMime ? "Text" : "text/plain"; + try { + if (data) { + return clipboardData.setData(mime, data) !== false; + } else { + return clipboardData.getData(mime); + } + } catch(e) { + if (!forceIEMime) + return handleClipboardData(e, data, true); + } + }; + + var doCopy = function(e, isCut) { + var data = host.getCopyText(); + if (!data) + return event.preventDefault(e); + + if (handleClipboardData(e, data)) { + isCut ? host.onCut() : host.onCopy(); + event.preventDefault(e); + } else { + copied = true; + text.value = data; + text.select(); + setTimeout(function(){ + copied = false; + resetValue(); + resetSelection(); + isCut ? host.onCut() : host.onCopy(); + }); + } + }; + + var onCut = function(e) { + doCopy(e, true); + }; + + var onCopy = function(e) { + doCopy(e, false); + }; + + var onPaste = function(e) { + var data = handleClipboardData(e); + if (typeof data == "string") { + if (data) + host.onPaste(data, e); + if (useragent.isIE) + setTimeout(resetSelection); + event.preventDefault(e); + } + else { + text.value = ""; + pasted = true; + } + }; + + event.addCommandKeyListener(text, host.onCommandKey.bind(host)); + + event.addListener(text, "select", onSelect); + + event.addListener(text, "input", onInput); + + event.addListener(text, "cut", onCut); + event.addListener(text, "copy", onCopy); + event.addListener(text, "paste", onPaste); + if (!('oncut' in text) || !('oncopy' in text) || !('onpaste' in text)) { + event.addListener(parentNode, "keydown", function(e) { + if ((useragent.isMac && !e.metaKey) || !e.ctrlKey) + return; + + switch (e.keyCode) { + case 67: + onCopy(e); + break; + case 86: + onPaste(e); + break; + case 88: + onCut(e); + break; + } + }); + } + var onCompositionStart = function(e) { + if (inComposition || !host.onCompositionStart || host.$readOnly) + return; + inComposition = {}; + inComposition.canUndo = host.session.$undoManager; + host.onCompositionStart(); + setTimeout(onCompositionUpdate, 0); + host.on("mousedown", onCompositionEnd); + if (inComposition.canUndo && !host.selection.isEmpty()) { + host.insert(""); + host.session.markUndoGroup(); + host.selection.clearSelection(); + } + host.session.markUndoGroup(); + }; + + var onCompositionUpdate = function() { + if (!inComposition || !host.onCompositionUpdate || host.$readOnly) + return; + var val = text.value.replace(/\u2028/g, ""); + if (inComposition.lastValue === val) return; + + host.onCompositionUpdate(val); + if (inComposition.lastValue) + host.undo(); + if (inComposition.canUndo) + inComposition.lastValue = val; + if (inComposition.lastValue) { + var r = host.selection.getRange(); + host.insert(inComposition.lastValue); + host.session.markUndoGroup(); + inComposition.range = host.selection.getRange(); + host.selection.setRange(r); + host.selection.clearSelection(); + } + }; + + var onCompositionEnd = function(e) { + if (!host.onCompositionEnd || host.$readOnly) return; + var c = inComposition; + inComposition = false; + var timer = setTimeout(function() { + timer = null; + var str = text.value.replace(/\u2028/g, ""); + if (inComposition) + return; + else if (str == c.lastValue) + resetValue(); + else if (!c.lastValue && str) { + resetValue(); + sendText(str); + } + }); + inputHandler = function compositionInputHandler(str) { + if (timer) + clearTimeout(timer); + str = str.replace(/\u2028/g, ""); + if (str == c.lastValue) + return ""; + if (c.lastValue && timer) + host.undo(); + return str; + }; + host.onCompositionEnd(); + host.removeListener("mousedown", onCompositionEnd); + if (e.type == "compositionend" && c.range) { + host.selection.setRange(c.range); + } + var needsOnInput = + (!!useragent.isChrome && useragent.isChrome >= 53) || + (!!useragent.isWebKit && useragent.isWebKit >= 603); + + if (needsOnInput) { + onInput(); + } + }; + + + + var syncComposition = lang.delayedCall(onCompositionUpdate, 50); + + event.addListener(text, "compositionstart", onCompositionStart); + if (useragent.isGecko) { + event.addListener(text, "text", function(){syncComposition.schedule();}); + } else { + event.addListener(text, "keyup", function(){syncComposition.schedule();}); + event.addListener(text, "keydown", function(){syncComposition.schedule();}); + } + event.addListener(text, "compositionend", onCompositionEnd); + + this.getElement = function() { + return text; + }; + + this.setReadOnly = function(readOnly) { + text.readOnly = readOnly; + }; + + this.onContextMenu = function(e) { + afterContextMenu = true; + resetSelection(host.selection.isEmpty()); + host._emit("nativecontextmenu", {target: host, domEvent: e}); + this.moveToMouse(e, true); + }; + + this.moveToMouse = function(e, bringToFront) { + if (!tempStyle) + tempStyle = text.style.cssText; + text.style.cssText = (bringToFront ? "z-index:100000;" : "") + + "height:" + text.style.height + ";" + + (useragent.isIE ? "opacity:0.1;" : ""); + + var rect = host.container.getBoundingClientRect(); + var style = dom.computedStyle(host.container); + var top = rect.top + (parseInt(style.borderTopWidth) || 0); + var left = rect.left + (parseInt(rect.borderLeftWidth) || 0); + var maxTop = rect.bottom - top - text.clientHeight -2; + var move = function(e) { + text.style.left = e.clientX - left - 2 + "px"; + text.style.top = Math.min(e.clientY - top - 2, maxTop) + "px"; + }; + move(e); + + if (e.type != "mousedown") + return; + + if (host.renderer.$keepTextAreaAtCursor) + host.renderer.$keepTextAreaAtCursor = null; + + clearTimeout(closeTimeout); + if (useragent.isWin) + event.capture(host.container, move, onContextMenuClose); + }; + + this.onContextMenuClose = onContextMenuClose; + var closeTimeout; + function onContextMenuClose() { + clearTimeout(closeTimeout); + closeTimeout = setTimeout(function () { + if (tempStyle) { + text.style.cssText = tempStyle; + tempStyle = ''; + } + if (host.renderer.$keepTextAreaAtCursor == null) { + host.renderer.$keepTextAreaAtCursor = true; + host.renderer.$moveTextAreaToCursor(); + } + }, 0); + } + + var onContextMenu = function(e) { + host.textInput.onContextMenu(e); + onContextMenuClose(); + }; + event.addListener(text, "mouseup", onContextMenu); + event.addListener(text, "mousedown", function(e) { + e.preventDefault(); + onContextMenuClose(); + }); + event.addListener(host.renderer.scroller, "contextmenu", onContextMenu); + event.addListener(text, "contextmenu", onContextMenu); +}; + +exports.TextInput = TextInput; +}); + +ace.define("ace/mouse/default_handlers",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) { +"use strict"; + +var dom = acequire("../lib/dom"); +var event = acequire("../lib/event"); +var useragent = acequire("../lib/useragent"); + +var DRAG_OFFSET = 0; // pixels +var SCROLL_COOLDOWN_T = 250; // milliseconds + +function DefaultHandlers(mouseHandler) { + mouseHandler.$clickSelection = null; + + var editor = mouseHandler.editor; + editor.setDefaultHandler("mousedown", this.onMouseDown.bind(mouseHandler)); + editor.setDefaultHandler("dblclick", this.onDoubleClick.bind(mouseHandler)); + editor.setDefaultHandler("tripleclick", this.onTripleClick.bind(mouseHandler)); + editor.setDefaultHandler("quadclick", this.onQuadClick.bind(mouseHandler)); + editor.setDefaultHandler("mousewheel", this.onMouseWheel.bind(mouseHandler)); + editor.setDefaultHandler("touchmove", this.onTouchMove.bind(mouseHandler)); + + var exports = ["select", "startSelect", "selectEnd", "selectAllEnd", "selectByWordsEnd", + "selectByLinesEnd", "dragWait", "dragWaitEnd", "focusWait"]; + + exports.forEach(function(x) { + mouseHandler[x] = this[x]; + }, this); + + mouseHandler.selectByLines = this.extendSelectionBy.bind(mouseHandler, "getLineRange"); + mouseHandler.selectByWords = this.extendSelectionBy.bind(mouseHandler, "getWordRange"); +} + +(function() { + + this.onMouseDown = function(ev) { + var inSelection = ev.inSelection(); + var pos = ev.getDocumentPosition(); + this.mousedownEvent = ev; + var editor = this.editor; + + var button = ev.getButton(); + if (button !== 0) { + var selectionRange = editor.getSelectionRange(); + var selectionEmpty = selectionRange.isEmpty(); + editor.$blockScrolling++; + if (selectionEmpty || button == 1) + editor.selection.moveToPosition(pos); + editor.$blockScrolling--; + if (button == 2) { + editor.textInput.onContextMenu(ev.domEvent); + if (!useragent.isMozilla) + ev.preventDefault(); + } + return; + } + + this.mousedownEvent.time = Date.now(); + if (inSelection && !editor.isFocused()) { + editor.focus(); + if (this.$focusTimout && !this.$clickSelection && !editor.inMultiSelectMode) { + this.setState("focusWait"); + this.captureMouse(ev); + return; + } + } + + this.captureMouse(ev); + this.startSelect(pos, ev.domEvent._clicks > 1); + return ev.preventDefault(); + }; + + this.startSelect = function(pos, waitForClickSelection) { + pos = pos || this.editor.renderer.screenToTextCoordinates(this.x, this.y); + var editor = this.editor; + editor.$blockScrolling++; + if (this.mousedownEvent.getShiftKey()) + editor.selection.selectToPosition(pos); + else if (!waitForClickSelection) + editor.selection.moveToPosition(pos); + if (!waitForClickSelection) + this.select(); + if (editor.renderer.scroller.setCapture) { + editor.renderer.scroller.setCapture(); + } + editor.setStyle("ace_selecting"); + this.setState("select"); + editor.$blockScrolling--; + }; + + this.select = function() { + var anchor, editor = this.editor; + var cursor = editor.renderer.screenToTextCoordinates(this.x, this.y); + editor.$blockScrolling++; + if (this.$clickSelection) { + var cmp = this.$clickSelection.comparePoint(cursor); + + if (cmp == -1) { + anchor = this.$clickSelection.end; + } else if (cmp == 1) { + anchor = this.$clickSelection.start; + } else { + var orientedRange = calcRangeOrientation(this.$clickSelection, cursor); + cursor = orientedRange.cursor; + anchor = orientedRange.anchor; + } + editor.selection.setSelectionAnchor(anchor.row, anchor.column); + } + editor.selection.selectToPosition(cursor); + editor.$blockScrolling--; + editor.renderer.scrollCursorIntoView(); + }; + + this.extendSelectionBy = function(unitName) { + var anchor, editor = this.editor; + var cursor = editor.renderer.screenToTextCoordinates(this.x, this.y); + var range = editor.selection[unitName](cursor.row, cursor.column); + editor.$blockScrolling++; + if (this.$clickSelection) { + var cmpStart = this.$clickSelection.comparePoint(range.start); + var cmpEnd = this.$clickSelection.comparePoint(range.end); + + if (cmpStart == -1 && cmpEnd <= 0) { + anchor = this.$clickSelection.end; + if (range.end.row != cursor.row || range.end.column != cursor.column) + cursor = range.start; + } else if (cmpEnd == 1 && cmpStart >= 0) { + anchor = this.$clickSelection.start; + if (range.start.row != cursor.row || range.start.column != cursor.column) + cursor = range.end; + } else if (cmpStart == -1 && cmpEnd == 1) { + cursor = range.end; + anchor = range.start; + } else { + var orientedRange = calcRangeOrientation(this.$clickSelection, cursor); + cursor = orientedRange.cursor; + anchor = orientedRange.anchor; + } + editor.selection.setSelectionAnchor(anchor.row, anchor.column); + } + editor.selection.selectToPosition(cursor); + editor.$blockScrolling--; + editor.renderer.scrollCursorIntoView(); + }; + + this.selectEnd = + this.selectAllEnd = + this.selectByWordsEnd = + this.selectByLinesEnd = function() { + this.$clickSelection = null; + this.editor.unsetStyle("ace_selecting"); + if (this.editor.renderer.scroller.releaseCapture) { + this.editor.renderer.scroller.releaseCapture(); + } + }; + + this.focusWait = function() { + var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y); + var time = Date.now(); + + if (distance > DRAG_OFFSET || time - this.mousedownEvent.time > this.$focusTimout) + this.startSelect(this.mousedownEvent.getDocumentPosition()); + }; + + this.onDoubleClick = function(ev) { + var pos = ev.getDocumentPosition(); + var editor = this.editor; + var session = editor.session; + + var range = session.getBracketRange(pos); + if (range) { + if (range.isEmpty()) { + range.start.column--; + range.end.column++; + } + this.setState("select"); + } else { + range = editor.selection.getWordRange(pos.row, pos.column); + this.setState("selectByWords"); + } + this.$clickSelection = range; + this.select(); + }; + + this.onTripleClick = function(ev) { + var pos = ev.getDocumentPosition(); + var editor = this.editor; + + this.setState("selectByLines"); + var range = editor.getSelectionRange(); + if (range.isMultiLine() && range.contains(pos.row, pos.column)) { + this.$clickSelection = editor.selection.getLineRange(range.start.row); + this.$clickSelection.end = editor.selection.getLineRange(range.end.row).end; + } else { + this.$clickSelection = editor.selection.getLineRange(pos.row); + } + this.select(); + }; + + this.onQuadClick = function(ev) { + var editor = this.editor; + + editor.selectAll(); + this.$clickSelection = editor.getSelectionRange(); + this.setState("selectAll"); + }; + + this.onMouseWheel = function(ev) { + if (ev.getAccelKey()) + return; + if (ev.getShiftKey() && ev.wheelY && !ev.wheelX) { + ev.wheelX = ev.wheelY; + ev.wheelY = 0; + } + + var editor = this.editor; + + if (!this.$lastScroll) + this.$lastScroll = { t: 0, vx: 0, vy: 0, allowed: 0 }; + + var prevScroll = this.$lastScroll; + var t = ev.domEvent.timeStamp; + var dt = t - prevScroll.t; + var vx = ev.wheelX / dt; + var vy = ev.wheelY / dt; + if (dt < SCROLL_COOLDOWN_T) { + vx = (vx + prevScroll.vx) / 2; + vy = (vy + prevScroll.vy) / 2; + } + + var direction = Math.abs(vx / vy); + + var canScroll = false; + if (direction >= 1 && editor.renderer.isScrollableBy(ev.wheelX * ev.speed, 0)) + canScroll = true; + if (direction <= 1 && editor.renderer.isScrollableBy(0, ev.wheelY * ev.speed)) + canScroll = true; + + if (canScroll) { + prevScroll.allowed = t; + } else if (t - prevScroll.allowed < SCROLL_COOLDOWN_T) { + var isSlower = Math.abs(vx) <= 1.1 * Math.abs(prevScroll.vx) + && Math.abs(vy) <= 1.1 * Math.abs(prevScroll.vy); + if (isSlower) { + canScroll = true; + prevScroll.allowed = t; + } + else { + prevScroll.allowed = 0; + } + } + + prevScroll.t = t; + prevScroll.vx = vx; + prevScroll.vy = vy; + + if (canScroll) { + editor.renderer.scrollBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed); + return ev.stop(); + } + }; + + this.onTouchMove = function(ev) { + this.editor._emit("mousewheel", ev); + }; + +}).call(DefaultHandlers.prototype); + +exports.DefaultHandlers = DefaultHandlers; + +function calcDistance(ax, ay, bx, by) { + return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2)); +} + +function calcRangeOrientation(range, cursor) { + if (range.start.row == range.end.row) + var cmp = 2 * cursor.column - range.start.column - range.end.column; + else if (range.start.row == range.end.row - 1 && !range.start.column && !range.end.column) + var cmp = cursor.column - 4; + else + var cmp = 2 * cursor.row - range.start.row - range.end.row; + + if (cmp < 0) + return {cursor: range.start, anchor: range.end}; + else + return {cursor: range.end, anchor: range.start}; +} + +}); + +ace.define("ace/tooltip",["require","exports","module","ace/lib/oop","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var dom = acequire("./lib/dom"); +function Tooltip (parentNode) { + this.isOpen = false; + this.$element = null; + this.$parentNode = parentNode; +} + +(function() { + this.$init = function() { + this.$element = dom.createElement("div"); + this.$element.className = "ace_tooltip"; + this.$element.style.display = "none"; + this.$parentNode.appendChild(this.$element); + return this.$element; + }; + this.getElement = function() { + return this.$element || this.$init(); + }; + this.setText = function(text) { + dom.setInnerText(this.getElement(), text); + }; + this.setHtml = function(html) { + this.getElement().innerHTML = html; + }; + this.setPosition = function(x, y) { + this.getElement().style.left = x + "px"; + this.getElement().style.top = y + "px"; + }; + this.setClassName = function(className) { + dom.addCssClass(this.getElement(), className); + }; + this.show = function(text, x, y) { + if (text != null) + this.setText(text); + if (x != null && y != null) + this.setPosition(x, y); + if (!this.isOpen) { + this.getElement().style.display = "block"; + this.isOpen = true; + } + }; + + this.hide = function() { + if (this.isOpen) { + this.getElement().style.display = "none"; + this.isOpen = false; + } + }; + this.getHeight = function() { + return this.getElement().offsetHeight; + }; + this.getWidth = function() { + return this.getElement().offsetWidth; + }; + + this.destroy = function() { + this.isOpen = false; + if (this.$element && this.$element.parentNode) { + this.$element.parentNode.removeChild(this.$element); + } + }; + +}).call(Tooltip.prototype); + +exports.Tooltip = Tooltip; +}); + +ace.define("ace/mouse/default_gutter_handler",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/event","ace/tooltip"], function(acequire, exports, module) { +"use strict"; +var dom = acequire("../lib/dom"); +var oop = acequire("../lib/oop"); +var event = acequire("../lib/event"); +var Tooltip = acequire("../tooltip").Tooltip; + +function GutterHandler(mouseHandler) { + var editor = mouseHandler.editor; + var gutter = editor.renderer.$gutterLayer; + var tooltip = new GutterTooltip(editor.container); + + mouseHandler.editor.setDefaultHandler("guttermousedown", function(e) { + if (!editor.isFocused() || e.getButton() != 0) + return; + var gutterRegion = gutter.getRegion(e); + + if (gutterRegion == "foldWidgets") + return; + + var row = e.getDocumentPosition().row; + var selection = editor.session.selection; + + if (e.getShiftKey()) + selection.selectTo(row, 0); + else { + if (e.domEvent.detail == 2) { + editor.selectAll(); + return e.preventDefault(); + } + mouseHandler.$clickSelection = editor.selection.getLineRange(row); + } + mouseHandler.setState("selectByLines"); + mouseHandler.captureMouse(e); + return e.preventDefault(); + }); + + + var tooltipTimeout, mouseEvent, tooltipAnnotation; + + function showTooltip() { + var row = mouseEvent.getDocumentPosition().row; + var annotation = gutter.$annotations[row]; + if (!annotation) + return hideTooltip(); + + var maxRow = editor.session.getLength(); + if (row == maxRow) { + var screenRow = editor.renderer.pixelToScreenCoordinates(0, mouseEvent.y).row; + var pos = mouseEvent.$pos; + if (screenRow > editor.session.documentToScreenRow(pos.row, pos.column)) + return hideTooltip(); + } + + if (tooltipAnnotation == annotation) + return; + tooltipAnnotation = annotation.text.join("
"); + + tooltip.setHtml(tooltipAnnotation); + tooltip.show(); + editor._signal("showGutterTooltip", tooltip); + editor.on("mousewheel", hideTooltip); + + if (mouseHandler.$tooltipFollowsMouse) { + moveTooltip(mouseEvent); + } else { + var gutterElement = mouseEvent.domEvent.target; + var rect = gutterElement.getBoundingClientRect(); + var style = tooltip.getElement().style; + style.left = rect.right + "px"; + style.top = rect.bottom + "px"; + } + } + + function hideTooltip() { + if (tooltipTimeout) + tooltipTimeout = clearTimeout(tooltipTimeout); + if (tooltipAnnotation) { + tooltip.hide(); + tooltipAnnotation = null; + editor._signal("hideGutterTooltip", tooltip); + editor.removeEventListener("mousewheel", hideTooltip); + } + } + + function moveTooltip(e) { + tooltip.setPosition(e.x, e.y); + } + + mouseHandler.editor.setDefaultHandler("guttermousemove", function(e) { + var target = e.domEvent.target || e.domEvent.srcElement; + if (dom.hasCssClass(target, "ace_fold-widget")) + return hideTooltip(); + + if (tooltipAnnotation && mouseHandler.$tooltipFollowsMouse) + moveTooltip(e); + + mouseEvent = e; + if (tooltipTimeout) + return; + tooltipTimeout = setTimeout(function() { + tooltipTimeout = null; + if (mouseEvent && !mouseHandler.isMousePressed) + showTooltip(); + else + hideTooltip(); + }, 50); + }); + + event.addListener(editor.renderer.$gutter, "mouseout", function(e) { + mouseEvent = null; + if (!tooltipAnnotation || tooltipTimeout) + return; + + tooltipTimeout = setTimeout(function() { + tooltipTimeout = null; + hideTooltip(); + }, 50); + }); + + editor.on("changeSession", hideTooltip); +} + +function GutterTooltip(parentNode) { + Tooltip.call(this, parentNode); +} + +oop.inherits(GutterTooltip, Tooltip); + +(function(){ + this.setPosition = function(x, y) { + var windowWidth = window.innerWidth || document.documentElement.clientWidth; + var windowHeight = window.innerHeight || document.documentElement.clientHeight; + var width = this.getWidth(); + var height = this.getHeight(); + x += 15; + y += 15; + if (x + width > windowWidth) { + x -= (x + width) - windowWidth; + } + if (y + height > windowHeight) { + y -= 20 + height; + } + Tooltip.prototype.setPosition.call(this, x, y); + }; + +}).call(GutterTooltip.prototype); + + + +exports.GutterHandler = GutterHandler; + +}); + +ace.define("ace/mouse/mouse_event",["require","exports","module","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) { +"use strict"; + +var event = acequire("../lib/event"); +var useragent = acequire("../lib/useragent"); +var MouseEvent = exports.MouseEvent = function(domEvent, editor) { + this.domEvent = domEvent; + this.editor = editor; + + this.x = this.clientX = domEvent.clientX; + this.y = this.clientY = domEvent.clientY; + + this.$pos = null; + this.$inSelection = null; + + this.propagationStopped = false; + this.defaultPrevented = false; +}; + +(function() { + + this.stopPropagation = function() { + event.stopPropagation(this.domEvent); + this.propagationStopped = true; + }; + + this.preventDefault = function() { + event.preventDefault(this.domEvent); + this.defaultPrevented = true; + }; + + this.stop = function() { + this.stopPropagation(); + this.preventDefault(); + }; + this.getDocumentPosition = function() { + if (this.$pos) + return this.$pos; + + this.$pos = this.editor.renderer.screenToTextCoordinates(this.clientX, this.clientY); + return this.$pos; + }; + this.inSelection = function() { + if (this.$inSelection !== null) + return this.$inSelection; + + var editor = this.editor; + + + var selectionRange = editor.getSelectionRange(); + if (selectionRange.isEmpty()) + this.$inSelection = false; + else { + var pos = this.getDocumentPosition(); + this.$inSelection = selectionRange.contains(pos.row, pos.column); + } + + return this.$inSelection; + }; + this.getButton = function() { + return event.getButton(this.domEvent); + }; + this.getShiftKey = function() { + return this.domEvent.shiftKey; + }; + + this.getAccelKey = useragent.isMac + ? function() { return this.domEvent.metaKey; } + : function() { return this.domEvent.ctrlKey; }; + +}).call(MouseEvent.prototype); + +}); + +ace.define("ace/mouse/dragdrop_handler",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) { +"use strict"; + +var dom = acequire("../lib/dom"); +var event = acequire("../lib/event"); +var useragent = acequire("../lib/useragent"); + +var AUTOSCROLL_DELAY = 200; +var SCROLL_CURSOR_DELAY = 200; +var SCROLL_CURSOR_HYSTERESIS = 5; + +function DragdropHandler(mouseHandler) { + + var editor = mouseHandler.editor; + + var blankImage = dom.createElement("img"); + blankImage.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; + if (useragent.isOpera) + blankImage.style.cssText = "width:1px;height:1px;position:fixed;top:0;left:0;z-index:2147483647;opacity:0;"; + + var exports = ["dragWait", "dragWaitEnd", "startDrag", "dragReadyEnd", "onMouseDrag"]; + + exports.forEach(function(x) { + mouseHandler[x] = this[x]; + }, this); + editor.addEventListener("mousedown", this.onMouseDown.bind(mouseHandler)); + + + var mouseTarget = editor.container; + var dragSelectionMarker, x, y; + var timerId, range; + var dragCursor, counter = 0; + var dragOperation; + var isInternal; + var autoScrollStartTime; + var cursorMovedTime; + var cursorPointOnCaretMoved; + + this.onDragStart = function(e) { + if (this.cancelDrag || !mouseTarget.draggable) { + var self = this; + setTimeout(function(){ + self.startSelect(); + self.captureMouse(e); + }, 0); + return e.preventDefault(); + } + range = editor.getSelectionRange(); + + var dataTransfer = e.dataTransfer; + dataTransfer.effectAllowed = editor.getReadOnly() ? "copy" : "copyMove"; + if (useragent.isOpera) { + editor.container.appendChild(blankImage); + blankImage.scrollTop = 0; + } + dataTransfer.setDragImage && dataTransfer.setDragImage(blankImage, 0, 0); + if (useragent.isOpera) { + editor.container.removeChild(blankImage); + } + dataTransfer.clearData(); + dataTransfer.setData("Text", editor.session.getTextRange()); + + isInternal = true; + this.setState("drag"); + }; + + this.onDragEnd = function(e) { + mouseTarget.draggable = false; + isInternal = false; + this.setState(null); + if (!editor.getReadOnly()) { + var dropEffect = e.dataTransfer.dropEffect; + if (!dragOperation && dropEffect == "move") + editor.session.remove(editor.getSelectionRange()); + editor.renderer.$cursorLayer.setBlinking(true); + } + this.editor.unsetStyle("ace_dragging"); + this.editor.renderer.setCursorStyle(""); + }; + + this.onDragEnter = function(e) { + if (editor.getReadOnly() || !canAccept(e.dataTransfer)) + return; + x = e.clientX; + y = e.clientY; + if (!dragSelectionMarker) + addDragMarker(); + counter++; + e.dataTransfer.dropEffect = dragOperation = getDropEffect(e); + return event.preventDefault(e); + }; + + this.onDragOver = function(e) { + if (editor.getReadOnly() || !canAccept(e.dataTransfer)) + return; + x = e.clientX; + y = e.clientY; + if (!dragSelectionMarker) { + addDragMarker(); + counter++; + } + if (onMouseMoveTimer !== null) + onMouseMoveTimer = null; + + e.dataTransfer.dropEffect = dragOperation = getDropEffect(e); + return event.preventDefault(e); + }; + + this.onDragLeave = function(e) { + counter--; + if (counter <= 0 && dragSelectionMarker) { + clearDragMarker(); + dragOperation = null; + return event.preventDefault(e); + } + }; + + this.onDrop = function(e) { + if (!dragCursor) + return; + var dataTransfer = e.dataTransfer; + if (isInternal) { + switch (dragOperation) { + case "move": + if (range.contains(dragCursor.row, dragCursor.column)) { + range = { + start: dragCursor, + end: dragCursor + }; + } else { + range = editor.moveText(range, dragCursor); + } + break; + case "copy": + range = editor.moveText(range, dragCursor, true); + break; + } + } else { + var dropData = dataTransfer.getData('Text'); + range = { + start: dragCursor, + end: editor.session.insert(dragCursor, dropData) + }; + editor.focus(); + dragOperation = null; + } + clearDragMarker(); + return event.preventDefault(e); + }; + + event.addListener(mouseTarget, "dragstart", this.onDragStart.bind(mouseHandler)); + event.addListener(mouseTarget, "dragend", this.onDragEnd.bind(mouseHandler)); + event.addListener(mouseTarget, "dragenter", this.onDragEnter.bind(mouseHandler)); + event.addListener(mouseTarget, "dragover", this.onDragOver.bind(mouseHandler)); + event.addListener(mouseTarget, "dragleave", this.onDragLeave.bind(mouseHandler)); + event.addListener(mouseTarget, "drop", this.onDrop.bind(mouseHandler)); + + function scrollCursorIntoView(cursor, prevCursor) { + var now = Date.now(); + var vMovement = !prevCursor || cursor.row != prevCursor.row; + var hMovement = !prevCursor || cursor.column != prevCursor.column; + if (!cursorMovedTime || vMovement || hMovement) { + editor.$blockScrolling += 1; + editor.moveCursorToPosition(cursor); + editor.$blockScrolling -= 1; + cursorMovedTime = now; + cursorPointOnCaretMoved = {x: x, y: y}; + } else { + var distance = calcDistance(cursorPointOnCaretMoved.x, cursorPointOnCaretMoved.y, x, y); + if (distance > SCROLL_CURSOR_HYSTERESIS) { + cursorMovedTime = null; + } else if (now - cursorMovedTime >= SCROLL_CURSOR_DELAY) { + editor.renderer.scrollCursorIntoView(); + cursorMovedTime = null; + } + } + } + + function autoScroll(cursor, prevCursor) { + var now = Date.now(); + var lineHeight = editor.renderer.layerConfig.lineHeight; + var characterWidth = editor.renderer.layerConfig.characterWidth; + var editorRect = editor.renderer.scroller.getBoundingClientRect(); + var offsets = { + x: { + left: x - editorRect.left, + right: editorRect.right - x + }, + y: { + top: y - editorRect.top, + bottom: editorRect.bottom - y + } + }; + var nearestXOffset = Math.min(offsets.x.left, offsets.x.right); + var nearestYOffset = Math.min(offsets.y.top, offsets.y.bottom); + var scrollCursor = {row: cursor.row, column: cursor.column}; + if (nearestXOffset / characterWidth <= 2) { + scrollCursor.column += (offsets.x.left < offsets.x.right ? -3 : +2); + } + if (nearestYOffset / lineHeight <= 1) { + scrollCursor.row += (offsets.y.top < offsets.y.bottom ? -1 : +1); + } + var vScroll = cursor.row != scrollCursor.row; + var hScroll = cursor.column != scrollCursor.column; + var vMovement = !prevCursor || cursor.row != prevCursor.row; + if (vScroll || (hScroll && !vMovement)) { + if (!autoScrollStartTime) + autoScrollStartTime = now; + else if (now - autoScrollStartTime >= AUTOSCROLL_DELAY) + editor.renderer.scrollCursorIntoView(scrollCursor); + } else { + autoScrollStartTime = null; + } + } + + function onDragInterval() { + var prevCursor = dragCursor; + dragCursor = editor.renderer.screenToTextCoordinates(x, y); + scrollCursorIntoView(dragCursor, prevCursor); + autoScroll(dragCursor, prevCursor); + } + + function addDragMarker() { + range = editor.selection.toOrientedRange(); + dragSelectionMarker = editor.session.addMarker(range, "ace_selection", editor.getSelectionStyle()); + editor.clearSelection(); + if (editor.isFocused()) + editor.renderer.$cursorLayer.setBlinking(false); + clearInterval(timerId); + onDragInterval(); + timerId = setInterval(onDragInterval, 20); + counter = 0; + event.addListener(document, "mousemove", onMouseMove); + } + + function clearDragMarker() { + clearInterval(timerId); + editor.session.removeMarker(dragSelectionMarker); + dragSelectionMarker = null; + editor.$blockScrolling += 1; + editor.selection.fromOrientedRange(range); + editor.$blockScrolling -= 1; + if (editor.isFocused() && !isInternal) + editor.renderer.$cursorLayer.setBlinking(!editor.getReadOnly()); + range = null; + dragCursor = null; + counter = 0; + autoScrollStartTime = null; + cursorMovedTime = null; + event.removeListener(document, "mousemove", onMouseMove); + } + var onMouseMoveTimer = null; + function onMouseMove() { + if (onMouseMoveTimer == null) { + onMouseMoveTimer = setTimeout(function() { + if (onMouseMoveTimer != null && dragSelectionMarker) + clearDragMarker(); + }, 20); + } + } + + function canAccept(dataTransfer) { + var types = dataTransfer.types; + return !types || Array.prototype.some.call(types, function(type) { + return type == 'text/plain' || type == 'Text'; + }); + } + + function getDropEffect(e) { + var copyAllowed = ['copy', 'copymove', 'all', 'uninitialized']; + var moveAllowed = ['move', 'copymove', 'linkmove', 'all', 'uninitialized']; + + var copyModifierState = useragent.isMac ? e.altKey : e.ctrlKey; + var effectAllowed = "uninitialized"; + try { + effectAllowed = e.dataTransfer.effectAllowed.toLowerCase(); + } catch (e) {} + var dropEffect = "none"; + + if (copyModifierState && copyAllowed.indexOf(effectAllowed) >= 0) + dropEffect = "copy"; + else if (moveAllowed.indexOf(effectAllowed) >= 0) + dropEffect = "move"; + else if (copyAllowed.indexOf(effectAllowed) >= 0) + dropEffect = "copy"; + + return dropEffect; + } +} + +(function() { + + this.dragWait = function() { + var interval = Date.now() - this.mousedownEvent.time; + if (interval > this.editor.getDragDelay()) + this.startDrag(); + }; + + this.dragWaitEnd = function() { + var target = this.editor.container; + target.draggable = false; + this.startSelect(this.mousedownEvent.getDocumentPosition()); + this.selectEnd(); + }; + + this.dragReadyEnd = function(e) { + this.editor.renderer.$cursorLayer.setBlinking(!this.editor.getReadOnly()); + this.editor.unsetStyle("ace_dragging"); + this.editor.renderer.setCursorStyle(""); + this.dragWaitEnd(); + }; + + this.startDrag = function(){ + this.cancelDrag = false; + var editor = this.editor; + var target = editor.container; + target.draggable = true; + editor.renderer.$cursorLayer.setBlinking(false); + editor.setStyle("ace_dragging"); + var cursorStyle = useragent.isWin ? "default" : "move"; + editor.renderer.setCursorStyle(cursorStyle); + this.setState("dragReady"); + }; + + this.onMouseDrag = function(e) { + var target = this.editor.container; + if (useragent.isIE && this.state == "dragReady") { + var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y); + if (distance > 3) + target.dragDrop(); + } + if (this.state === "dragWait") { + var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y); + if (distance > 0) { + target.draggable = false; + this.startSelect(this.mousedownEvent.getDocumentPosition()); + } + } + }; + + this.onMouseDown = function(e) { + if (!this.$dragEnabled) + return; + this.mousedownEvent = e; + var editor = this.editor; + + var inSelection = e.inSelection(); + var button = e.getButton(); + var clickCount = e.domEvent.detail || 1; + if (clickCount === 1 && button === 0 && inSelection) { + if (e.editor.inMultiSelectMode && (e.getAccelKey() || e.getShiftKey())) + return; + this.mousedownEvent.time = Date.now(); + var eventTarget = e.domEvent.target || e.domEvent.srcElement; + if ("unselectable" in eventTarget) + eventTarget.unselectable = "on"; + if (editor.getDragDelay()) { + if (useragent.isWebKit) { + this.cancelDrag = true; + var mouseTarget = editor.container; + mouseTarget.draggable = true; + } + this.setState("dragWait"); + } else { + this.startDrag(); + } + this.captureMouse(e, this.onMouseDrag.bind(this)); + e.defaultPrevented = true; + } + }; + +}).call(DragdropHandler.prototype); + + +function calcDistance(ax, ay, bx, by) { + return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2)); +} + +exports.DragdropHandler = DragdropHandler; + +}); + +ace.define("ace/lib/net",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; +var dom = acequire("./dom"); + +exports.get = function (url, callback) { + var xhr = new XMLHttpRequest(); + xhr.open('GET', url, true); + xhr.onreadystatechange = function () { + if (xhr.readyState === 4) { + callback(xhr.responseText); + } + }; + xhr.send(null); +}; + +exports.loadScript = function(path, callback) { + var head = dom.getDocumentHead(); + var s = document.createElement('script'); + + s.src = path; + head.appendChild(s); + + s.onload = s.onreadystatechange = function(_, isAbort) { + if (isAbort || !s.readyState || s.readyState == "loaded" || s.readyState == "complete") { + s = s.onload = s.onreadystatechange = null; + if (!isAbort) + callback(); + } + }; +}; +exports.qualifyURL = function(url) { + var a = document.createElement('a'); + a.href = url; + return a.href; +}; + +}); + +ace.define("ace/lib/event_emitter",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +var EventEmitter = {}; +var stopPropagation = function() { this.propagationStopped = true; }; +var preventDefault = function() { this.defaultPrevented = true; }; + +EventEmitter._emit = +EventEmitter._dispatchEvent = function(eventName, e) { + this._eventRegistry || (this._eventRegistry = {}); + this._defaultHandlers || (this._defaultHandlers = {}); + + var listeners = this._eventRegistry[eventName] || []; + var defaultHandler = this._defaultHandlers[eventName]; + if (!listeners.length && !defaultHandler) + return; + + if (typeof e != "object" || !e) + e = {}; + + if (!e.type) + e.type = eventName; + if (!e.stopPropagation) + e.stopPropagation = stopPropagation; + if (!e.preventDefault) + e.preventDefault = preventDefault; + + listeners = listeners.slice(); + for (var i=0; i 1) + base = parts[parts.length - 2]; + var path = options[component + "Path"]; + if (path == null) { + path = options.basePath; + } else if (sep == "/") { + component = sep = ""; + } + if (path && path.slice(-1) != "/") + path += "/"; + return path + component + sep + base + this.get("suffix"); +}; + +exports.setModuleUrl = function(name, subst) { + return options.$moduleUrls[name] = subst; +}; + +exports.$loading = {}; +exports.loadModule = function(moduleName, onLoad) { + var module, moduleType; + if (Array.isArray(moduleName)) { + moduleType = moduleName[0]; + moduleName = moduleName[1]; + } + + try { + module = acequire(moduleName); + } catch (e) {} + if (module && !exports.$loading[moduleName]) + return onLoad && onLoad(module); + + if (!exports.$loading[moduleName]) + exports.$loading[moduleName] = []; + + exports.$loading[moduleName].push(onLoad); + + if (exports.$loading[moduleName].length > 1) + return; + + var afterLoad = function() { + acequire([moduleName], function(module) { + exports._emit("load.module", {name: moduleName, module: module}); + var listeners = exports.$loading[moduleName]; + exports.$loading[moduleName] = null; + listeners.forEach(function(onLoad) { + onLoad && onLoad(module); + }); + }); + }; + + if (!exports.get("packaged")) + return afterLoad(); + net.loadScript(exports.moduleUrl(moduleName, moduleType), afterLoad); +}; +init(true);function init(packaged) { + + if (!global || !global.document) + return; + + options.packaged = packaged || acequire.packaged || module.packaged || (global.define && define.packaged); + + var scriptOptions = {}; + var scriptUrl = ""; + var currentScript = (document.currentScript || document._currentScript ); // native or polyfill + var currentDocument = currentScript && currentScript.ownerDocument || document; + + var scripts = currentDocument.getElementsByTagName("script"); + for (var i=0; i 0){ + if (action == 0x10){ + for(i = condPos; i < ix; i++){ + levels[i] = 1; + } + condPos = -1; + } else { + condPos = -1; + } + } + cond = impTab[newState][6]; + if (cond){ + if(condPos == -1){ + condPos = ix; + } + }else{ + if (condPos > -1){ + for(i = condPos; i < ix; i++){ + levels[i] = newLevel; + } + condPos = -1; + } + } + if (charTypes[ix] == B){ + levels[ix] = 0; + } + hiLevel |= newLevel; + } + if (hasUBAT_S){ + for(i = 0; i < len; i++){ + if(charTypes[i] == S){ + levels[i] = dir; + for(var j = i - 1; j >= 0; j--){ + if(charTypes[j] == WS){ + levels[j] = dir; + }else{ + break; + } + } + } + } + } +} + +function _invertLevel(lev, levels, _array) { + if (hiLevel < lev){ + return; + } + if (lev == 1 && dir == RTL && !hasUBAT_B){ + _array.reverse(); + return; + } + var len = _array.length, start = 0, end, lo, hi, tmp; + while(start < len){ + if (levels[start] >= lev){ + end = start + 1; + while(end < len && levels[end] >= lev){ + end++; + } + for(lo = start, hi = end - 1 ; lo < hi; lo++, hi--){ + tmp = _array[lo]; + _array[lo] = _array[hi]; + _array[hi] = tmp; + } + start = end; + } + start++; + } +} + +function _getCharClass(chars, types, classes, ix) { + var cType = types[ix], wType, nType, len, i; + switch(cType){ + case L: + case R: + lastArabic = false; + case ON: + case AN: + return cType; + case EN: + return lastArabic ? AN : EN; + case AL: + lastArabic = true; + hasUBAT_AL = true; + return R; + case WS: + return ON; + case CS: + if (ix < 1 || (ix + 1) >= types.length || + ((wType = classes[ix - 1]) != EN && wType != AN) || + ((nType = types[ix + 1]) != EN && nType != AN)){ + return ON; + } + if (lastArabic){nType = AN;} + return nType == wType ? nType : ON; + case ES: + wType = ix > 0 ? classes[ix - 1] : B; + if (wType == EN && (ix + 1) < types.length && types[ix + 1] == EN){ + return EN; + } + return ON; + case ET: + if (ix > 0 && classes[ix - 1] == EN){ + return EN; + } + if (lastArabic){ + return ON; + } + i = ix + 1; + len = types.length; + while (i < len && types[i] == ET){ + i++; + } + if (i < len && types[i] == EN){ + return EN; + } + return ON; + case NSM: + len = types.length; + i = ix + 1; + while (i < len && types[i] == NSM){ + i++; + } + if (i < len){ + var c = chars[ix], rtlCandidate = (c >= 0x0591 && c <= 0x08FF) || c == 0xFB1E; + + wType = types[i]; + if (rtlCandidate && (wType == R || wType == AL)){ + return R; + } + } + + if (ix < 1 || (wType = types[ix - 1]) == B){ + return ON; + } + return classes[ix - 1]; + case B: + lastArabic = false; + hasUBAT_B = true; + return dir; + case S: + hasUBAT_S = true; + return ON; + case LRE: + case RLE: + case LRO: + case RLO: + case PDF: + lastArabic = false; + case BN: + return ON; + } +} + +function _getCharacterType( ch ) { + var uc = ch.charCodeAt(0), hi = uc >> 8; + + if (hi == 0) { + return ((uc > 0x00BF) ? L : UnicodeTBL00[uc]); + } else if (hi == 5) { + return (/[\u0591-\u05f4]/.test(ch) ? R : L); + } else if (hi == 6) { + if (/[\u0610-\u061a\u064b-\u065f\u06d6-\u06e4\u06e7-\u06ed]/.test(ch)) + return NSM; + else if (/[\u0660-\u0669\u066b-\u066c]/.test(ch)) + return AN; + else if (uc == 0x066A) + return ET; + else if (/[\u06f0-\u06f9]/.test(ch)) + return EN; + else + return AL; + } else if (hi == 0x20 && uc <= 0x205F) { + return UnicodeTBL20[uc & 0xFF]; + } else if (hi == 0xFE) { + return (uc >= 0xFE70 ? AL : ON); + } + return ON; +} + +function _isArabicDiacritics( ch ) { + return (ch >= '\u064b' && ch <= '\u0655'); +} +exports.L = L; +exports.R = R; +exports.EN = EN; +exports.ON_R = 3; +exports.AN = 4; +exports.R_H = 5; +exports.B = 6; + +exports.DOT = "\xB7"; +exports.doBidiReorder = function(text, textCharTypes, isRtl) { + if (text.length < 2) + return {}; + + var chars = text.split(""), logicalFromVisual = new Array(chars.length), + bidiLevels = new Array(chars.length), levels = []; + + dir = isRtl ? RTL : LTR; + + _computeLevels(chars, levels, chars.length, textCharTypes); + + for (var i = 0; i < logicalFromVisual.length; logicalFromVisual[i] = i, i++); + + _invertLevel(2, levels, logicalFromVisual); + _invertLevel(1, levels, logicalFromVisual); + + for (var i = 0; i < logicalFromVisual.length - 1; i++) { //fix levels to reflect character width + if (textCharTypes[i] === AN) { + levels[i] = exports.AN; + } else if (levels[i] === R && ((textCharTypes[i] > AL && textCharTypes[i] < LRE) + || textCharTypes[i] === ON || textCharTypes[i] === BN)) { + levels[i] = exports.ON_R; + } else if ((i > 0 && chars[i - 1] === '\u0644') && /\u0622|\u0623|\u0625|\u0627/.test(chars[i])) { + levels[i - 1] = levels[i] = exports.R_H; + i++; + } + } + if (chars[chars.length - 1] === exports.DOT) + levels[chars.length - 1] = exports.B; + + for (var i = 0; i < logicalFromVisual.length; i++) { + bidiLevels[i] = levels[logicalFromVisual[i]]; + } + + return {'logicalFromVisual': logicalFromVisual, 'bidiLevels': bidiLevels}; +}; +exports.hasBidiCharacters = function(text, textCharTypes){ + var ret = false; + for (var i = 0; i < text.length; i++){ + textCharTypes[i] = _getCharacterType(text.charAt(i)); + if (!ret && (textCharTypes[i] == R || textCharTypes[i] == AL)) + ret = true; + } + return ret; +}; +exports.getVisualFromLogicalIdx = function(logIdx, rowMap) { + for (var i = 0; i < rowMap.logicalFromVisual.length; i++) { + if (rowMap.logicalFromVisual[i] == logIdx) + return i; + } + return 0; +}; + +}); + +ace.define("ace/bidihandler",["require","exports","module","ace/lib/bidiutil","ace/lib/lang","ace/lib/useragent"], function(acequire, exports, module) { +"use strict"; + +var bidiUtil = acequire("./lib/bidiutil"); +var lang = acequire("./lib/lang"); +var useragent = acequire("./lib/useragent"); +var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; +var BidiHandler = function(session) { + this.session = session; + this.bidiMap = {}; + this.currentRow = null; + this.bidiUtil = bidiUtil; + this.charWidths = []; + this.EOL = "\xAC"; + this.showInvisibles = true; + this.isRtlDir = false; + this.line = ""; + this.wrapIndent = 0; + this.isLastRow = false; + this.EOF = "\xB6"; + this.seenBidi = false; +}; + +(function() { + this.isBidiRow = function(screenRow, docRow, splitIndex) { + if (!this.seenBidi) + return false; + if (screenRow !== this.currentRow) { + this.currentRow = screenRow; + this.updateRowLine(docRow, splitIndex); + this.updateBidiMap(); + } + return this.bidiMap.bidiLevels; + }; + + this.onChange = function(delta) { + if (!this.seenBidi) { + if (delta.action == "insert" && bidiRE.test(delta.lines.join("\n"))) { + this.seenBidi = true; + this.currentRow = null; + } + } + else { + this.currentRow = null; + } + }; + + this.getDocumentRow = function() { + var docRow = 0; + var rowCache = this.session.$screenRowCache; + if (rowCache.length) { + var index = this.session.$getRowCacheIndex(rowCache, this.currentRow); + if (index >= 0) + docRow = this.session.$docRowCache[index]; + } + + return docRow; + }; + + this.getSplitIndex = function() { + var splitIndex = 0; + var rowCache = this.session.$screenRowCache; + if (rowCache.length) { + var currentIndex, prevIndex = this.session.$getRowCacheIndex(rowCache, this.currentRow); + while (this.currentRow - splitIndex > 0) { + currentIndex = this.session.$getRowCacheIndex(rowCache, this.currentRow - splitIndex - 1); + if (currentIndex !== prevIndex) + break; + + prevIndex = currentIndex; + splitIndex++; + } + } + + return splitIndex; + }; + + this.updateRowLine = function(docRow, splitIndex) { + if (docRow === undefined) + docRow = this.getDocumentRow(); + + this.wrapIndent = 0; + this.isLastRow = (docRow === this.session.getLength() - 1); + this.line = this.session.getLine(docRow); + if (this.session.$useWrapMode) { + var splits = this.session.$wrapData[docRow]; + if (splits) { + if (splitIndex === undefined) + splitIndex = this.getSplitIndex(); + + if(splitIndex > 0 && splits.length) { + this.wrapIndent = splits.indent; + this.line = (splitIndex < splits.length) ? + this.line.substring(splits[splitIndex - 1], splits[splits.length - 1]) : + this.line.substring(splits[splits.length - 1]); + } else { + this.line = this.line.substring(0, splits[splitIndex]); + } + } + } + var session = this.session, shift = 0, size; + this.line = this.line.replace(/\t|[\u1100-\u2029, \u202F-\uFFE6]/g, function(ch, i){ + if (ch === '\t' || session.isFullWidth(ch.charCodeAt(0))) { + size = (ch === '\t') ? session.getScreenTabSize(i + shift) : 2; + shift += size - 1; + return lang.stringRepeat(bidiUtil.DOT, size); + } + return ch; + }); + }; + + this.updateBidiMap = function() { + var textCharTypes = [], endOfLine = this.isLastRow ? this.EOF : this.EOL; + var line = this.line + (this.showInvisibles ? endOfLine : bidiUtil.DOT); + if (bidiUtil.hasBidiCharacters(line, textCharTypes)) { + this.bidiMap = bidiUtil.doBidiReorder(line, textCharTypes, this.isRtlDir); + } else { + this.bidiMap = {}; + } + }; + this.markAsDirty = function() { + this.currentRow = null; + }; + this.updateCharacterWidths = function(fontMetrics) { + if (!this.seenBidi) + return; + if (this.characterWidth === fontMetrics.$characterSize.width) + return; + + var characterWidth = this.characterWidth = fontMetrics.$characterSize.width; + var bidiCharWidth = fontMetrics.$measureCharWidth("\u05d4"); + + this.charWidths[bidiUtil.L] = this.charWidths[bidiUtil.EN] = this.charWidths[bidiUtil.ON_R] = characterWidth; + this.charWidths[bidiUtil.R] = this.charWidths[bidiUtil.AN] = bidiCharWidth; + this.charWidths[bidiUtil.R_H] = useragent.isChrome ? bidiCharWidth : bidiCharWidth * 0.45; + this.charWidths[bidiUtil.B] = 0; + + this.currentRow = null; + }; + + this.getShowInvisibles = function() { + return this.showInvisibles; + }; + + this.setShowInvisibles = function(showInvisibles) { + this.showInvisibles = showInvisibles; + this.currentRow = null; + }; + + this.setEolChar = function(eolChar) { + this.EOL = eolChar; + }; + + this.setTextDir = function(isRtlDir) { + this.isRtlDir = isRtlDir; + }; + this.getPosLeft = function(col) { + col -= this.wrapIndent; + var visualIdx = bidiUtil.getVisualFromLogicalIdx(col > 0 ? col - 1 : 0, this.bidiMap), + levels = this.bidiMap.bidiLevels, left = 0; + + if (col === 0 && levels[visualIdx] % 2 !== 0) + visualIdx++; + + for (var i = 0; i < visualIdx; i++) { + left += this.charWidths[levels[i]]; + } + + if (col !== 0 && levels[visualIdx] % 2 === 0) + left += this.charWidths[levels[visualIdx]]; + + if (this.wrapIndent) + left += this.wrapIndent * this.charWidths[bidiUtil.L]; + + return left; + }; + this.getSelections = function(startCol, endCol) { + var map = this.bidiMap, levels = map.bidiLevels, level, offset = this.wrapIndent * this.charWidths[bidiUtil.L], selections = [], + selColMin = Math.min(startCol, endCol) - this.wrapIndent, selColMax = Math.max(startCol, endCol) - this.wrapIndent, + isSelected = false, isSelectedPrev = false, selectionStart = 0; + + for (var logIdx, visIdx = 0; visIdx < levels.length; visIdx++) { + logIdx = map.logicalFromVisual[visIdx]; + level = levels[visIdx]; + isSelected = (logIdx >= selColMin) && (logIdx < selColMax); + if (isSelected && !isSelectedPrev) { + selectionStart = offset; + } else if (!isSelected && isSelectedPrev) { + selections.push({left: selectionStart, width: offset - selectionStart}); + } + offset += this.charWidths[level]; + isSelectedPrev = isSelected; + } + + if (isSelected && (visIdx === levels.length)) { + selections.push({left: selectionStart, width: offset - selectionStart}); + } + + return selections; + }; + this.offsetToCol = function(posX) { + var logicalIdx = 0, posX = Math.max(posX, 0), + offset = 0, visualIdx = 0, levels = this.bidiMap.bidiLevels, + charWidth = this.charWidths[levels[visualIdx]]; + + if (this.wrapIndent) { + posX -= this.wrapIndent * this.charWidths[bidiUtil.L]; + } + + while(posX > offset + charWidth/2) { + offset += charWidth; + if(visualIdx === levels.length - 1) { + charWidth = 0; + break; + } + charWidth = this.charWidths[levels[++visualIdx]]; + } + + if (visualIdx > 0 && (levels[visualIdx - 1] % 2 !== 0) && (levels[visualIdx] % 2 === 0)){ + if(posX < offset) + visualIdx--; + logicalIdx = this.bidiMap.logicalFromVisual[visualIdx]; + + } else if (visualIdx > 0 && (levels[visualIdx - 1] % 2 === 0) && (levels[visualIdx] % 2 !== 0)){ + logicalIdx = 1 + ((posX > offset) ? this.bidiMap.logicalFromVisual[visualIdx] + : this.bidiMap.logicalFromVisual[visualIdx - 1]); + + } else if ((this.isRtlDir && visualIdx === levels.length - 1 && charWidth === 0 && (levels[visualIdx - 1] % 2 === 0)) + || (!this.isRtlDir && visualIdx === 0 && (levels[visualIdx] % 2 !== 0))){ + logicalIdx = 1 + this.bidiMap.logicalFromVisual[visualIdx]; + } else { + if (visualIdx > 0 && (levels[visualIdx - 1] % 2 !== 0) && charWidth !== 0) + visualIdx--; + logicalIdx = this.bidiMap.logicalFromVisual[visualIdx]; + } + + return (logicalIdx + this.wrapIndent); + }; + +}).call(BidiHandler.prototype); + +exports.BidiHandler = BidiHandler; +}); + +ace.define("ace/range",["require","exports","module"], function(acequire, exports, module) { +"use strict"; +var comparePoints = function(p1, p2) { + return p1.row - p2.row || p1.column - p2.column; +}; +var Range = function(startRow, startColumn, endRow, endColumn) { + this.start = { + row: startRow, + column: startColumn + }; + + this.end = { + row: endRow, + column: endColumn + }; +}; + +(function() { + this.isEqual = function(range) { + return this.start.row === range.start.row && + this.end.row === range.end.row && + this.start.column === range.start.column && + this.end.column === range.end.column; + }; + this.toString = function() { + return ("Range: [" + this.start.row + "/" + this.start.column + + "] -> [" + this.end.row + "/" + this.end.column + "]"); + }; + + this.contains = function(row, column) { + return this.compare(row, column) == 0; + }; + this.compareRange = function(range) { + var cmp, + end = range.end, + start = range.start; + + cmp = this.compare(end.row, end.column); + if (cmp == 1) { + cmp = this.compare(start.row, start.column); + if (cmp == 1) { + return 2; + } else if (cmp == 0) { + return 1; + } else { + return 0; + } + } else if (cmp == -1) { + return -2; + } else { + cmp = this.compare(start.row, start.column); + if (cmp == -1) { + return -1; + } else if (cmp == 1) { + return 42; + } else { + return 0; + } + } + }; + this.comparePoint = function(p) { + return this.compare(p.row, p.column); + }; + this.containsRange = function(range) { + return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; + }; + this.intersects = function(range) { + var cmp = this.compareRange(range); + return (cmp == -1 || cmp == 0 || cmp == 1); + }; + this.isEnd = function(row, column) { + return this.end.row == row && this.end.column == column; + }; + this.isStart = function(row, column) { + return this.start.row == row && this.start.column == column; + }; + this.setStart = function(row, column) { + if (typeof row == "object") { + this.start.column = row.column; + this.start.row = row.row; + } else { + this.start.row = row; + this.start.column = column; + } + }; + this.setEnd = function(row, column) { + if (typeof row == "object") { + this.end.column = row.column; + this.end.row = row.row; + } else { + this.end.row = row; + this.end.column = column; + } + }; + this.inside = function(row, column) { + if (this.compare(row, column) == 0) { + if (this.isEnd(row, column) || this.isStart(row, column)) { + return false; + } else { + return true; + } + } + return false; + }; + this.insideStart = function(row, column) { + if (this.compare(row, column) == 0) { + if (this.isEnd(row, column)) { + return false; + } else { + return true; + } + } + return false; + }; + this.insideEnd = function(row, column) { + if (this.compare(row, column) == 0) { + if (this.isStart(row, column)) { + return false; + } else { + return true; + } + } + return false; + }; + this.compare = function(row, column) { + if (!this.isMultiLine()) { + if (row === this.start.row) { + return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0); + } + } + + if (row < this.start.row) + return -1; + + if (row > this.end.row) + return 1; + + if (this.start.row === row) + return column >= this.start.column ? 0 : -1; + + if (this.end.row === row) + return column <= this.end.column ? 0 : 1; + + return 0; + }; + this.compareStart = function(row, column) { + if (this.start.row == row && this.start.column == column) { + return -1; + } else { + return this.compare(row, column); + } + }; + this.compareEnd = function(row, column) { + if (this.end.row == row && this.end.column == column) { + return 1; + } else { + return this.compare(row, column); + } + }; + this.compareInside = function(row, column) { + if (this.end.row == row && this.end.column == column) { + return 1; + } else if (this.start.row == row && this.start.column == column) { + return -1; + } else { + return this.compare(row, column); + } + }; + this.clipRows = function(firstRow, lastRow) { + if (this.end.row > lastRow) + var end = {row: lastRow + 1, column: 0}; + else if (this.end.row < firstRow) + var end = {row: firstRow, column: 0}; + + if (this.start.row > lastRow) + var start = {row: lastRow + 1, column: 0}; + else if (this.start.row < firstRow) + var start = {row: firstRow, column: 0}; + + return Range.fromPoints(start || this.start, end || this.end); + }; + this.extend = function(row, column) { + var cmp = this.compare(row, column); + + if (cmp == 0) + return this; + else if (cmp == -1) + var start = {row: row, column: column}; + else + var end = {row: row, column: column}; + + return Range.fromPoints(start || this.start, end || this.end); + }; + + this.isEmpty = function() { + return (this.start.row === this.end.row && this.start.column === this.end.column); + }; + this.isMultiLine = function() { + return (this.start.row !== this.end.row); + }; + this.clone = function() { + return Range.fromPoints(this.start, this.end); + }; + this.collapseRows = function() { + if (this.end.column == 0) + return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0); + else + return new Range(this.start.row, 0, this.end.row, 0); + }; + this.toScreenRange = function(session) { + var screenPosStart = session.documentToScreenPosition(this.start); + var screenPosEnd = session.documentToScreenPosition(this.end); + + return new Range( + screenPosStart.row, screenPosStart.column, + screenPosEnd.row, screenPosEnd.column + ); + }; + this.moveBy = function(row, column) { + this.start.row += row; + this.start.column += column; + this.end.row += row; + this.end.column += column; + }; + +}).call(Range.prototype); +Range.fromPoints = function(start, end) { + return new Range(start.row, start.column, end.row, end.column); +}; +Range.comparePoints = comparePoints; + +Range.comparePoints = function(p1, p2) { + return p1.row - p2.row || p1.column - p2.column; +}; + + +exports.Range = Range; +}); + +ace.define("ace/selection",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter","ace/range"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var lang = acequire("./lib/lang"); +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var Range = acequire("./range").Range; +var Selection = function(session) { + this.session = session; + this.doc = session.getDocument(); + + this.clearSelection(); + this.lead = this.selectionLead = this.doc.createAnchor(0, 0); + this.anchor = this.selectionAnchor = this.doc.createAnchor(0, 0); + + var self = this; + this.lead.on("change", function(e) { + self._emit("changeCursor"); + if (!self.$isEmpty) + self._emit("changeSelection"); + if (!self.$keepDesiredColumnOnChange && e.old.column != e.value.column) + self.$desiredColumn = null; + }); + + this.selectionAnchor.on("change", function() { + if (!self.$isEmpty) + self._emit("changeSelection"); + }); +}; + +(function() { + + oop.implement(this, EventEmitter); + this.isEmpty = function() { + return (this.$isEmpty || ( + this.anchor.row == this.lead.row && + this.anchor.column == this.lead.column + )); + }; + this.isMultiLine = function() { + if (this.isEmpty()) { + return false; + } + + return this.getRange().isMultiLine(); + }; + this.getCursor = function() { + return this.lead.getPosition(); + }; + this.setSelectionAnchor = function(row, column) { + this.anchor.setPosition(row, column); + + if (this.$isEmpty) { + this.$isEmpty = false; + this._emit("changeSelection"); + } + }; + this.getSelectionAnchor = function() { + if (this.$isEmpty) + return this.getSelectionLead(); + else + return this.anchor.getPosition(); + }; + this.getSelectionLead = function() { + return this.lead.getPosition(); + }; + this.shiftSelection = function(columns) { + if (this.$isEmpty) { + this.moveCursorTo(this.lead.row, this.lead.column + columns); + return; + } + + var anchor = this.getSelectionAnchor(); + var lead = this.getSelectionLead(); + + var isBackwards = this.isBackwards(); + + if (!isBackwards || anchor.column !== 0) + this.setSelectionAnchor(anchor.row, anchor.column + columns); + + if (isBackwards || lead.column !== 0) { + this.$moveSelection(function() { + this.moveCursorTo(lead.row, lead.column + columns); + }); + } + }; + this.isBackwards = function() { + var anchor = this.anchor; + var lead = this.lead; + return (anchor.row > lead.row || (anchor.row == lead.row && anchor.column > lead.column)); + }; + this.getRange = function() { + var anchor = this.anchor; + var lead = this.lead; + + if (this.isEmpty()) + return Range.fromPoints(lead, lead); + + if (this.isBackwards()) { + return Range.fromPoints(lead, anchor); + } + else { + return Range.fromPoints(anchor, lead); + } + }; + this.clearSelection = function() { + if (!this.$isEmpty) { + this.$isEmpty = true; + this._emit("changeSelection"); + } + }; + this.selectAll = function() { + var lastRow = this.doc.getLength() - 1; + this.setSelectionAnchor(0, 0); + this.moveCursorTo(lastRow, this.doc.getLine(lastRow).length); + }; + this.setRange = + this.setSelectionRange = function(range, reverse) { + if (reverse) { + this.setSelectionAnchor(range.end.row, range.end.column); + this.selectTo(range.start.row, range.start.column); + } else { + this.setSelectionAnchor(range.start.row, range.start.column); + this.selectTo(range.end.row, range.end.column); + } + if (this.getRange().isEmpty()) + this.$isEmpty = true; + this.$desiredColumn = null; + }; + + this.$moveSelection = function(mover) { + var lead = this.lead; + if (this.$isEmpty) + this.setSelectionAnchor(lead.row, lead.column); + + mover.call(this); + }; + this.selectTo = function(row, column) { + this.$moveSelection(function() { + this.moveCursorTo(row, column); + }); + }; + this.selectToPosition = function(pos) { + this.$moveSelection(function() { + this.moveCursorToPosition(pos); + }); + }; + this.moveTo = function(row, column) { + this.clearSelection(); + this.moveCursorTo(row, column); + }; + this.moveToPosition = function(pos) { + this.clearSelection(); + this.moveCursorToPosition(pos); + }; + this.selectUp = function() { + this.$moveSelection(this.moveCursorUp); + }; + this.selectDown = function() { + this.$moveSelection(this.moveCursorDown); + }; + this.selectRight = function() { + this.$moveSelection(this.moveCursorRight); + }; + this.selectLeft = function() { + this.$moveSelection(this.moveCursorLeft); + }; + this.selectLineStart = function() { + this.$moveSelection(this.moveCursorLineStart); + }; + this.selectLineEnd = function() { + this.$moveSelection(this.moveCursorLineEnd); + }; + this.selectFileEnd = function() { + this.$moveSelection(this.moveCursorFileEnd); + }; + this.selectFileStart = function() { + this.$moveSelection(this.moveCursorFileStart); + }; + this.selectWordRight = function() { + this.$moveSelection(this.moveCursorWordRight); + }; + this.selectWordLeft = function() { + this.$moveSelection(this.moveCursorWordLeft); + }; + this.getWordRange = function(row, column) { + if (typeof column == "undefined") { + var cursor = row || this.lead; + row = cursor.row; + column = cursor.column; + } + return this.session.getWordRange(row, column); + }; + this.selectWord = function() { + this.setSelectionRange(this.getWordRange()); + }; + this.selectAWord = function() { + var cursor = this.getCursor(); + var range = this.session.getAWordRange(cursor.row, cursor.column); + this.setSelectionRange(range); + }; + + this.getLineRange = function(row, excludeLastChar) { + var rowStart = typeof row == "number" ? row : this.lead.row; + var rowEnd; + + var foldLine = this.session.getFoldLine(rowStart); + if (foldLine) { + rowStart = foldLine.start.row; + rowEnd = foldLine.end.row; + } else { + rowEnd = rowStart; + } + if (excludeLastChar === true) + return new Range(rowStart, 0, rowEnd, this.session.getLine(rowEnd).length); + else + return new Range(rowStart, 0, rowEnd + 1, 0); + }; + this.selectLine = function() { + this.setSelectionRange(this.getLineRange()); + }; + this.moveCursorUp = function() { + this.moveCursorBy(-1, 0); + }; + this.moveCursorDown = function() { + this.moveCursorBy(1, 0); + }; + this.wouldMoveIntoSoftTab = function(cursor, tabSize, direction) { + var start = cursor.column; + var end = cursor.column + tabSize; + + if (direction < 0) { + start = cursor.column - tabSize; + end = cursor.column; + } + return this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(start, end).split(" ").length-1 == tabSize; + }; + this.moveCursorLeft = function() { + var cursor = this.lead.getPosition(), + fold; + + if (fold = this.session.getFoldAt(cursor.row, cursor.column, -1)) { + this.moveCursorTo(fold.start.row, fold.start.column); + } else if (cursor.column === 0) { + if (cursor.row > 0) { + this.moveCursorTo(cursor.row - 1, this.doc.getLine(cursor.row - 1).length); + } + } + else { + var tabSize = this.session.getTabSize(); + if (this.wouldMoveIntoSoftTab(cursor, tabSize, -1) && !this.session.getNavigateWithinSoftTabs()) { + this.moveCursorBy(0, -tabSize); + } else { + this.moveCursorBy(0, -1); + } + } + }; + this.moveCursorRight = function() { + var cursor = this.lead.getPosition(), + fold; + if (fold = this.session.getFoldAt(cursor.row, cursor.column, 1)) { + this.moveCursorTo(fold.end.row, fold.end.column); + } + else if (this.lead.column == this.doc.getLine(this.lead.row).length) { + if (this.lead.row < this.doc.getLength() - 1) { + this.moveCursorTo(this.lead.row + 1, 0); + } + } + else { + var tabSize = this.session.getTabSize(); + var cursor = this.lead; + if (this.wouldMoveIntoSoftTab(cursor, tabSize, 1) && !this.session.getNavigateWithinSoftTabs()) { + this.moveCursorBy(0, tabSize); + } else { + this.moveCursorBy(0, 1); + } + } + }; + this.moveCursorLineStart = function() { + var row = this.lead.row; + var column = this.lead.column; + var screenRow = this.session.documentToScreenRow(row, column); + var firstColumnPosition = this.session.screenToDocumentPosition(screenRow, 0); + var beforeCursor = this.session.getDisplayLine( + row, null, firstColumnPosition.row, + firstColumnPosition.column + ); + + var leadingSpace = beforeCursor.match(/^\s*/); + if (leadingSpace[0].length != column && !this.session.$useEmacsStyleLineStart) + firstColumnPosition.column += leadingSpace[0].length; + this.moveCursorToPosition(firstColumnPosition); + }; + this.moveCursorLineEnd = function() { + var lead = this.lead; + var lineEnd = this.session.getDocumentLastRowColumnPosition(lead.row, lead.column); + if (this.lead.column == lineEnd.column) { + var line = this.session.getLine(lineEnd.row); + if (lineEnd.column == line.length) { + var textEnd = line.search(/\s+$/); + if (textEnd > 0) + lineEnd.column = textEnd; + } + } + + this.moveCursorTo(lineEnd.row, lineEnd.column); + }; + this.moveCursorFileEnd = function() { + var row = this.doc.getLength() - 1; + var column = this.doc.getLine(row).length; + this.moveCursorTo(row, column); + }; + this.moveCursorFileStart = function() { + this.moveCursorTo(0, 0); + }; + this.moveCursorLongWordRight = function() { + var row = this.lead.row; + var column = this.lead.column; + var line = this.doc.getLine(row); + var rightOfCursor = line.substring(column); + + var match; + this.session.nonTokenRe.lastIndex = 0; + this.session.tokenRe.lastIndex = 0; + var fold = this.session.getFoldAt(row, column, 1); + if (fold) { + this.moveCursorTo(fold.end.row, fold.end.column); + return; + } + if (match = this.session.nonTokenRe.exec(rightOfCursor)) { + column += this.session.nonTokenRe.lastIndex; + this.session.nonTokenRe.lastIndex = 0; + rightOfCursor = line.substring(column); + } + if (column >= line.length) { + this.moveCursorTo(row, line.length); + this.moveCursorRight(); + if (row < this.doc.getLength() - 1) + this.moveCursorWordRight(); + return; + } + if (match = this.session.tokenRe.exec(rightOfCursor)) { + column += this.session.tokenRe.lastIndex; + this.session.tokenRe.lastIndex = 0; + } + + this.moveCursorTo(row, column); + }; + this.moveCursorLongWordLeft = function() { + var row = this.lead.row; + var column = this.lead.column; + var fold; + if (fold = this.session.getFoldAt(row, column, -1)) { + this.moveCursorTo(fold.start.row, fold.start.column); + return; + } + + var str = this.session.getFoldStringAt(row, column, -1); + if (str == null) { + str = this.doc.getLine(row).substring(0, column); + } + + var leftOfCursor = lang.stringReverse(str); + var match; + this.session.nonTokenRe.lastIndex = 0; + this.session.tokenRe.lastIndex = 0; + if (match = this.session.nonTokenRe.exec(leftOfCursor)) { + column -= this.session.nonTokenRe.lastIndex; + leftOfCursor = leftOfCursor.slice(this.session.nonTokenRe.lastIndex); + this.session.nonTokenRe.lastIndex = 0; + } + if (column <= 0) { + this.moveCursorTo(row, 0); + this.moveCursorLeft(); + if (row > 0) + this.moveCursorWordLeft(); + return; + } + if (match = this.session.tokenRe.exec(leftOfCursor)) { + column -= this.session.tokenRe.lastIndex; + this.session.tokenRe.lastIndex = 0; + } + + this.moveCursorTo(row, column); + }; + + this.$shortWordEndIndex = function(rightOfCursor) { + var match, index = 0, ch; + var whitespaceRe = /\s/; + var tokenRe = this.session.tokenRe; + + tokenRe.lastIndex = 0; + if (match = this.session.tokenRe.exec(rightOfCursor)) { + index = this.session.tokenRe.lastIndex; + } else { + while ((ch = rightOfCursor[index]) && whitespaceRe.test(ch)) + index ++; + + if (index < 1) { + tokenRe.lastIndex = 0; + while ((ch = rightOfCursor[index]) && !tokenRe.test(ch)) { + tokenRe.lastIndex = 0; + index ++; + if (whitespaceRe.test(ch)) { + if (index > 2) { + index--; + break; + } else { + while ((ch = rightOfCursor[index]) && whitespaceRe.test(ch)) + index ++; + if (index > 2) + break; + } + } + } + } + } + tokenRe.lastIndex = 0; + + return index; + }; + + this.moveCursorShortWordRight = function() { + var row = this.lead.row; + var column = this.lead.column; + var line = this.doc.getLine(row); + var rightOfCursor = line.substring(column); + + var fold = this.session.getFoldAt(row, column, 1); + if (fold) + return this.moveCursorTo(fold.end.row, fold.end.column); + + if (column == line.length) { + var l = this.doc.getLength(); + do { + row++; + rightOfCursor = this.doc.getLine(row); + } while (row < l && /^\s*$/.test(rightOfCursor)); + + if (!/^\s+/.test(rightOfCursor)) + rightOfCursor = ""; + column = 0; + } + + var index = this.$shortWordEndIndex(rightOfCursor); + + this.moveCursorTo(row, column + index); + }; + + this.moveCursorShortWordLeft = function() { + var row = this.lead.row; + var column = this.lead.column; + + var fold; + if (fold = this.session.getFoldAt(row, column, -1)) + return this.moveCursorTo(fold.start.row, fold.start.column); + + var line = this.session.getLine(row).substring(0, column); + if (column === 0) { + do { + row--; + line = this.doc.getLine(row); + } while (row > 0 && /^\s*$/.test(line)); + + column = line.length; + if (!/\s+$/.test(line)) + line = ""; + } + + var leftOfCursor = lang.stringReverse(line); + var index = this.$shortWordEndIndex(leftOfCursor); + + return this.moveCursorTo(row, column - index); + }; + + this.moveCursorWordRight = function() { + if (this.session.$selectLongWords) + this.moveCursorLongWordRight(); + else + this.moveCursorShortWordRight(); + }; + + this.moveCursorWordLeft = function() { + if (this.session.$selectLongWords) + this.moveCursorLongWordLeft(); + else + this.moveCursorShortWordLeft(); + }; + this.moveCursorBy = function(rows, chars) { + var screenPos = this.session.documentToScreenPosition( + this.lead.row, + this.lead.column + ); + + var offsetX; + + if (chars === 0) { + if (rows !== 0) { + if (this.session.$bidiHandler.isBidiRow(screenPos.row, this.lead.row)) { + offsetX = this.session.$bidiHandler.getPosLeft(screenPos.column); + screenPos.column = Math.round(offsetX / this.session.$bidiHandler.charWidths[0]); + } else { + offsetX = screenPos.column * this.session.$bidiHandler.charWidths[0]; + } + } + + if (this.$desiredColumn) + screenPos.column = this.$desiredColumn; + else + this.$desiredColumn = screenPos.column; + } + + var docPos = this.session.screenToDocumentPosition(screenPos.row + rows, screenPos.column, offsetX); + + if (rows !== 0 && chars === 0 && docPos.row === this.lead.row && docPos.column === this.lead.column) { + if (this.session.lineWidgets && this.session.lineWidgets[docPos.row]) { + if (docPos.row > 0 || rows > 0) + docPos.row++; + } + } + this.moveCursorTo(docPos.row, docPos.column + chars, chars === 0); + }; + this.moveCursorToPosition = function(position) { + this.moveCursorTo(position.row, position.column); + }; + this.moveCursorTo = function(row, column, keepDesiredColumn) { + var fold = this.session.getFoldAt(row, column, 1); + if (fold) { + row = fold.start.row; + column = fold.start.column; + } + + this.$keepDesiredColumnOnChange = true; + var line = this.session.getLine(row); + if (/[\uDC00-\uDFFF]/.test(line.charAt(column)) && line.charAt(column - 1)) { + if (this.lead.row == row && this.lead.column == column + 1) + column = column - 1; + else + column = column + 1; + } + this.lead.setPosition(row, column); + this.$keepDesiredColumnOnChange = false; + + if (!keepDesiredColumn) + this.$desiredColumn = null; + }; + this.moveCursorToScreen = function(row, column, keepDesiredColumn) { + var pos = this.session.screenToDocumentPosition(row, column); + this.moveCursorTo(pos.row, pos.column, keepDesiredColumn); + }; + this.detach = function() { + this.lead.detach(); + this.anchor.detach(); + this.session = this.doc = null; + }; + + this.fromOrientedRange = function(range) { + this.setSelectionRange(range, range.cursor == range.start); + this.$desiredColumn = range.desiredColumn || this.$desiredColumn; + }; + + this.toOrientedRange = function(range) { + var r = this.getRange(); + if (range) { + range.start.column = r.start.column; + range.start.row = r.start.row; + range.end.column = r.end.column; + range.end.row = r.end.row; + } else { + range = r; + } + + range.cursor = this.isBackwards() ? range.start : range.end; + range.desiredColumn = this.$desiredColumn; + return range; + }; + this.getRangeOfMovements = function(func) { + var start = this.getCursor(); + try { + func(this); + var end = this.getCursor(); + return Range.fromPoints(start,end); + } catch(e) { + return Range.fromPoints(start,start); + } finally { + this.moveCursorToPosition(start); + } + }; + + this.toJSON = function() { + if (this.rangeCount) { + var data = this.ranges.map(function(r) { + var r1 = r.clone(); + r1.isBackwards = r.cursor == r.start; + return r1; + }); + } else { + var data = this.getRange(); + data.isBackwards = this.isBackwards(); + } + return data; + }; + + this.fromJSON = function(data) { + if (data.start == undefined) { + if (this.rangeList) { + this.toSingleRange(data[0]); + for (var i = data.length; i--; ) { + var r = Range.fromPoints(data[i].start, data[i].end); + if (data[i].isBackwards) + r.cursor = r.start; + this.addRange(r, true); + } + return; + } else + data = data[0]; + } + if (this.rangeList) + this.toSingleRange(data); + this.setSelectionRange(data, data.isBackwards); + }; + + this.isEqual = function(data) { + if ((data.length || this.rangeCount) && data.length != this.rangeCount) + return false; + if (!data.length || !this.ranges) + return this.getRange().isEqual(data); + + for (var i = this.ranges.length; i--; ) { + if (!this.ranges[i].isEqual(data[i])) + return false; + } + return true; + }; + +}).call(Selection.prototype); + +exports.Selection = Selection; +}); + +ace.define("ace/tokenizer",["require","exports","module","ace/config"], function(acequire, exports, module) { +"use strict"; + +var config = acequire("./config"); +var MAX_TOKEN_COUNT = 2000; +var Tokenizer = function(rules) { + this.states = rules; + + this.regExps = {}; + this.matchMappings = {}; + for (var key in this.states) { + var state = this.states[key]; + var ruleRegExps = []; + var matchTotal = 0; + var mapping = this.matchMappings[key] = {defaultToken: "text"}; + var flag = "g"; + + var splitterRurles = []; + for (var i = 0; i < state.length; i++) { + var rule = state[i]; + if (rule.defaultToken) + mapping.defaultToken = rule.defaultToken; + if (rule.caseInsensitive) + flag = "gi"; + if (rule.regex == null) + continue; + + if (rule.regex instanceof RegExp) + rule.regex = rule.regex.toString().slice(1, -1); + var adjustedregex = rule.regex; + var matchcount = new RegExp("(?:(" + adjustedregex + ")|(.))").exec("a").length - 2; + if (Array.isArray(rule.token)) { + if (rule.token.length == 1 || matchcount == 1) { + rule.token = rule.token[0]; + } else if (matchcount - 1 != rule.token.length) { + this.reportError("number of classes and regexp groups doesn't match", { + rule: rule, + groupCount: matchcount - 1 + }); + rule.token = rule.token[0]; + } else { + rule.tokenArray = rule.token; + rule.token = null; + rule.onMatch = this.$arrayTokens; + } + } else if (typeof rule.token == "function" && !rule.onMatch) { + if (matchcount > 1) + rule.onMatch = this.$applyToken; + else + rule.onMatch = rule.token; + } + + if (matchcount > 1) { + if (/\\\d/.test(rule.regex)) { + adjustedregex = rule.regex.replace(/\\([0-9]+)/g, function(match, digit) { + return "\\" + (parseInt(digit, 10) + matchTotal + 1); + }); + } else { + matchcount = 1; + adjustedregex = this.removeCapturingGroups(rule.regex); + } + if (!rule.splitRegex && typeof rule.token != "string") + splitterRurles.push(rule); // flag will be known only at the very end + } + + mapping[matchTotal] = i; + matchTotal += matchcount; + + ruleRegExps.push(adjustedregex); + if (!rule.onMatch) + rule.onMatch = null; + } + + if (!ruleRegExps.length) { + mapping[0] = 0; + ruleRegExps.push("$"); + } + + splitterRurles.forEach(function(rule) { + rule.splitRegex = this.createSplitterRegexp(rule.regex, flag); + }, this); + + this.regExps[key] = new RegExp("(" + ruleRegExps.join(")|(") + ")|($)", flag); + } +}; + +(function() { + this.$setMaxTokenCount = function(m) { + MAX_TOKEN_COUNT = m | 0; + }; + + this.$applyToken = function(str) { + var values = this.splitRegex.exec(str).slice(1); + var types = this.token.apply(this, values); + if (typeof types === "string") + return [{type: types, value: str}]; + + var tokens = []; + for (var i = 0, l = types.length; i < l; i++) { + if (values[i]) + tokens[tokens.length] = { + type: types[i], + value: values[i] + }; + } + return tokens; + }; + + this.$arrayTokens = function(str) { + if (!str) + return []; + var values = this.splitRegex.exec(str); + if (!values) + return "text"; + var tokens = []; + var types = this.tokenArray; + for (var i = 0, l = types.length; i < l; i++) { + if (values[i + 1]) + tokens[tokens.length] = { + type: types[i], + value: values[i + 1] + }; + } + return tokens; + }; + + this.removeCapturingGroups = function(src) { + var r = src.replace( + /\[(?:\\.|[^\]])*?\]|\\.|\(\?[:=!]|(\()/g, + function(x, y) {return y ? "(?:" : x;} + ); + return r; + }; + + this.createSplitterRegexp = function(src, flag) { + if (src.indexOf("(?=") != -1) { + var stack = 0; + var inChClass = false; + var lastCapture = {}; + src.replace(/(\\.)|(\((?:\?[=!])?)|(\))|([\[\]])/g, function( + m, esc, parenOpen, parenClose, square, index + ) { + if (inChClass) { + inChClass = square != "]"; + } else if (square) { + inChClass = true; + } else if (parenClose) { + if (stack == lastCapture.stack) { + lastCapture.end = index+1; + lastCapture.stack = -1; + } + stack--; + } else if (parenOpen) { + stack++; + if (parenOpen.length != 1) { + lastCapture.stack = stack; + lastCapture.start = index; + } + } + return m; + }); + + if (lastCapture.end != null && /^\)*$/.test(src.substr(lastCapture.end))) + src = src.substring(0, lastCapture.start) + src.substr(lastCapture.end); + } + if (src.charAt(0) != "^") src = "^" + src; + if (src.charAt(src.length - 1) != "$") src += "$"; + + return new RegExp(src, (flag||"").replace("g", "")); + }; + this.getLineTokens = function(line, startState) { + if (startState && typeof startState != "string") { + var stack = startState.slice(0); + startState = stack[0]; + if (startState === "#tmp") { + stack.shift(); + startState = stack.shift(); + } + } else + var stack = []; + + var currentState = startState || "start"; + var state = this.states[currentState]; + if (!state) { + currentState = "start"; + state = this.states[currentState]; + } + var mapping = this.matchMappings[currentState]; + var re = this.regExps[currentState]; + re.lastIndex = 0; + + var match, tokens = []; + var lastIndex = 0; + var matchAttempts = 0; + + var token = {type: null, value: ""}; + + while (match = re.exec(line)) { + var type = mapping.defaultToken; + var rule = null; + var value = match[0]; + var index = re.lastIndex; + + if (index - value.length > lastIndex) { + var skipped = line.substring(lastIndex, index - value.length); + if (token.type == type) { + token.value += skipped; + } else { + if (token.type) + tokens.push(token); + token = {type: type, value: skipped}; + } + } + + for (var i = 0; i < match.length-2; i++) { + if (match[i + 1] === undefined) + continue; + + rule = state[mapping[i]]; + + if (rule.onMatch) + type = rule.onMatch(value, currentState, stack, line); + else + type = rule.token; + + if (rule.next) { + if (typeof rule.next == "string") { + currentState = rule.next; + } else { + currentState = rule.next(currentState, stack); + } + + state = this.states[currentState]; + if (!state) { + this.reportError("state doesn't exist", currentState); + currentState = "start"; + state = this.states[currentState]; + } + mapping = this.matchMappings[currentState]; + lastIndex = index; + re = this.regExps[currentState]; + re.lastIndex = index; + } + if (rule.consumeLineEnd) + lastIndex = index; + break; + } + + if (value) { + if (typeof type === "string") { + if ((!rule || rule.merge !== false) && token.type === type) { + token.value += value; + } else { + if (token.type) + tokens.push(token); + token = {type: type, value: value}; + } + } else if (type) { + if (token.type) + tokens.push(token); + token = {type: null, value: ""}; + for (var i = 0; i < type.length; i++) + tokens.push(type[i]); + } + } + + if (lastIndex == line.length) + break; + + lastIndex = index; + + if (matchAttempts++ > MAX_TOKEN_COUNT) { + if (matchAttempts > 2 * line.length) { + this.reportError("infinite loop with in ace tokenizer", { + startState: startState, + line: line + }); + } + while (lastIndex < line.length) { + if (token.type) + tokens.push(token); + token = { + value: line.substring(lastIndex, lastIndex += 2000), + type: "overflow" + }; + } + currentState = "start"; + stack = []; + break; + } + } + + if (token.type) + tokens.push(token); + + if (stack.length > 1) { + if (stack[0] !== currentState) + stack.unshift("#tmp", currentState); + } + return { + tokens : tokens, + state : stack.length ? stack : currentState + }; + }; + + this.reportError = config.reportError; + +}).call(Tokenizer.prototype); + +exports.Tokenizer = Tokenizer; +}); + +ace.define("ace/mode/text_highlight_rules",["require","exports","module","ace/lib/lang"], function(acequire, exports, module) { +"use strict"; + +var lang = acequire("../lib/lang"); + +var TextHighlightRules = function() { + + this.$rules = { + "start" : [{ + token : "empty_line", + regex : '^$' + }, { + defaultToken : "text" + }] + }; +}; + +(function() { + + this.addRules = function(rules, prefix) { + if (!prefix) { + for (var key in rules) + this.$rules[key] = rules[key]; + return; + } + for (var key in rules) { + var state = rules[key]; + for (var i = 0; i < state.length; i++) { + var rule = state[i]; + if (rule.next || rule.onMatch) { + if (typeof rule.next == "string") { + if (rule.next.indexOf(prefix) !== 0) + rule.next = prefix + rule.next; + } + if (rule.nextState && rule.nextState.indexOf(prefix) !== 0) + rule.nextState = prefix + rule.nextState; + } + } + this.$rules[prefix + key] = state; + } + }; + + this.getRules = function() { + return this.$rules; + }; + + this.embedRules = function (HighlightRules, prefix, escapeRules, states, append) { + var embedRules = typeof HighlightRules == "function" + ? new HighlightRules().getRules() + : HighlightRules; + if (states) { + for (var i = 0; i < states.length; i++) + states[i] = prefix + states[i]; + } else { + states = []; + for (var key in embedRules) + states.push(prefix + key); + } + + this.addRules(embedRules, prefix); + + if (escapeRules) { + var addRules = Array.prototype[append ? "push" : "unshift"]; + for (var i = 0; i < states.length; i++) + addRules.apply(this.$rules[states[i]], lang.deepCopy(escapeRules)); + } + + if (!this.$embeds) + this.$embeds = []; + this.$embeds.push(prefix); + }; + + this.getEmbeds = function() { + return this.$embeds; + }; + + var pushState = function(currentState, stack) { + if (currentState != "start" || stack.length) + stack.unshift(this.nextState, currentState); + return this.nextState; + }; + var popState = function(currentState, stack) { + stack.shift(); + return stack.shift() || "start"; + }; + + this.normalizeRules = function() { + var id = 0; + var rules = this.$rules; + function processState(key) { + var state = rules[key]; + state.processed = true; + for (var i = 0; i < state.length; i++) { + var rule = state[i]; + var toInsert = null; + if (Array.isArray(rule)) { + toInsert = rule; + rule = {}; + } + if (!rule.regex && rule.start) { + rule.regex = rule.start; + if (!rule.next) + rule.next = []; + rule.next.push({ + defaultToken: rule.token + }, { + token: rule.token + ".end", + regex: rule.end || rule.start, + next: "pop" + }); + rule.token = rule.token + ".start"; + rule.push = true; + } + var next = rule.next || rule.push; + if (next && Array.isArray(next)) { + var stateName = rule.stateName; + if (!stateName) { + stateName = rule.token; + if (typeof stateName != "string") + stateName = stateName[0] || ""; + if (rules[stateName]) + stateName += id++; + } + rules[stateName] = next; + rule.next = stateName; + processState(stateName); + } else if (next == "pop") { + rule.next = popState; + } + + if (rule.push) { + rule.nextState = rule.next || rule.push; + rule.next = pushState; + delete rule.push; + } + + if (rule.rules) { + for (var r in rule.rules) { + if (rules[r]) { + if (rules[r].push) + rules[r].push.apply(rules[r], rule.rules[r]); + } else { + rules[r] = rule.rules[r]; + } + } + } + var includeName = typeof rule == "string" ? rule : rule.include; + if (includeName) { + if (Array.isArray(includeName)) + toInsert = includeName.map(function(x) { return rules[x]; }); + else + toInsert = rules[includeName]; + } + + if (toInsert) { + var args = [i, 1].concat(toInsert); + if (rule.noEscape) + args = args.filter(function(x) {return !x.next;}); + state.splice.apply(state, args); + i--; + } + + if (rule.keywordMap) { + rule.token = this.createKeywordMapper( + rule.keywordMap, rule.defaultToken || "text", rule.caseInsensitive + ); + delete rule.defaultToken; + } + } + } + Object.keys(rules).forEach(processState, this); + }; + + this.createKeywordMapper = function(map, defaultToken, ignoreCase, splitChar) { + var keywords = Object.create(null); + Object.keys(map).forEach(function(className) { + var a = map[className]; + if (ignoreCase) + a = a.toLowerCase(); + var list = a.split(splitChar || "|"); + for (var i = list.length; i--; ) + keywords[list[i]] = className; + }); + if (Object.getPrototypeOf(keywords)) { + keywords.__proto__ = null; + } + this.$keywordList = Object.keys(keywords); + map = null; + return ignoreCase + ? function(value) {return keywords[value.toLowerCase()] || defaultToken; } + : function(value) {return keywords[value] || defaultToken; }; + }; + + this.getKeywords = function() { + return this.$keywords; + }; + +}).call(TextHighlightRules.prototype); + +exports.TextHighlightRules = TextHighlightRules; +}); + +ace.define("ace/mode/behaviour",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +var Behaviour = function() { + this.$behaviours = {}; +}; + +(function () { + + this.add = function (name, action, callback) { + switch (undefined) { + case this.$behaviours: + this.$behaviours = {}; + case this.$behaviours[name]: + this.$behaviours[name] = {}; + } + this.$behaviours[name][action] = callback; + }; + + this.addBehaviours = function (behaviours) { + for (var key in behaviours) { + for (var action in behaviours[key]) { + this.add(key, action, behaviours[key][action]); + } + } + }; + + this.remove = function (name) { + if (this.$behaviours && this.$behaviours[name]) { + delete this.$behaviours[name]; + } + }; + + this.inherit = function (mode, filter) { + if (typeof mode === "function") { + var behaviours = new mode().getBehaviours(filter); + } else { + var behaviours = mode.getBehaviours(filter); + } + this.addBehaviours(behaviours); + }; + + this.getBehaviours = function (filter) { + if (!filter) { + return this.$behaviours; + } else { + var ret = {}; + for (var i = 0; i < filter.length; i++) { + if (this.$behaviours[filter[i]]) { + ret[filter[i]] = this.$behaviours[filter[i]]; + } + } + return ret; + } + }; + +}).call(Behaviour.prototype); + +exports.Behaviour = Behaviour; +}); + +ace.define("ace/token_iterator",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("./range").Range; +var TokenIterator = function(session, initialRow, initialColumn) { + this.$session = session; + this.$row = initialRow; + this.$rowTokens = session.getTokens(initialRow); + + var token = session.getTokenAt(initialRow, initialColumn); + this.$tokenIndex = token ? token.index : -1; +}; + +(function() { + this.stepBackward = function() { + this.$tokenIndex -= 1; + + while (this.$tokenIndex < 0) { + this.$row -= 1; + if (this.$row < 0) { + this.$row = 0; + return null; + } + + this.$rowTokens = this.$session.getTokens(this.$row); + this.$tokenIndex = this.$rowTokens.length - 1; + } + + return this.$rowTokens[this.$tokenIndex]; + }; + this.stepForward = function() { + this.$tokenIndex += 1; + var rowCount; + while (this.$tokenIndex >= this.$rowTokens.length) { + this.$row += 1; + if (!rowCount) + rowCount = this.$session.getLength(); + if (this.$row >= rowCount) { + this.$row = rowCount - 1; + return null; + } + + this.$rowTokens = this.$session.getTokens(this.$row); + this.$tokenIndex = 0; + } + + return this.$rowTokens[this.$tokenIndex]; + }; + this.getCurrentToken = function () { + return this.$rowTokens[this.$tokenIndex]; + }; + this.getCurrentTokenRow = function () { + return this.$row; + }; + this.getCurrentTokenColumn = function() { + var rowTokens = this.$rowTokens; + var tokenIndex = this.$tokenIndex; + var column = rowTokens[tokenIndex].start; + if (column !== undefined) + return column; + + column = 0; + while (tokenIndex > 0) { + tokenIndex -= 1; + column += rowTokens[tokenIndex].value.length; + } + + return column; + }; + this.getCurrentTokenPosition = function() { + return {row: this.$row, column: this.getCurrentTokenColumn()}; + }; + this.getCurrentTokenRange = function() { + var token = this.$rowTokens[this.$tokenIndex]; + var column = this.getCurrentTokenColumn(); + return new Range(this.$row, column, this.$row, column + token.value.length); + }; + +}).call(TokenIterator.prototype); + +exports.TokenIterator = TokenIterator; +}); + +ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Behaviour = acequire("../behaviour").Behaviour; +var TokenIterator = acequire("../../token_iterator").TokenIterator; +var lang = acequire("../../lib/lang"); + +var SAFE_INSERT_IN_TOKENS = + ["text", "paren.rparen", "punctuation.operator"]; +var SAFE_INSERT_BEFORE_TOKENS = + ["text", "paren.rparen", "punctuation.operator", "comment"]; + +var context; +var contextCache = {}; +var defaultQuotes = {'"' : '"', "'" : "'"}; + +var initContext = function(editor) { + var id = -1; + if (editor.multiSelect) { + id = editor.selection.index; + if (contextCache.rangeCount != editor.multiSelect.rangeCount) + contextCache = {rangeCount: editor.multiSelect.rangeCount}; + } + if (contextCache[id]) + return context = contextCache[id]; + context = contextCache[id] = { + autoInsertedBrackets: 0, + autoInsertedRow: -1, + autoInsertedLineEnd: "", + maybeInsertedBrackets: 0, + maybeInsertedRow: -1, + maybeInsertedLineStart: "", + maybeInsertedLineEnd: "" + }; +}; + +var getWrapped = function(selection, selected, opening, closing) { + var rowDiff = selection.end.row - selection.start.row; + return { + text: opening + selected + closing, + selection: [ + 0, + selection.start.column + 1, + rowDiff, + selection.end.column + (rowDiff ? 0 : 1) + ] + }; +}; + +var CstyleBehaviour = function(options) { + this.add("braces", "insertion", function(state, action, editor, session, text) { + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + if (text == '{') { + initContext(editor); + var selection = editor.getSelectionRange(); + var selected = session.doc.getTextRange(selection); + if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) { + return getWrapped(selection, selected, '{', '}'); + } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { + if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode || options && options.braces) { + CstyleBehaviour.recordAutoInsert(editor, session, "}"); + return { + text: '{}', + selection: [1, 1] + }; + } else { + CstyleBehaviour.recordMaybeInsert(editor, session, "{"); + return { + text: '{', + selection: [1, 1] + }; + } + } + } else if (text == '}') { + initContext(editor); + var rightChar = line.substring(cursor.column, cursor.column + 1); + if (rightChar == '}') { + var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); + if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { + CstyleBehaviour.popAutoInsertedClosing(); + return { + text: '', + selection: [1, 1] + }; + } + } + } else if (text == "\n" || text == "\r\n") { + initContext(editor); + var closing = ""; + if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) { + closing = lang.stringRepeat("}", context.maybeInsertedBrackets); + CstyleBehaviour.clearMaybeInsertedClosing(); + } + var rightChar = line.substring(cursor.column, cursor.column + 1); + if (rightChar === '}') { + var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}'); + if (!openBracePos) + return null; + var next_indent = this.$getIndent(session.getLine(openBracePos.row)); + } else if (closing) { + var next_indent = this.$getIndent(line); + } else { + CstyleBehaviour.clearMaybeInsertedClosing(); + return; + } + var indent = next_indent + session.getTabString(); + + return { + text: '\n' + indent + '\n' + next_indent + closing, + selection: [1, indent.length, 1, indent.length] + }; + } else { + CstyleBehaviour.clearMaybeInsertedClosing(); + } + }); + + this.add("braces", "deletion", function(state, action, editor, session, range) { + var selected = session.doc.getTextRange(range); + if (!range.isMultiLine() && selected == '{') { + initContext(editor); + var line = session.doc.getLine(range.start.row); + var rightChar = line.substring(range.end.column, range.end.column + 1); + if (rightChar == '}') { + range.end.column++; + return range; + } else { + context.maybeInsertedBrackets--; + } + } + }); + + this.add("parens", "insertion", function(state, action, editor, session, text) { + if (text == '(') { + initContext(editor); + var selection = editor.getSelectionRange(); + var selected = session.doc.getTextRange(selection); + if (selected !== "" && editor.getWrapBehavioursEnabled()) { + return getWrapped(selection, selected, '(', ')'); + } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { + CstyleBehaviour.recordAutoInsert(editor, session, ")"); + return { + text: '()', + selection: [1, 1] + }; + } + } else if (text == ')') { + initContext(editor); + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + var rightChar = line.substring(cursor.column, cursor.column + 1); + if (rightChar == ')') { + var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); + if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { + CstyleBehaviour.popAutoInsertedClosing(); + return { + text: '', + selection: [1, 1] + }; + } + } + } + }); + + this.add("parens", "deletion", function(state, action, editor, session, range) { + var selected = session.doc.getTextRange(range); + if (!range.isMultiLine() && selected == '(') { + initContext(editor); + var line = session.doc.getLine(range.start.row); + var rightChar = line.substring(range.start.column + 1, range.start.column + 2); + if (rightChar == ')') { + range.end.column++; + return range; + } + } + }); + + this.add("brackets", "insertion", function(state, action, editor, session, text) { + if (text == '[') { + initContext(editor); + var selection = editor.getSelectionRange(); + var selected = session.doc.getTextRange(selection); + if (selected !== "" && editor.getWrapBehavioursEnabled()) { + return getWrapped(selection, selected, '[', ']'); + } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { + CstyleBehaviour.recordAutoInsert(editor, session, "]"); + return { + text: '[]', + selection: [1, 1] + }; + } + } else if (text == ']') { + initContext(editor); + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + var rightChar = line.substring(cursor.column, cursor.column + 1); + if (rightChar == ']') { + var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row}); + if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { + CstyleBehaviour.popAutoInsertedClosing(); + return { + text: '', + selection: [1, 1] + }; + } + } + } + }); + + this.add("brackets", "deletion", function(state, action, editor, session, range) { + var selected = session.doc.getTextRange(range); + if (!range.isMultiLine() && selected == '[') { + initContext(editor); + var line = session.doc.getLine(range.start.row); + var rightChar = line.substring(range.start.column + 1, range.start.column + 2); + if (rightChar == ']') { + range.end.column++; + return range; + } + } + }); + + this.add("string_dquotes", "insertion", function(state, action, editor, session, text) { + var quotes = session.$mode.$quotes || defaultQuotes; + if (text.length == 1 && quotes[text]) { + if (this.lineCommentStart && this.lineCommentStart.indexOf(text) != -1) + return; + initContext(editor); + var quote = text; + var selection = editor.getSelectionRange(); + var selected = session.doc.getTextRange(selection); + if (selected !== "" && (selected.length != 1 || !quotes[selected]) && editor.getWrapBehavioursEnabled()) { + return getWrapped(selection, selected, quote, quote); + } else if (!selected) { + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + var leftChar = line.substring(cursor.column-1, cursor.column); + var rightChar = line.substring(cursor.column, cursor.column + 1); + + var token = session.getTokenAt(cursor.row, cursor.column); + var rightToken = session.getTokenAt(cursor.row, cursor.column + 1); + if (leftChar == "\\" && token && /escape/.test(token.type)) + return null; + + var stringBefore = token && /string|escape/.test(token.type); + var stringAfter = !rightToken || /string|escape/.test(rightToken.type); + + var pair; + if (rightChar == quote) { + pair = stringBefore !== stringAfter; + if (pair && /string\.end/.test(rightToken.type)) + pair = false; + } else { + if (stringBefore && !stringAfter) + return null; // wrap string with different quote + if (stringBefore && stringAfter) + return null; // do not pair quotes inside strings + var wordRe = session.$mode.tokenRe; + wordRe.lastIndex = 0; + var isWordBefore = wordRe.test(leftChar); + wordRe.lastIndex = 0; + var isWordAfter = wordRe.test(leftChar); + if (isWordBefore || isWordAfter) + return null; // before or after alphanumeric + if (rightChar && !/[\s;,.})\]\\]/.test(rightChar)) + return null; // there is rightChar and it isn't closing + pair = true; + } + return { + text: pair ? quote + quote : "", + selection: [1,1] + }; + } + } + }); + + this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { + var selected = session.doc.getTextRange(range); + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { + initContext(editor); + var line = session.doc.getLine(range.start.row); + var rightChar = line.substring(range.start.column + 1, range.start.column + 2); + if (rightChar == selected) { + range.end.column++; + return range; + } + } + }); + +}; + + +CstyleBehaviour.isSaneInsertion = function(editor, session) { + var cursor = editor.getCursorPosition(); + var iterator = new TokenIterator(session, cursor.row, cursor.column); + if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) { + var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1); + if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) + return false; + } + iterator.stepForward(); + return iterator.getCurrentTokenRow() !== cursor.row || + this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS); +}; + +CstyleBehaviour.$matchTokenType = function(token, types) { + return types.indexOf(token.type || token) > -1; +}; + +CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) { + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0])) + context.autoInsertedBrackets = 0; + context.autoInsertedRow = cursor.row; + context.autoInsertedLineEnd = bracket + line.substr(cursor.column); + context.autoInsertedBrackets++; +}; + +CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) { + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + if (!this.isMaybeInsertedClosing(cursor, line)) + context.maybeInsertedBrackets = 0; + context.maybeInsertedRow = cursor.row; + context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket; + context.maybeInsertedLineEnd = line.substr(cursor.column); + context.maybeInsertedBrackets++; +}; + +CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) { + return context.autoInsertedBrackets > 0 && + cursor.row === context.autoInsertedRow && + bracket === context.autoInsertedLineEnd[0] && + line.substr(cursor.column) === context.autoInsertedLineEnd; +}; + +CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) { + return context.maybeInsertedBrackets > 0 && + cursor.row === context.maybeInsertedRow && + line.substr(cursor.column) === context.maybeInsertedLineEnd && + line.substr(0, cursor.column) == context.maybeInsertedLineStart; +}; + +CstyleBehaviour.popAutoInsertedClosing = function() { + context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1); + context.autoInsertedBrackets--; +}; + +CstyleBehaviour.clearMaybeInsertedClosing = function() { + if (context) { + context.maybeInsertedBrackets = 0; + context.maybeInsertedRow = -1; + } +}; + + + +oop.inherits(CstyleBehaviour, Behaviour); + +exports.CstyleBehaviour = CstyleBehaviour; +}); + +ace.define("ace/unicode",["require","exports","module"], function(acequire, exports, module) { +"use strict"; +exports.packages = {}; + +addUnicodePackage({ + L: "0041-005A0061-007A00AA00B500BA00C0-00D600D8-00F600F8-02C102C6-02D102E0-02E402EC02EE0370-037403760377037A-037D03860388-038A038C038E-03A103A3-03F503F7-0481048A-05250531-055605590561-058705D0-05EA05F0-05F20621-064A066E066F0671-06D306D506E506E606EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA07F407F507FA0800-0815081A082408280904-0939093D09500958-0961097109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E460E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EC60EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10A0-10C510D0-10FA10FC1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317D717DC1820-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541AA71B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C7D1CE9-1CEC1CEE-1CF11D00-1DBF1E00-1F151F18-1F1D1F20-1F451F48-1F4D1F50-1F571F591F5B1F5D1F5F-1F7D1F80-1FB41FB6-1FBC1FBE1FC2-1FC41FC6-1FCC1FD0-1FD31FD6-1FDB1FE0-1FEC1FF2-1FF41FF6-1FFC2071207F2090-209421022107210A-211321152119-211D212421262128212A-212D212F-2139213C-213F2145-2149214E218321842C00-2C2E2C30-2C5E2C60-2CE42CEB-2CEE2D00-2D252D30-2D652D6F2D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE2E2F300530063031-3035303B303C3041-3096309D-309F30A1-30FA30FC-30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A48CA4D0-A4FDA500-A60CA610-A61FA62AA62BA640-A65FA662-A66EA67F-A697A6A0-A6E5A717-A71FA722-A788A78BA78CA7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2A9CFAA00-AA28AA40-AA42AA44-AA4BAA60-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADB-AADDABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB00-FB06FB13-FB17FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF21-FF3AFF41-FF5AFF66-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC", + Ll: "0061-007A00AA00B500BA00DF-00F600F8-00FF01010103010501070109010B010D010F01110113011501170119011B011D011F01210123012501270129012B012D012F01310133013501370138013A013C013E014001420144014601480149014B014D014F01510153015501570159015B015D015F01610163016501670169016B016D016F0171017301750177017A017C017E-0180018301850188018C018D019201950199-019B019E01A101A301A501A801AA01AB01AD01B001B401B601B901BA01BD-01BF01C601C901CC01CE01D001D201D401D601D801DA01DC01DD01DF01E101E301E501E701E901EB01ED01EF01F001F301F501F901FB01FD01FF02010203020502070209020B020D020F02110213021502170219021B021D021F02210223022502270229022B022D022F02310233-0239023C023F0240024202470249024B024D024F-02930295-02AF037103730377037B-037D039003AC-03CE03D003D103D5-03D703D903DB03DD03DF03E103E303E503E703E903EB03ED03EF-03F303F503F803FB03FC0430-045F04610463046504670469046B046D046F04710473047504770479047B047D047F0481048B048D048F04910493049504970499049B049D049F04A104A304A504A704A904AB04AD04AF04B104B304B504B704B904BB04BD04BF04C204C404C604C804CA04CC04CE04CF04D104D304D504D704D904DB04DD04DF04E104E304E504E704E904EB04ED04EF04F104F304F504F704F904FB04FD04FF05010503050505070509050B050D050F05110513051505170519051B051D051F0521052305250561-05871D00-1D2B1D62-1D771D79-1D9A1E011E031E051E071E091E0B1E0D1E0F1E111E131E151E171E191E1B1E1D1E1F1E211E231E251E271E291E2B1E2D1E2F1E311E331E351E371E391E3B1E3D1E3F1E411E431E451E471E491E4B1E4D1E4F1E511E531E551E571E591E5B1E5D1E5F1E611E631E651E671E691E6B1E6D1E6F1E711E731E751E771E791E7B1E7D1E7F1E811E831E851E871E891E8B1E8D1E8F1E911E931E95-1E9D1E9F1EA11EA31EA51EA71EA91EAB1EAD1EAF1EB11EB31EB51EB71EB91EBB1EBD1EBF1EC11EC31EC51EC71EC91ECB1ECD1ECF1ED11ED31ED51ED71ED91EDB1EDD1EDF1EE11EE31EE51EE71EE91EEB1EED1EEF1EF11EF31EF51EF71EF91EFB1EFD1EFF-1F071F10-1F151F20-1F271F30-1F371F40-1F451F50-1F571F60-1F671F70-1F7D1F80-1F871F90-1F971FA0-1FA71FB0-1FB41FB61FB71FBE1FC2-1FC41FC61FC71FD0-1FD31FD61FD71FE0-1FE71FF2-1FF41FF61FF7210A210E210F2113212F21342139213C213D2146-2149214E21842C30-2C5E2C612C652C662C682C6A2C6C2C712C732C742C76-2C7C2C812C832C852C872C892C8B2C8D2C8F2C912C932C952C972C992C9B2C9D2C9F2CA12CA32CA52CA72CA92CAB2CAD2CAF2CB12CB32CB52CB72CB92CBB2CBD2CBF2CC12CC32CC52CC72CC92CCB2CCD2CCF2CD12CD32CD52CD72CD92CDB2CDD2CDF2CE12CE32CE42CEC2CEE2D00-2D25A641A643A645A647A649A64BA64DA64FA651A653A655A657A659A65BA65DA65FA663A665A667A669A66BA66DA681A683A685A687A689A68BA68DA68FA691A693A695A697A723A725A727A729A72BA72DA72F-A731A733A735A737A739A73BA73DA73FA741A743A745A747A749A74BA74DA74FA751A753A755A757A759A75BA75DA75FA761A763A765A767A769A76BA76DA76FA771-A778A77AA77CA77FA781A783A785A787A78CFB00-FB06FB13-FB17FF41-FF5A", + Lu: "0041-005A00C0-00D600D8-00DE01000102010401060108010A010C010E01100112011401160118011A011C011E01200122012401260128012A012C012E01300132013401360139013B013D013F0141014301450147014A014C014E01500152015401560158015A015C015E01600162016401660168016A016C016E017001720174017601780179017B017D018101820184018601870189-018B018E-0191019301940196-0198019C019D019F01A001A201A401A601A701A901AC01AE01AF01B1-01B301B501B701B801BC01C401C701CA01CD01CF01D101D301D501D701D901DB01DE01E001E201E401E601E801EA01EC01EE01F101F401F6-01F801FA01FC01FE02000202020402060208020A020C020E02100212021402160218021A021C021E02200222022402260228022A022C022E02300232023A023B023D023E02410243-02460248024A024C024E03700372037603860388-038A038C038E038F0391-03A103A3-03AB03CF03D2-03D403D803DA03DC03DE03E003E203E403E603E803EA03EC03EE03F403F703F903FA03FD-042F04600462046404660468046A046C046E04700472047404760478047A047C047E0480048A048C048E04900492049404960498049A049C049E04A004A204A404A604A804AA04AC04AE04B004B204B404B604B804BA04BC04BE04C004C104C304C504C704C904CB04CD04D004D204D404D604D804DA04DC04DE04E004E204E404E604E804EA04EC04EE04F004F204F404F604F804FA04FC04FE05000502050405060508050A050C050E05100512051405160518051A051C051E0520052205240531-055610A0-10C51E001E021E041E061E081E0A1E0C1E0E1E101E121E141E161E181E1A1E1C1E1E1E201E221E241E261E281E2A1E2C1E2E1E301E321E341E361E381E3A1E3C1E3E1E401E421E441E461E481E4A1E4C1E4E1E501E521E541E561E581E5A1E5C1E5E1E601E621E641E661E681E6A1E6C1E6E1E701E721E741E761E781E7A1E7C1E7E1E801E821E841E861E881E8A1E8C1E8E1E901E921E941E9E1EA01EA21EA41EA61EA81EAA1EAC1EAE1EB01EB21EB41EB61EB81EBA1EBC1EBE1EC01EC21EC41EC61EC81ECA1ECC1ECE1ED01ED21ED41ED61ED81EDA1EDC1EDE1EE01EE21EE41EE61EE81EEA1EEC1EEE1EF01EF21EF41EF61EF81EFA1EFC1EFE1F08-1F0F1F18-1F1D1F28-1F2F1F38-1F3F1F48-1F4D1F591F5B1F5D1F5F1F68-1F6F1FB8-1FBB1FC8-1FCB1FD8-1FDB1FE8-1FEC1FF8-1FFB21022107210B-210D2110-211221152119-211D212421262128212A-212D2130-2133213E213F214521832C00-2C2E2C602C62-2C642C672C692C6B2C6D-2C702C722C752C7E-2C802C822C842C862C882C8A2C8C2C8E2C902C922C942C962C982C9A2C9C2C9E2CA02CA22CA42CA62CA82CAA2CAC2CAE2CB02CB22CB42CB62CB82CBA2CBC2CBE2CC02CC22CC42CC62CC82CCA2CCC2CCE2CD02CD22CD42CD62CD82CDA2CDC2CDE2CE02CE22CEB2CEDA640A642A644A646A648A64AA64CA64EA650A652A654A656A658A65AA65CA65EA662A664A666A668A66AA66CA680A682A684A686A688A68AA68CA68EA690A692A694A696A722A724A726A728A72AA72CA72EA732A734A736A738A73AA73CA73EA740A742A744A746A748A74AA74CA74EA750A752A754A756A758A75AA75CA75EA760A762A764A766A768A76AA76CA76EA779A77BA77DA77EA780A782A784A786A78BFF21-FF3A", + Lt: "01C501C801CB01F21F88-1F8F1F98-1F9F1FA8-1FAF1FBC1FCC1FFC", + Lm: "02B0-02C102C6-02D102E0-02E402EC02EE0374037A0559064006E506E607F407F507FA081A0824082809710E460EC610FC17D718431AA71C78-1C7D1D2C-1D611D781D9B-1DBF2071207F2090-20942C7D2D6F2E2F30053031-3035303B309D309E30FC-30FEA015A4F8-A4FDA60CA67FA717-A71FA770A788A9CFAA70AADDFF70FF9EFF9F", + Lo: "01BB01C0-01C3029405D0-05EA05F0-05F20621-063F0641-064A066E066F0671-06D306D506EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA0800-08150904-0939093D09500958-096109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E450E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10D0-10FA1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317DC1820-18421844-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C771CE9-1CEC1CEE-1CF12135-21382D30-2D652D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE3006303C3041-3096309F30A1-30FA30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A014A016-A48CA4D0-A4F7A500-A60BA610-A61FA62AA62BA66EA6A0-A6E5A7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2AA00-AA28AA40-AA42AA44-AA4BAA60-AA6FAA71-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADBAADCABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF66-FF6FFF71-FF9DFFA0-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC", + M: "0300-036F0483-04890591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DE-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0903093C093E-094E0951-0955096209630981-098309BC09BE-09C409C709C809CB-09CD09D709E209E30A01-0A030A3C0A3E-0A420A470A480A4B-0A4D0A510A700A710A750A81-0A830ABC0ABE-0AC50AC7-0AC90ACB-0ACD0AE20AE30B01-0B030B3C0B3E-0B440B470B480B4B-0B4D0B560B570B620B630B820BBE-0BC20BC6-0BC80BCA-0BCD0BD70C01-0C030C3E-0C440C46-0C480C4A-0C4D0C550C560C620C630C820C830CBC0CBE-0CC40CC6-0CC80CCA-0CCD0CD50CD60CE20CE30D020D030D3E-0D440D46-0D480D4A-0D4D0D570D620D630D820D830DCA0DCF-0DD40DD60DD8-0DDF0DF20DF30E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F3E0F3F0F71-0F840F860F870F90-0F970F99-0FBC0FC6102B-103E1056-1059105E-10601062-10641067-106D1071-10741082-108D108F109A-109D135F1712-17141732-1734175217531772177317B6-17D317DD180B-180D18A91920-192B1930-193B19B0-19C019C819C91A17-1A1B1A55-1A5E1A60-1A7C1A7F1B00-1B041B34-1B441B6B-1B731B80-1B821BA1-1BAA1C24-1C371CD0-1CD21CD4-1CE81CED1CF21DC0-1DE61DFD-1DFF20D0-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66F-A672A67CA67DA6F0A6F1A802A806A80BA823-A827A880A881A8B4-A8C4A8E0-A8F1A926-A92DA947-A953A980-A983A9B3-A9C0AA29-AA36AA43AA4CAA4DAA7BAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE3-ABEAABECABEDFB1EFE00-FE0FFE20-FE26", + Mn: "0300-036F0483-04870591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DF-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0902093C0941-0948094D0951-095509620963098109BC09C1-09C409CD09E209E30A010A020A3C0A410A420A470A480A4B-0A4D0A510A700A710A750A810A820ABC0AC1-0AC50AC70AC80ACD0AE20AE30B010B3C0B3F0B41-0B440B4D0B560B620B630B820BC00BCD0C3E-0C400C46-0C480C4A-0C4D0C550C560C620C630CBC0CBF0CC60CCC0CCD0CE20CE30D41-0D440D4D0D620D630DCA0DD2-0DD40DD60E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F71-0F7E0F80-0F840F860F870F90-0F970F99-0FBC0FC6102D-10301032-10371039103A103D103E10581059105E-10601071-1074108210851086108D109D135F1712-17141732-1734175217531772177317B7-17BD17C617C9-17D317DD180B-180D18A91920-19221927192819321939-193B1A171A181A561A58-1A5E1A601A621A65-1A6C1A73-1A7C1A7F1B00-1B031B341B36-1B3A1B3C1B421B6B-1B731B801B811BA2-1BA51BA81BA91C2C-1C331C361C371CD0-1CD21CD4-1CE01CE2-1CE81CED1DC0-1DE61DFD-1DFF20D0-20DC20E120E5-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66FA67CA67DA6F0A6F1A802A806A80BA825A826A8C4A8E0-A8F1A926-A92DA947-A951A980-A982A9B3A9B6-A9B9A9BCAA29-AA2EAA31AA32AA35AA36AA43AA4CAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE5ABE8ABEDFB1EFE00-FE0FFE20-FE26", + Mc: "0903093E-09400949-094C094E0982098309BE-09C009C709C809CB09CC09D70A030A3E-0A400A830ABE-0AC00AC90ACB0ACC0B020B030B3E0B400B470B480B4B0B4C0B570BBE0BBF0BC10BC20BC6-0BC80BCA-0BCC0BD70C01-0C030C41-0C440C820C830CBE0CC0-0CC40CC70CC80CCA0CCB0CD50CD60D020D030D3E-0D400D46-0D480D4A-0D4C0D570D820D830DCF-0DD10DD8-0DDF0DF20DF30F3E0F3F0F7F102B102C10311038103B103C105610571062-10641067-106D108310841087-108C108F109A-109C17B617BE-17C517C717C81923-19261929-192B193019311933-193819B0-19C019C819C91A19-1A1B1A551A571A611A631A641A6D-1A721B041B351B3B1B3D-1B411B431B441B821BA11BA61BA71BAA1C24-1C2B1C341C351CE11CF2A823A824A827A880A881A8B4-A8C3A952A953A983A9B4A9B5A9BAA9BBA9BD-A9C0AA2FAA30AA33AA34AA4DAA7BABE3ABE4ABE6ABE7ABE9ABEAABEC", + Me: "0488048906DE20DD-20E020E2-20E4A670-A672", + N: "0030-003900B200B300B900BC-00BE0660-066906F0-06F907C0-07C90966-096F09E6-09EF09F4-09F90A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BF20C66-0C6F0C78-0C7E0CE6-0CEF0D66-0D750E50-0E590ED0-0ED90F20-0F331040-10491090-10991369-137C16EE-16F017E0-17E917F0-17F91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C5920702074-20792080-20892150-21822185-21892460-249B24EA-24FF2776-27932CFD30073021-30293038-303A3192-31953220-32293251-325F3280-328932B1-32BFA620-A629A6E6-A6EFA830-A835A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19", + Nd: "0030-00390660-066906F0-06F907C0-07C90966-096F09E6-09EF0A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BEF0C66-0C6F0CE6-0CEF0D66-0D6F0E50-0E590ED0-0ED90F20-0F291040-10491090-109917E0-17E91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C59A620-A629A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19", + Nl: "16EE-16F02160-21822185-218830073021-30293038-303AA6E6-A6EF", + No: "00B200B300B900BC-00BE09F4-09F90BF0-0BF20C78-0C7E0D70-0D750F2A-0F331369-137C17F0-17F920702074-20792080-20892150-215F21892460-249B24EA-24FF2776-27932CFD3192-31953220-32293251-325F3280-328932B1-32BFA830-A835", + P: "0021-00230025-002A002C-002F003A003B003F0040005B-005D005F007B007D00A100AB00B700BB00BF037E0387055A-055F0589058A05BE05C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F3A-0F3D0F850FD0-0FD4104A-104F10FB1361-13681400166D166E169B169C16EB-16ED1735173617D4-17D617D8-17DA1800-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD32010-20272030-20432045-20512053-205E207D207E208D208E2329232A2768-277527C527C627E6-27EF2983-299829D8-29DB29FC29FD2CF9-2CFC2CFE2CFF2E00-2E2E2E302E313001-30033008-30113014-301F3030303D30A030FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFD3EFD3FFE10-FE19FE30-FE52FE54-FE61FE63FE68FE6AFE6BFF01-FF03FF05-FF0AFF0C-FF0FFF1AFF1BFF1FFF20FF3B-FF3DFF3FFF5BFF5DFF5F-FF65", + Pd: "002D058A05BE140018062010-20152E172E1A301C303030A0FE31FE32FE58FE63FF0D", + Ps: "0028005B007B0F3A0F3C169B201A201E2045207D208D23292768276A276C276E27702772277427C527E627E827EA27EC27EE2983298529872989298B298D298F299129932995299729D829DA29FC2E222E242E262E283008300A300C300E3010301430163018301A301DFD3EFE17FE35FE37FE39FE3BFE3DFE3FFE41FE43FE47FE59FE5BFE5DFF08FF3BFF5BFF5FFF62", + Pe: "0029005D007D0F3B0F3D169C2046207E208E232A2769276B276D276F27712773277527C627E727E927EB27ED27EF298429862988298A298C298E2990299229942996299829D929DB29FD2E232E252E272E293009300B300D300F3011301530173019301B301E301FFD3FFE18FE36FE38FE3AFE3CFE3EFE40FE42FE44FE48FE5AFE5CFE5EFF09FF3DFF5DFF60FF63", + Pi: "00AB2018201B201C201F20392E022E042E092E0C2E1C2E20", + Pf: "00BB2019201D203A2E032E052E0A2E0D2E1D2E21", + Pc: "005F203F20402054FE33FE34FE4D-FE4FFF3F", + Po: "0021-00230025-0027002A002C002E002F003A003B003F0040005C00A100B700BF037E0387055A-055F058905C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F850FD0-0FD4104A-104F10FB1361-1368166D166E16EB-16ED1735173617D4-17D617D8-17DA1800-18051807-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD3201620172020-20272030-2038203B-203E2041-20432047-205120532055-205E2CF9-2CFC2CFE2CFF2E002E012E06-2E082E0B2E0E-2E162E182E192E1B2E1E2E1F2E2A-2E2E2E302E313001-3003303D30FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFE10-FE16FE19FE30FE45FE46FE49-FE4CFE50-FE52FE54-FE57FE5F-FE61FE68FE6AFE6BFF01-FF03FF05-FF07FF0AFF0CFF0EFF0FFF1AFF1BFF1FFF20FF3CFF61FF64FF65", + S: "0024002B003C-003E005E0060007C007E00A2-00A900AC00AE-00B100B400B600B800D700F702C2-02C502D2-02DF02E5-02EB02ED02EF-02FF03750384038503F604820606-0608060B060E060F06E906FD06FE07F609F209F309FA09FB0AF10B700BF3-0BFA0C7F0CF10CF20D790E3F0F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-139917DB194019E0-19FF1B61-1B6A1B74-1B7C1FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE20442052207A-207C208A-208C20A0-20B8210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B2140-2144214A-214D214F2190-2328232B-23E82400-24262440-244A249C-24E92500-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE27C0-27C427C7-27CA27CC27D0-27E527F0-29822999-29D729DC-29FB29FE-2B4C2B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F309B309C319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A700-A716A720A721A789A78AA828-A82BA836-A839AA77-AA79FB29FDFCFDFDFE62FE64-FE66FE69FF04FF0BFF1C-FF1EFF3EFF40FF5CFF5EFFE0-FFE6FFE8-FFEEFFFCFFFD", + Sm: "002B003C-003E007C007E00AC00B100D700F703F60606-060820442052207A-207C208A-208C2140-2144214B2190-2194219A219B21A021A321A621AE21CE21CF21D221D421F4-22FF2308-230B23202321237C239B-23B323DC-23E125B725C125F8-25FF266F27C0-27C427C7-27CA27CC27D0-27E527F0-27FF2900-29822999-29D729DC-29FB29FE-2AFF2B30-2B442B47-2B4CFB29FE62FE64-FE66FF0BFF1C-FF1EFF5CFF5EFFE2FFE9-FFEC", + Sc: "002400A2-00A5060B09F209F309FB0AF10BF90E3F17DB20A0-20B8A838FDFCFE69FF04FFE0FFE1FFE5FFE6", + Sk: "005E006000A800AF00B400B802C2-02C502D2-02DF02E5-02EB02ED02EF-02FF0375038403851FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE309B309CA700-A716A720A721A789A78AFF3EFF40FFE3", + So: "00A600A700A900AE00B000B60482060E060F06E906FD06FE07F609FA0B700BF3-0BF80BFA0C7F0CF10CF20D790F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-1399194019E0-19FF1B61-1B6A1B74-1B7C210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B214A214C214D214F2195-2199219C-219F21A121A221A421A521A7-21AD21AF-21CD21D021D121D321D5-21F32300-2307230C-231F2322-2328232B-237B237D-239A23B4-23DB23E2-23E82400-24262440-244A249C-24E92500-25B625B8-25C025C2-25F72600-266E2670-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE2800-28FF2B00-2B2F2B452B462B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A828-A82BA836A837A839AA77-AA79FDFDFFE4FFE8FFEDFFEEFFFCFFFD", + Z: "002000A01680180E2000-200A20282029202F205F3000", + Zs: "002000A01680180E2000-200A202F205F3000", + Zl: "2028", + Zp: "2029", + C: "0000-001F007F-009F00AD03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-0605061C061D0620065F06DD070E070F074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17B417B517DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF200B-200F202A-202E2060-206F20722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-F8FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFD-FF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFFBFFFEFFFF", + Cc: "0000-001F007F-009F", + Cf: "00AD0600-060306DD070F17B417B5200B-200F202A-202E2060-2064206A-206FFEFFFFF9-FFFB", + Co: "E000-F8FF", + Cs: "D800-DFFF", + Cn: "03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-05FF06040605061C061D0620065F070E074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF2065-206920722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-D7FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFDFEFEFF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFF8FFFEFFFF" +}); + +function addUnicodePackage (pack) { + var codePoint = /\w{4}/g; + for (var name in pack) + exports.packages[name] = pack[name].replace(codePoint, "\\u$&"); +} + +}); + +ace.define("ace/mode/text",["require","exports","module","ace/tokenizer","ace/mode/text_highlight_rules","ace/mode/behaviour/cstyle","ace/unicode","ace/lib/lang","ace/token_iterator","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Tokenizer = acequire("../tokenizer").Tokenizer; +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; +var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; +var unicode = acequire("../unicode"); +var lang = acequire("../lib/lang"); +var TokenIterator = acequire("../token_iterator").TokenIterator; +var Range = acequire("../range").Range; + +var Mode = function() { + this.HighlightRules = TextHighlightRules; +}; + +(function() { + this.$defaultBehaviour = new CstyleBehaviour(); + + this.tokenRe = new RegExp("^[" + + unicode.packages.L + + unicode.packages.Mn + unicode.packages.Mc + + unicode.packages.Nd + + unicode.packages.Pc + "\\$_]+", "g" + ); + + this.nonTokenRe = new RegExp("^(?:[^" + + unicode.packages.L + + unicode.packages.Mn + unicode.packages.Mc + + unicode.packages.Nd + + unicode.packages.Pc + "\\$_]|\\s])+", "g" + ); + + this.getTokenizer = function() { + if (!this.$tokenizer) { + this.$highlightRules = this.$highlightRules || new this.HighlightRules(this.$highlightRuleConfig); + this.$tokenizer = new Tokenizer(this.$highlightRules.getRules()); + } + return this.$tokenizer; + }; + + this.lineCommentStart = ""; + this.blockComment = ""; + + this.toggleCommentLines = function(state, session, startRow, endRow) { + var doc = session.doc; + + var ignoreBlankLines = true; + var shouldRemove = true; + var minIndent = Infinity; + var tabSize = session.getTabSize(); + var insertAtTabStop = false; + + if (!this.lineCommentStart) { + if (!this.blockComment) + return false; + var lineCommentStart = this.blockComment.start; + var lineCommentEnd = this.blockComment.end; + var regexpStart = new RegExp("^(\\s*)(?:" + lang.escapeRegExp(lineCommentStart) + ")"); + var regexpEnd = new RegExp("(?:" + lang.escapeRegExp(lineCommentEnd) + ")\\s*$"); + + var comment = function(line, i) { + if (testRemove(line, i)) + return; + if (!ignoreBlankLines || /\S/.test(line)) { + doc.insertInLine({row: i, column: line.length}, lineCommentEnd); + doc.insertInLine({row: i, column: minIndent}, lineCommentStart); + } + }; + + var uncomment = function(line, i) { + var m; + if (m = line.match(regexpEnd)) + doc.removeInLine(i, line.length - m[0].length, line.length); + if (m = line.match(regexpStart)) + doc.removeInLine(i, m[1].length, m[0].length); + }; + + var testRemove = function(line, row) { + if (regexpStart.test(line)) + return true; + var tokens = session.getTokens(row); + for (var i = 0; i < tokens.length; i++) { + if (tokens[i].type === "comment") + return true; + } + }; + } else { + if (Array.isArray(this.lineCommentStart)) { + var regexpStart = this.lineCommentStart.map(lang.escapeRegExp).join("|"); + var lineCommentStart = this.lineCommentStart[0]; + } else { + var regexpStart = lang.escapeRegExp(this.lineCommentStart); + var lineCommentStart = this.lineCommentStart; + } + regexpStart = new RegExp("^(\\s*)(?:" + regexpStart + ") ?"); + + insertAtTabStop = session.getUseSoftTabs(); + + var uncomment = function(line, i) { + var m = line.match(regexpStart); + if (!m) return; + var start = m[1].length, end = m[0].length; + if (!shouldInsertSpace(line, start, end) && m[0][end - 1] == " ") + end--; + doc.removeInLine(i, start, end); + }; + var commentWithSpace = lineCommentStart + " "; + var comment = function(line, i) { + if (!ignoreBlankLines || /\S/.test(line)) { + if (shouldInsertSpace(line, minIndent, minIndent)) + doc.insertInLine({row: i, column: minIndent}, commentWithSpace); + else + doc.insertInLine({row: i, column: minIndent}, lineCommentStart); + } + }; + var testRemove = function(line, i) { + return regexpStart.test(line); + }; + + var shouldInsertSpace = function(line, before, after) { + var spaces = 0; + while (before-- && line.charAt(before) == " ") + spaces++; + if (spaces % tabSize != 0) + return false; + var spaces = 0; + while (line.charAt(after++) == " ") + spaces++; + if (tabSize > 2) + return spaces % tabSize != tabSize - 1; + else + return spaces % tabSize == 0; + return true; + }; + } + + function iter(fun) { + for (var i = startRow; i <= endRow; i++) + fun(doc.getLine(i), i); + } + + + var minEmptyLength = Infinity; + iter(function(line, i) { + var indent = line.search(/\S/); + if (indent !== -1) { + if (indent < minIndent) + minIndent = indent; + if (shouldRemove && !testRemove(line, i)) + shouldRemove = false; + } else if (minEmptyLength > line.length) { + minEmptyLength = line.length; + } + }); + + if (minIndent == Infinity) { + minIndent = minEmptyLength; + ignoreBlankLines = false; + shouldRemove = false; + } + + if (insertAtTabStop && minIndent % tabSize != 0) + minIndent = Math.floor(minIndent / tabSize) * tabSize; + + iter(shouldRemove ? uncomment : comment); + }; + + this.toggleBlockComment = function(state, session, range, cursor) { + var comment = this.blockComment; + if (!comment) + return; + if (!comment.start && comment[0]) + comment = comment[0]; + + var iterator = new TokenIterator(session, cursor.row, cursor.column); + var token = iterator.getCurrentToken(); + + var sel = session.selection; + var initialRange = session.selection.toOrientedRange(); + var startRow, colDiff; + + if (token && /comment/.test(token.type)) { + var startRange, endRange; + while (token && /comment/.test(token.type)) { + var i = token.value.indexOf(comment.start); + if (i != -1) { + var row = iterator.getCurrentTokenRow(); + var column = iterator.getCurrentTokenColumn() + i; + startRange = new Range(row, column, row, column + comment.start.length); + break; + } + token = iterator.stepBackward(); + } + + var iterator = new TokenIterator(session, cursor.row, cursor.column); + var token = iterator.getCurrentToken(); + while (token && /comment/.test(token.type)) { + var i = token.value.indexOf(comment.end); + if (i != -1) { + var row = iterator.getCurrentTokenRow(); + var column = iterator.getCurrentTokenColumn() + i; + endRange = new Range(row, column, row, column + comment.end.length); + break; + } + token = iterator.stepForward(); + } + if (endRange) + session.remove(endRange); + if (startRange) { + session.remove(startRange); + startRow = startRange.start.row; + colDiff = -comment.start.length; + } + } else { + colDiff = comment.start.length; + startRow = range.start.row; + session.insert(range.end, comment.end); + session.insert(range.start, comment.start); + } + if (initialRange.start.row == startRow) + initialRange.start.column += colDiff; + if (initialRange.end.row == startRow) + initialRange.end.column += colDiff; + session.selection.fromOrientedRange(initialRange); + }; + + this.getNextLineIndent = function(state, line, tab) { + return this.$getIndent(line); + }; + + this.checkOutdent = function(state, line, input) { + return false; + }; + + this.autoOutdent = function(state, doc, row) { + }; + + this.$getIndent = function(line) { + return line.match(/^\s*/)[0]; + }; + + this.createWorker = function(session) { + return null; + }; + + this.createModeDelegates = function (mapping) { + this.$embeds = []; + this.$modes = {}; + for (var i in mapping) { + if (mapping[i]) { + this.$embeds.push(i); + this.$modes[i] = new mapping[i](); + } + } + + var delegations = ["toggleBlockComment", "toggleCommentLines", "getNextLineIndent", + "checkOutdent", "autoOutdent", "transformAction", "getCompletions"]; + + for (var i = 0; i < delegations.length; i++) { + (function(scope) { + var functionName = delegations[i]; + var defaultHandler = scope[functionName]; + scope[delegations[i]] = function() { + return this.$delegator(functionName, arguments, defaultHandler); + }; + }(this)); + } + }; + + this.$delegator = function(method, args, defaultHandler) { + var state = args[0]; + if (typeof state != "string") + state = state[0]; + for (var i = 0; i < this.$embeds.length; i++) { + if (!this.$modes[this.$embeds[i]]) continue; + + var split = state.split(this.$embeds[i]); + if (!split[0] && split[1]) { + args[0] = split[1]; + var mode = this.$modes[this.$embeds[i]]; + return mode[method].apply(mode, args); + } + } + var ret = defaultHandler.apply(this, args); + return defaultHandler ? ret : undefined; + }; + + this.transformAction = function(state, action, editor, session, param) { + if (this.$behaviour) { + var behaviours = this.$behaviour.getBehaviours(); + for (var key in behaviours) { + if (behaviours[key][action]) { + var ret = behaviours[key][action].apply(this, arguments); + if (ret) { + return ret; + } + } + } + } + }; + + this.getKeywords = function(append) { + if (!this.completionKeywords) { + var rules = this.$tokenizer.rules; + var completionKeywords = []; + for (var rule in rules) { + var ruleItr = rules[rule]; + for (var r = 0, l = ruleItr.length; r < l; r++) { + if (typeof ruleItr[r].token === "string") { + if (/keyword|support|storage/.test(ruleItr[r].token)) + completionKeywords.push(ruleItr[r].regex); + } + else if (typeof ruleItr[r].token === "object") { + for (var a = 0, aLength = ruleItr[r].token.length; a < aLength; a++) { + if (/keyword|support|storage/.test(ruleItr[r].token[a])) { + var rule = ruleItr[r].regex.match(/\(.+?\)/g)[a]; + completionKeywords.push(rule.substr(1, rule.length - 2)); + } + } + } + } + } + this.completionKeywords = completionKeywords; + } + if (!append) + return this.$keywordList; + return completionKeywords.concat(this.$keywordList || []); + }; + + this.$createKeywordList = function() { + if (!this.$highlightRules) + this.getTokenizer(); + return this.$keywordList = this.$highlightRules.$keywordList || []; + }; + + this.getCompletions = function(state, session, pos, prefix) { + var keywords = this.$keywordList || this.$createKeywordList(); + return keywords.map(function(word) { + return { + name: word, + value: word, + score: 0, + meta: "keyword" + }; + }); + }; + + this.$id = "ace/mode/text"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +ace.define("ace/apply_delta",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +function throwDeltaError(delta, errorText){ + console.log("Invalid Delta:", delta); + throw "Invalid Delta: " + errorText; +} + +function positionInDocument(docLines, position) { + return position.row >= 0 && position.row < docLines.length && + position.column >= 0 && position.column <= docLines[position.row].length; +} + +function validateDelta(docLines, delta) { + if (delta.action != "insert" && delta.action != "remove") + throwDeltaError(delta, "delta.action must be 'insert' or 'remove'"); + if (!(delta.lines instanceof Array)) + throwDeltaError(delta, "delta.lines must be an Array"); + if (!delta.start || !delta.end) + throwDeltaError(delta, "delta.start/end must be an present"); + var start = delta.start; + if (!positionInDocument(docLines, delta.start)) + throwDeltaError(delta, "delta.start must be contained in document"); + var end = delta.end; + if (delta.action == "remove" && !positionInDocument(docLines, end)) + throwDeltaError(delta, "delta.end must contained in document for 'remove' actions"); + var numRangeRows = end.row - start.row; + var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0)); + if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars) + throwDeltaError(delta, "delta.range must match delta lines"); +} + +exports.applyDelta = function(docLines, delta, doNotValidate) { + + var row = delta.start.row; + var startColumn = delta.start.column; + var line = docLines[row] || ""; + switch (delta.action) { + case "insert": + var lines = delta.lines; + if (lines.length === 1) { + docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn); + } else { + var args = [row, 1].concat(delta.lines); + docLines.splice.apply(docLines, args); + docLines[row] = line.substring(0, startColumn) + docLines[row]; + docLines[row + delta.lines.length - 1] += line.substring(startColumn); + } + break; + case "remove": + var endColumn = delta.end.column; + var endRow = delta.end.row; + if (row === endRow) { + docLines[row] = line.substring(0, startColumn) + line.substring(endColumn); + } else { + docLines.splice( + row, endRow - row + 1, + line.substring(0, startColumn) + docLines[endRow].substring(endColumn) + ); + } + break; + } +}; +}); + +ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; + +var Anchor = exports.Anchor = function(doc, row, column) { + this.$onChange = this.onChange.bind(this); + this.attach(doc); + + if (typeof column == "undefined") + this.setPosition(row.row, row.column); + else + this.setPosition(row, column); +}; + +(function() { + + oop.implement(this, EventEmitter); + this.getPosition = function() { + return this.$clipPositionToDocument(this.row, this.column); + }; + this.getDocument = function() { + return this.document; + }; + this.$insertRight = false; + this.onChange = function(delta) { + if (delta.start.row == delta.end.row && delta.start.row != this.row) + return; + + if (delta.start.row > this.row) + return; + + var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight); + this.setPosition(point.row, point.column, true); + }; + + function $pointsInOrder(point1, point2, equalPointsInOrder) { + var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column; + return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter); + } + + function $getTransformedPoint(delta, point, moveIfEqual) { + var deltaIsInsert = delta.action == "insert"; + var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row); + var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column); + var deltaStart = delta.start; + var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range. + if ($pointsInOrder(point, deltaStart, moveIfEqual)) { + return { + row: point.row, + column: point.column + }; + } + if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) { + return { + row: point.row + deltaRowShift, + column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0) + }; + } + + return { + row: deltaStart.row, + column: deltaStart.column + }; + } + this.setPosition = function(row, column, noClip) { + var pos; + if (noClip) { + pos = { + row: row, + column: column + }; + } else { + pos = this.$clipPositionToDocument(row, column); + } + + if (this.row == pos.row && this.column == pos.column) + return; + + var old = { + row: this.row, + column: this.column + }; + + this.row = pos.row; + this.column = pos.column; + this._signal("change", { + old: old, + value: pos + }); + }; + this.detach = function() { + this.document.removeEventListener("change", this.$onChange); + }; + this.attach = function(doc) { + this.document = doc || this.document; + this.document.on("change", this.$onChange); + }; + this.$clipPositionToDocument = function(row, column) { + var pos = {}; + + if (row >= this.document.getLength()) { + pos.row = Math.max(0, this.document.getLength() - 1); + pos.column = this.document.getLine(pos.row).length; + } + else if (row < 0) { + pos.row = 0; + pos.column = 0; + } + else { + pos.row = row; + pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column)); + } + + if (column < 0) + pos.column = 0; + + return pos; + }; + +}).call(Anchor.prototype); + +}); + +ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var applyDelta = acequire("./apply_delta").applyDelta; +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var Range = acequire("./range").Range; +var Anchor = acequire("./anchor").Anchor; + +var Document = function(textOrLines) { + this.$lines = [""]; + if (textOrLines.length === 0) { + this.$lines = [""]; + } else if (Array.isArray(textOrLines)) { + this.insertMergedLines({row: 0, column: 0}, textOrLines); + } else { + this.insert({row: 0, column:0}, textOrLines); + } +}; + +(function() { + + oop.implement(this, EventEmitter); + this.setValue = function(text) { + var len = this.getLength() - 1; + this.remove(new Range(0, 0, len, this.getLine(len).length)); + this.insert({row: 0, column: 0}, text); + }; + this.getValue = function() { + return this.getAllLines().join(this.getNewLineCharacter()); + }; + this.createAnchor = function(row, column) { + return new Anchor(this, row, column); + }; + if ("aaa".split(/a/).length === 0) { + this.$split = function(text) { + return text.replace(/\r\n|\r/g, "\n").split("\n"); + }; + } else { + this.$split = function(text) { + return text.split(/\r\n|\r|\n/); + }; + } + + + this.$detectNewLine = function(text) { + var match = text.match(/^.*?(\r\n|\r|\n)/m); + this.$autoNewLine = match ? match[1] : "\n"; + this._signal("changeNewLineMode"); + }; + this.getNewLineCharacter = function() { + switch (this.$newLineMode) { + case "windows": + return "\r\n"; + case "unix": + return "\n"; + default: + return this.$autoNewLine || "\n"; + } + }; + + this.$autoNewLine = ""; + this.$newLineMode = "auto"; + this.setNewLineMode = function(newLineMode) { + if (this.$newLineMode === newLineMode) + return; + + this.$newLineMode = newLineMode; + this._signal("changeNewLineMode"); + }; + this.getNewLineMode = function() { + return this.$newLineMode; + }; + this.isNewLine = function(text) { + return (text == "\r\n" || text == "\r" || text == "\n"); + }; + this.getLine = function(row) { + return this.$lines[row] || ""; + }; + this.getLines = function(firstRow, lastRow) { + return this.$lines.slice(firstRow, lastRow + 1); + }; + this.getAllLines = function() { + return this.getLines(0, this.getLength()); + }; + this.getLength = function() { + return this.$lines.length; + }; + this.getTextRange = function(range) { + return this.getLinesForRange(range).join(this.getNewLineCharacter()); + }; + this.getLinesForRange = function(range) { + var lines; + if (range.start.row === range.end.row) { + lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)]; + } else { + lines = this.getLines(range.start.row, range.end.row); + lines[0] = (lines[0] || "").substring(range.start.column); + var l = lines.length - 1; + if (range.end.row - range.start.row == l) + lines[l] = lines[l].substring(0, range.end.column); + } + return lines; + }; + this.insertLines = function(row, lines) { + console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead."); + return this.insertFullLines(row, lines); + }; + this.removeLines = function(firstRow, lastRow) { + console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead."); + return this.removeFullLines(firstRow, lastRow); + }; + this.insertNewLine = function(position) { + console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead."); + return this.insertMergedLines(position, ["", ""]); + }; + this.insert = function(position, text) { + if (this.getLength() <= 1) + this.$detectNewLine(text); + + return this.insertMergedLines(position, this.$split(text)); + }; + this.insertInLine = function(position, text) { + var start = this.clippedPos(position.row, position.column); + var end = this.pos(position.row, position.column + text.length); + + this.applyDelta({ + start: start, + end: end, + action: "insert", + lines: [text] + }, true); + + return this.clonePos(end); + }; + + this.clippedPos = function(row, column) { + var length = this.getLength(); + if (row === undefined) { + row = length; + } else if (row < 0) { + row = 0; + } else if (row >= length) { + row = length - 1; + column = undefined; + } + var line = this.getLine(row); + if (column == undefined) + column = line.length; + column = Math.min(Math.max(column, 0), line.length); + return {row: row, column: column}; + }; + + this.clonePos = function(pos) { + return {row: pos.row, column: pos.column}; + }; + + this.pos = function(row, column) { + return {row: row, column: column}; + }; + + this.$clipPosition = function(position) { + var length = this.getLength(); + if (position.row >= length) { + position.row = Math.max(0, length - 1); + position.column = this.getLine(length - 1).length; + } else { + position.row = Math.max(0, position.row); + position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length); + } + return position; + }; + this.insertFullLines = function(row, lines) { + row = Math.min(Math.max(row, 0), this.getLength()); + var column = 0; + if (row < this.getLength()) { + lines = lines.concat([""]); + column = 0; + } else { + lines = [""].concat(lines); + row--; + column = this.$lines[row].length; + } + this.insertMergedLines({row: row, column: column}, lines); + }; + this.insertMergedLines = function(position, lines) { + var start = this.clippedPos(position.row, position.column); + var end = { + row: start.row + lines.length - 1, + column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length + }; + + this.applyDelta({ + start: start, + end: end, + action: "insert", + lines: lines + }); + + return this.clonePos(end); + }; + this.remove = function(range) { + var start = this.clippedPos(range.start.row, range.start.column); + var end = this.clippedPos(range.end.row, range.end.column); + this.applyDelta({ + start: start, + end: end, + action: "remove", + lines: this.getLinesForRange({start: start, end: end}) + }); + return this.clonePos(start); + }; + this.removeInLine = function(row, startColumn, endColumn) { + var start = this.clippedPos(row, startColumn); + var end = this.clippedPos(row, endColumn); + + this.applyDelta({ + start: start, + end: end, + action: "remove", + lines: this.getLinesForRange({start: start, end: end}) + }, true); + + return this.clonePos(start); + }; + this.removeFullLines = function(firstRow, lastRow) { + firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1); + lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1); + var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0; + var deleteLastNewLine = lastRow < this.getLength() - 1; + var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow ); + var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 ); + var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow ); + var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length ); + var range = new Range(startRow, startCol, endRow, endCol); + var deletedLines = this.$lines.slice(firstRow, lastRow + 1); + + this.applyDelta({ + start: range.start, + end: range.end, + action: "remove", + lines: this.getLinesForRange(range) + }); + return deletedLines; + }; + this.removeNewLine = function(row) { + if (row < this.getLength() - 1 && row >= 0) { + this.applyDelta({ + start: this.pos(row, this.getLine(row).length), + end: this.pos(row + 1, 0), + action: "remove", + lines: ["", ""] + }); + } + }; + this.replace = function(range, text) { + if (!(range instanceof Range)) + range = Range.fromPoints(range.start, range.end); + if (text.length === 0 && range.isEmpty()) + return range.start; + if (text == this.getTextRange(range)) + return range.end; + + this.remove(range); + var end; + if (text) { + end = this.insert(range.start, text); + } + else { + end = range.start; + } + + return end; + }; + this.applyDeltas = function(deltas) { + for (var i=0; i=0; i--) { + this.revertDelta(deltas[i]); + } + }; + this.applyDelta = function(delta, doNotValidate) { + var isInsert = delta.action == "insert"; + if (isInsert ? delta.lines.length <= 1 && !delta.lines[0] + : !Range.comparePoints(delta.start, delta.end)) { + return; + } + + if (isInsert && delta.lines.length > 20000) + this.$splitAndapplyLargeDelta(delta, 20000); + applyDelta(this.$lines, delta, doNotValidate); + this._signal("change", delta); + }; + + this.$splitAndapplyLargeDelta = function(delta, MAX) { + var lines = delta.lines; + var l = lines.length; + var row = delta.start.row; + var column = delta.start.column; + var from = 0, to = 0; + do { + from = to; + to += MAX - 1; + var chunk = lines.slice(from, to); + if (to > l) { + delta.lines = chunk; + delta.start.row = row + from; + delta.start.column = column; + break; + } + chunk.push(""); + this.applyDelta({ + start: this.pos(row + from, column), + end: this.pos(row + to, column = 0), + action: delta.action, + lines: chunk + }, true); + } while(true); + }; + this.revertDelta = function(delta) { + this.applyDelta({ + start: this.clonePos(delta.start), + end: this.clonePos(delta.end), + action: (delta.action == "insert" ? "remove" : "insert"), + lines: delta.lines.slice() + }); + }; + this.indexToPosition = function(index, startRow) { + var lines = this.$lines || this.getAllLines(); + var newlineLength = this.getNewLineCharacter().length; + for (var i = startRow || 0, l = lines.length; i < l; i++) { + index -= lines[i].length + newlineLength; + if (index < 0) + return {row: i, column: index + lines[i].length + newlineLength}; + } + return {row: l-1, column: lines[l-1].length}; + }; + this.positionToIndex = function(pos, startRow) { + var lines = this.$lines || this.getAllLines(); + var newlineLength = this.getNewLineCharacter().length; + var index = 0; + var row = Math.min(pos.row, lines.length); + for (var i = startRow || 0; i < row; ++i) + index += lines[i].length + newlineLength; + + return index + pos.column; + }; + +}).call(Document.prototype); + +exports.Document = Document; +}); + +ace.define("ace/background_tokenizer",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; + +var BackgroundTokenizer = function(tokenizer, editor) { + this.running = false; + this.lines = []; + this.states = []; + this.currentLine = 0; + this.tokenizer = tokenizer; + + var self = this; + + this.$worker = function() { + if (!self.running) { return; } + + var workerStart = new Date(); + var currentLine = self.currentLine; + var endLine = -1; + var doc = self.doc; + + var startLine = currentLine; + while (self.lines[currentLine]) + currentLine++; + + var len = doc.getLength(); + var processedLines = 0; + self.running = false; + while (currentLine < len) { + self.$tokenizeRow(currentLine); + endLine = currentLine; + do { + currentLine++; + } while (self.lines[currentLine]); + processedLines ++; + if ((processedLines % 5 === 0) && (new Date() - workerStart) > 20) { + self.running = setTimeout(self.$worker, 20); + break; + } + } + self.currentLine = currentLine; + + if (endLine == -1) + endLine = currentLine; + + if (startLine <= endLine) + self.fireUpdateEvent(startLine, endLine); + }; +}; + +(function(){ + + oop.implement(this, EventEmitter); + this.setTokenizer = function(tokenizer) { + this.tokenizer = tokenizer; + this.lines = []; + this.states = []; + + this.start(0); + }; + this.setDocument = function(doc) { + this.doc = doc; + this.lines = []; + this.states = []; + + this.stop(); + }; + this.fireUpdateEvent = function(firstRow, lastRow) { + var data = { + first: firstRow, + last: lastRow + }; + this._signal("update", {data: data}); + }; + this.start = function(startRow) { + this.currentLine = Math.min(startRow || 0, this.currentLine, this.doc.getLength()); + this.lines.splice(this.currentLine, this.lines.length); + this.states.splice(this.currentLine, this.states.length); + + this.stop(); + this.running = setTimeout(this.$worker, 700); + }; + + this.scheduleStart = function() { + if (!this.running) + this.running = setTimeout(this.$worker, 700); + }; + + this.$updateOnChange = function(delta) { + var startRow = delta.start.row; + var len = delta.end.row - startRow; + + if (len === 0) { + this.lines[startRow] = null; + } else if (delta.action == "remove") { + this.lines.splice(startRow, len + 1, null); + this.states.splice(startRow, len + 1, null); + } else { + var args = Array(len + 1); + args.unshift(startRow, 1); + this.lines.splice.apply(this.lines, args); + this.states.splice.apply(this.states, args); + } + + this.currentLine = Math.min(startRow, this.currentLine, this.doc.getLength()); + + this.stop(); + }; + this.stop = function() { + if (this.running) + clearTimeout(this.running); + this.running = false; + }; + this.getTokens = function(row) { + return this.lines[row] || this.$tokenizeRow(row); + }; + this.getState = function(row) { + if (this.currentLine == row) + this.$tokenizeRow(row); + return this.states[row] || "start"; + }; + + this.$tokenizeRow = function(row) { + var line = this.doc.getLine(row); + var state = this.states[row - 1]; + + var data = this.tokenizer.getLineTokens(line, state, row); + + if (this.states[row] + "" !== data.state + "") { + this.states[row] = data.state; + this.lines[row + 1] = null; + if (this.currentLine > row + 1) + this.currentLine = row + 1; + } else if (this.currentLine == row) { + this.currentLine = row + 1; + } + + return this.lines[row] = data.tokens; + }; + +}).call(BackgroundTokenizer.prototype); + +exports.BackgroundTokenizer = BackgroundTokenizer; +}); + +ace.define("ace/search_highlight",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"], function(acequire, exports, module) { +"use strict"; + +var lang = acequire("./lib/lang"); +var oop = acequire("./lib/oop"); +var Range = acequire("./range").Range; + +var SearchHighlight = function(regExp, clazz, type) { + this.setRegexp(regExp); + this.clazz = clazz; + this.type = type || "text"; +}; + +(function() { + this.MAX_RANGES = 500; + + this.setRegexp = function(regExp) { + if (this.regExp+"" == regExp+"") + return; + this.regExp = regExp; + this.cache = []; + }; + + this.update = function(html, markerLayer, session, config) { + if (!this.regExp) + return; + var start = config.firstRow, end = config.lastRow; + + for (var i = start; i <= end; i++) { + var ranges = this.cache[i]; + if (ranges == null) { + ranges = lang.getMatchOffsets(session.getLine(i), this.regExp); + if (ranges.length > this.MAX_RANGES) + ranges = ranges.slice(0, this.MAX_RANGES); + ranges = ranges.map(function(match) { + return new Range(i, match.offset, i, match.offset + match.length); + }); + this.cache[i] = ranges.length ? ranges : ""; + } + + for (var j = ranges.length; j --; ) { + markerLayer.drawSingleLineMarker( + html, ranges[j].toScreenRange(session), this.clazz, config); + } + } + }; + +}).call(SearchHighlight.prototype); + +exports.SearchHighlight = SearchHighlight; +}); + +ace.define("ace/edit_session/fold_line",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; +function FoldLine(foldData, folds) { + this.foldData = foldData; + if (Array.isArray(folds)) { + this.folds = folds; + } else { + folds = this.folds = [ folds ]; + } + + var last = folds[folds.length - 1]; + this.range = new Range(folds[0].start.row, folds[0].start.column, + last.end.row, last.end.column); + this.start = this.range.start; + this.end = this.range.end; + + this.folds.forEach(function(fold) { + fold.setFoldLine(this); + }, this); +} + +(function() { + this.shiftRow = function(shift) { + this.start.row += shift; + this.end.row += shift; + this.folds.forEach(function(fold) { + fold.start.row += shift; + fold.end.row += shift; + }); + }; + + this.addFold = function(fold) { + if (fold.sameRow) { + if (fold.start.row < this.startRow || fold.endRow > this.endRow) { + throw new Error("Can't add a fold to this FoldLine as it has no connection"); + } + this.folds.push(fold); + this.folds.sort(function(a, b) { + return -a.range.compareEnd(b.start.row, b.start.column); + }); + if (this.range.compareEnd(fold.start.row, fold.start.column) > 0) { + this.end.row = fold.end.row; + this.end.column = fold.end.column; + } else if (this.range.compareStart(fold.end.row, fold.end.column) < 0) { + this.start.row = fold.start.row; + this.start.column = fold.start.column; + } + } else if (fold.start.row == this.end.row) { + this.folds.push(fold); + this.end.row = fold.end.row; + this.end.column = fold.end.column; + } else if (fold.end.row == this.start.row) { + this.folds.unshift(fold); + this.start.row = fold.start.row; + this.start.column = fold.start.column; + } else { + throw new Error("Trying to add fold to FoldRow that doesn't have a matching row"); + } + fold.foldLine = this; + }; + + this.containsRow = function(row) { + return row >= this.start.row && row <= this.end.row; + }; + + this.walk = function(callback, endRow, endColumn) { + var lastEnd = 0, + folds = this.folds, + fold, + cmp, stop, isNewRow = true; + + if (endRow == null) { + endRow = this.end.row; + endColumn = this.end.column; + } + + for (var i = 0; i < folds.length; i++) { + fold = folds[i]; + + cmp = fold.range.compareStart(endRow, endColumn); + if (cmp == -1) { + callback(null, endRow, endColumn, lastEnd, isNewRow); + return; + } + + stop = callback(null, fold.start.row, fold.start.column, lastEnd, isNewRow); + stop = !stop && callback(fold.placeholder, fold.start.row, fold.start.column, lastEnd); + if (stop || cmp === 0) { + return; + } + isNewRow = !fold.sameRow; + lastEnd = fold.end.column; + } + callback(null, endRow, endColumn, lastEnd, isNewRow); + }; + + this.getNextFoldTo = function(row, column) { + var fold, cmp; + for (var i = 0; i < this.folds.length; i++) { + fold = this.folds[i]; + cmp = fold.range.compareEnd(row, column); + if (cmp == -1) { + return { + fold: fold, + kind: "after" + }; + } else if (cmp === 0) { + return { + fold: fold, + kind: "inside" + }; + } + } + return null; + }; + + this.addRemoveChars = function(row, column, len) { + var ret = this.getNextFoldTo(row, column), + fold, folds; + if (ret) { + fold = ret.fold; + if (ret.kind == "inside" + && fold.start.column != column + && fold.start.row != row) + { + window.console && window.console.log(row, column, fold); + } else if (fold.start.row == row) { + folds = this.folds; + var i = folds.indexOf(fold); + if (i === 0) { + this.start.column += len; + } + for (i; i < folds.length; i++) { + fold = folds[i]; + fold.start.column += len; + if (!fold.sameRow) { + return; + } + fold.end.column += len; + } + this.end.column += len; + } + } + }; + + this.split = function(row, column) { + var pos = this.getNextFoldTo(row, column); + + if (!pos || pos.kind == "inside") + return null; + + var fold = pos.fold; + var folds = this.folds; + var foldData = this.foldData; + + var i = folds.indexOf(fold); + var foldBefore = folds[i - 1]; + this.end.row = foldBefore.end.row; + this.end.column = foldBefore.end.column; + folds = folds.splice(i, folds.length - i); + + var newFoldLine = new FoldLine(foldData, folds); + foldData.splice(foldData.indexOf(this) + 1, 0, newFoldLine); + return newFoldLine; + }; + + this.merge = function(foldLineNext) { + var folds = foldLineNext.folds; + for (var i = 0; i < folds.length; i++) { + this.addFold(folds[i]); + } + var foldData = this.foldData; + foldData.splice(foldData.indexOf(foldLineNext), 1); + }; + + this.toString = function() { + var ret = [this.range.toString() + ": [" ]; + + this.folds.forEach(function(fold) { + ret.push(" " + fold.toString()); + }); + ret.push("]"); + return ret.join("\n"); + }; + + this.idxToPosition = function(idx) { + var lastFoldEndColumn = 0; + + for (var i = 0; i < this.folds.length; i++) { + var fold = this.folds[i]; + + idx -= fold.start.column - lastFoldEndColumn; + if (idx < 0) { + return { + row: fold.start.row, + column: fold.start.column + idx + }; + } + + idx -= fold.placeholder.length; + if (idx < 0) { + return fold.start; + } + + lastFoldEndColumn = fold.end.column; + } + + return { + row: this.end.row, + column: this.end.column + idx + }; + }; +}).call(FoldLine.prototype); + +exports.FoldLine = FoldLine; +}); + +ace.define("ace/range_list",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; +var Range = acequire("./range").Range; +var comparePoints = Range.comparePoints; + +var RangeList = function() { + this.ranges = []; +}; + +(function() { + this.comparePoints = comparePoints; + + this.pointIndex = function(pos, excludeEdges, startIndex) { + var list = this.ranges; + + for (var i = startIndex || 0; i < list.length; i++) { + var range = list[i]; + var cmpEnd = comparePoints(pos, range.end); + if (cmpEnd > 0) + continue; + var cmpStart = comparePoints(pos, range.start); + if (cmpEnd === 0) + return excludeEdges && cmpStart !== 0 ? -i-2 : i; + if (cmpStart > 0 || (cmpStart === 0 && !excludeEdges)) + return i; + + return -i-1; + } + return -i - 1; + }; + + this.add = function(range) { + var excludeEdges = !range.isEmpty(); + var startIndex = this.pointIndex(range.start, excludeEdges); + if (startIndex < 0) + startIndex = -startIndex - 1; + + var endIndex = this.pointIndex(range.end, excludeEdges, startIndex); + + if (endIndex < 0) + endIndex = -endIndex - 1; + else + endIndex++; + return this.ranges.splice(startIndex, endIndex - startIndex, range); + }; + + this.addList = function(list) { + var removed = []; + for (var i = list.length; i--; ) { + removed.push.apply(removed, this.add(list[i])); + } + return removed; + }; + + this.substractPoint = function(pos) { + var i = this.pointIndex(pos); + + if (i >= 0) + return this.ranges.splice(i, 1); + }; + this.merge = function() { + var removed = []; + var list = this.ranges; + + list = list.sort(function(a, b) { + return comparePoints(a.start, b.start); + }); + + var next = list[0], range; + for (var i = 1; i < list.length; i++) { + range = next; + next = list[i]; + var cmp = comparePoints(range.end, next.start); + if (cmp < 0) + continue; + + if (cmp == 0 && !range.isEmpty() && !next.isEmpty()) + continue; + + if (comparePoints(range.end, next.end) < 0) { + range.end.row = next.end.row; + range.end.column = next.end.column; + } + + list.splice(i, 1); + removed.push(next); + next = range; + i--; + } + + this.ranges = list; + + return removed; + }; + + this.contains = function(row, column) { + return this.pointIndex({row: row, column: column}) >= 0; + }; + + this.containsPoint = function(pos) { + return this.pointIndex(pos) >= 0; + }; + + this.rangeAtPoint = function(pos) { + var i = this.pointIndex(pos); + if (i >= 0) + return this.ranges[i]; + }; + + + this.clipRows = function(startRow, endRow) { + var list = this.ranges; + if (list[0].start.row > endRow || list[list.length - 1].start.row < startRow) + return []; + + var startIndex = this.pointIndex({row: startRow, column: 0}); + if (startIndex < 0) + startIndex = -startIndex - 1; + var endIndex = this.pointIndex({row: endRow, column: 0}, startIndex); + if (endIndex < 0) + endIndex = -endIndex - 1; + + var clipped = []; + for (var i = startIndex; i < endIndex; i++) { + clipped.push(list[i]); + } + return clipped; + }; + + this.removeAll = function() { + return this.ranges.splice(0, this.ranges.length); + }; + + this.attach = function(session) { + if (this.session) + this.detach(); + + this.session = session; + this.onChange = this.$onChange.bind(this); + + this.session.on('change', this.onChange); + }; + + this.detach = function() { + if (!this.session) + return; + this.session.removeListener('change', this.onChange); + this.session = null; + }; + + this.$onChange = function(delta) { + if (delta.action == "insert"){ + var start = delta.start; + var end = delta.end; + } else { + var end = delta.start; + var start = delta.end; + } + var startRow = start.row; + var endRow = end.row; + var lineDif = endRow - startRow; + + var colDiff = -start.column + end.column; + var ranges = this.ranges; + + for (var i = 0, n = ranges.length; i < n; i++) { + var r = ranges[i]; + if (r.end.row < startRow) + continue; + if (r.start.row > startRow) + break; + + if (r.start.row == startRow && r.start.column >= start.column ) { + if (r.start.column == start.column && this.$insertRight) { + } else { + r.start.column += colDiff; + r.start.row += lineDif; + } + } + if (r.end.row == startRow && r.end.column >= start.column) { + if (r.end.column == start.column && this.$insertRight) { + continue; + } + if (r.end.column == start.column && colDiff > 0 && i < n - 1) { + if (r.end.column > r.start.column && r.end.column == ranges[i+1].start.column) + r.end.column -= colDiff; + } + r.end.column += colDiff; + r.end.row += lineDif; + } + } + + if (lineDif != 0 && i < n) { + for (; i < n; i++) { + var r = ranges[i]; + r.start.row += lineDif; + r.end.row += lineDif; + } + } + }; + +}).call(RangeList.prototype); + +exports.RangeList = RangeList; +}); + +ace.define("ace/edit_session/fold",["require","exports","module","ace/range","ace/range_list","ace/lib/oop"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; +var RangeList = acequire("../range_list").RangeList; +var oop = acequire("../lib/oop"); +var Fold = exports.Fold = function(range, placeholder) { + this.foldLine = null; + this.placeholder = placeholder; + this.range = range; + this.start = range.start; + this.end = range.end; + + this.sameRow = range.start.row == range.end.row; + this.subFolds = this.ranges = []; +}; + +oop.inherits(Fold, RangeList); + +(function() { + + this.toString = function() { + return '"' + this.placeholder + '" ' + this.range.toString(); + }; + + this.setFoldLine = function(foldLine) { + this.foldLine = foldLine; + this.subFolds.forEach(function(fold) { + fold.setFoldLine(foldLine); + }); + }; + + this.clone = function() { + var range = this.range.clone(); + var fold = new Fold(range, this.placeholder); + this.subFolds.forEach(function(subFold) { + fold.subFolds.push(subFold.clone()); + }); + fold.collapseChildren = this.collapseChildren; + return fold; + }; + + this.addSubFold = function(fold) { + if (this.range.isEqual(fold)) + return; + + if (!this.range.containsRange(fold)) + throw new Error("A fold can't intersect already existing fold" + fold.range + this.range); + consumeRange(fold, this.start); + + var row = fold.start.row, column = fold.start.column; + for (var i = 0, cmp = -1; i < this.subFolds.length; i++) { + cmp = this.subFolds[i].range.compare(row, column); + if (cmp != 1) + break; + } + var afterStart = this.subFolds[i]; + + if (cmp == 0) + return afterStart.addSubFold(fold); + var row = fold.range.end.row, column = fold.range.end.column; + for (var j = i, cmp = -1; j < this.subFolds.length; j++) { + cmp = this.subFolds[j].range.compare(row, column); + if (cmp != 1) + break; + } + var afterEnd = this.subFolds[j]; + + if (cmp == 0) + throw new Error("A fold can't intersect already existing fold" + fold.range + this.range); + + var consumedFolds = this.subFolds.splice(i, j - i, fold); + fold.setFoldLine(this.foldLine); + + return fold; + }; + + this.restoreRange = function(range) { + return restoreRange(range, this.start); + }; + +}).call(Fold.prototype); + +function consumePoint(point, anchor) { + point.row -= anchor.row; + if (point.row == 0) + point.column -= anchor.column; +} +function consumeRange(range, anchor) { + consumePoint(range.start, anchor); + consumePoint(range.end, anchor); +} +function restorePoint(point, anchor) { + if (point.row == 0) + point.column += anchor.column; + point.row += anchor.row; +} +function restoreRange(range, anchor) { + restorePoint(range.start, anchor); + restorePoint(range.end, anchor); +} + +}); + +ace.define("ace/edit_session/folding",["require","exports","module","ace/range","ace/edit_session/fold_line","ace/edit_session/fold","ace/token_iterator"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; +var FoldLine = acequire("./fold_line").FoldLine; +var Fold = acequire("./fold").Fold; +var TokenIterator = acequire("../token_iterator").TokenIterator; + +function Folding() { + this.getFoldAt = function(row, column, side) { + var foldLine = this.getFoldLine(row); + if (!foldLine) + return null; + + var folds = foldLine.folds; + for (var i = 0; i < folds.length; i++) { + var fold = folds[i]; + if (fold.range.contains(row, column)) { + if (side == 1 && fold.range.isEnd(row, column)) { + continue; + } else if (side == -1 && fold.range.isStart(row, column)) { + continue; + } + return fold; + } + } + }; + this.getFoldsInRange = function(range) { + var start = range.start; + var end = range.end; + var foldLines = this.$foldData; + var foundFolds = []; + + start.column += 1; + end.column -= 1; + + for (var i = 0; i < foldLines.length; i++) { + var cmp = foldLines[i].range.compareRange(range); + if (cmp == 2) { + continue; + } + else if (cmp == -2) { + break; + } + + var folds = foldLines[i].folds; + for (var j = 0; j < folds.length; j++) { + var fold = folds[j]; + cmp = fold.range.compareRange(range); + if (cmp == -2) { + break; + } else if (cmp == 2) { + continue; + } else + if (cmp == 42) { + break; + } + foundFolds.push(fold); + } + } + start.column -= 1; + end.column += 1; + + return foundFolds; + }; + + this.getFoldsInRangeList = function(ranges) { + if (Array.isArray(ranges)) { + var folds = []; + ranges.forEach(function(range) { + folds = folds.concat(this.getFoldsInRange(range)); + }, this); + } else { + var folds = this.getFoldsInRange(ranges); + } + return folds; + }; + this.getAllFolds = function() { + var folds = []; + var foldLines = this.$foldData; + + for (var i = 0; i < foldLines.length; i++) + for (var j = 0; j < foldLines[i].folds.length; j++) + folds.push(foldLines[i].folds[j]); + + return folds; + }; + this.getFoldStringAt = function(row, column, trim, foldLine) { + foldLine = foldLine || this.getFoldLine(row); + if (!foldLine) + return null; + + var lastFold = { + end: { column: 0 } + }; + var str, fold; + for (var i = 0; i < foldLine.folds.length; i++) { + fold = foldLine.folds[i]; + var cmp = fold.range.compareEnd(row, column); + if (cmp == -1) { + str = this + .getLine(fold.start.row) + .substring(lastFold.end.column, fold.start.column); + break; + } + else if (cmp === 0) { + return null; + } + lastFold = fold; + } + if (!str) + str = this.getLine(fold.start.row).substring(lastFold.end.column); + + if (trim == -1) + return str.substring(0, column - lastFold.end.column); + else if (trim == 1) + return str.substring(column - lastFold.end.column); + else + return str; + }; + + this.getFoldLine = function(docRow, startFoldLine) { + var foldData = this.$foldData; + var i = 0; + if (startFoldLine) + i = foldData.indexOf(startFoldLine); + if (i == -1) + i = 0; + for (i; i < foldData.length; i++) { + var foldLine = foldData[i]; + if (foldLine.start.row <= docRow && foldLine.end.row >= docRow) { + return foldLine; + } else if (foldLine.end.row > docRow) { + return null; + } + } + return null; + }; + this.getNextFoldLine = function(docRow, startFoldLine) { + var foldData = this.$foldData; + var i = 0; + if (startFoldLine) + i = foldData.indexOf(startFoldLine); + if (i == -1) + i = 0; + for (i; i < foldData.length; i++) { + var foldLine = foldData[i]; + if (foldLine.end.row >= docRow) { + return foldLine; + } + } + return null; + }; + + this.getFoldedRowCount = function(first, last) { + var foldData = this.$foldData, rowCount = last-first+1; + for (var i = 0; i < foldData.length; i++) { + var foldLine = foldData[i], + end = foldLine.end.row, + start = foldLine.start.row; + if (end >= last) { + if (start < last) { + if (start >= first) + rowCount -= last-start; + else + rowCount = 0; // in one fold + } + break; + } else if (end >= first){ + if (start >= first) // fold inside range + rowCount -= end-start; + else + rowCount -= end-first+1; + } + } + return rowCount; + }; + + this.$addFoldLine = function(foldLine) { + this.$foldData.push(foldLine); + this.$foldData.sort(function(a, b) { + return a.start.row - b.start.row; + }); + return foldLine; + }; + this.addFold = function(placeholder, range) { + var foldData = this.$foldData; + var added = false; + var fold; + + if (placeholder instanceof Fold) + fold = placeholder; + else { + fold = new Fold(range, placeholder); + fold.collapseChildren = range.collapseChildren; + } + this.$clipRangeToDocument(fold.range); + + var startRow = fold.start.row; + var startColumn = fold.start.column; + var endRow = fold.end.row; + var endColumn = fold.end.column; + if (!(startRow < endRow || + startRow == endRow && startColumn <= endColumn - 2)) + throw new Error("The range has to be at least 2 characters width"); + + var startFold = this.getFoldAt(startRow, startColumn, 1); + var endFold = this.getFoldAt(endRow, endColumn, -1); + if (startFold && endFold == startFold) + return startFold.addSubFold(fold); + + if (startFold && !startFold.range.isStart(startRow, startColumn)) + this.removeFold(startFold); + + if (endFold && !endFold.range.isEnd(endRow, endColumn)) + this.removeFold(endFold); + var folds = this.getFoldsInRange(fold.range); + if (folds.length > 0) { + this.removeFolds(folds); + folds.forEach(function(subFold) { + fold.addSubFold(subFold); + }); + } + + for (var i = 0; i < foldData.length; i++) { + var foldLine = foldData[i]; + if (endRow == foldLine.start.row) { + foldLine.addFold(fold); + added = true; + break; + } else if (startRow == foldLine.end.row) { + foldLine.addFold(fold); + added = true; + if (!fold.sameRow) { + var foldLineNext = foldData[i + 1]; + if (foldLineNext && foldLineNext.start.row == endRow) { + foldLine.merge(foldLineNext); + break; + } + } + break; + } else if (endRow <= foldLine.start.row) { + break; + } + } + + if (!added) + foldLine = this.$addFoldLine(new FoldLine(this.$foldData, fold)); + + if (this.$useWrapMode) + this.$updateWrapData(foldLine.start.row, foldLine.start.row); + else + this.$updateRowLengthCache(foldLine.start.row, foldLine.start.row); + this.$modified = true; + this._signal("changeFold", { data: fold, action: "add" }); + + return fold; + }; + + this.addFolds = function(folds) { + folds.forEach(function(fold) { + this.addFold(fold); + }, this); + }; + + this.removeFold = function(fold) { + var foldLine = fold.foldLine; + var startRow = foldLine.start.row; + var endRow = foldLine.end.row; + + var foldLines = this.$foldData; + var folds = foldLine.folds; + if (folds.length == 1) { + foldLines.splice(foldLines.indexOf(foldLine), 1); + } else + if (foldLine.range.isEnd(fold.end.row, fold.end.column)) { + folds.pop(); + foldLine.end.row = folds[folds.length - 1].end.row; + foldLine.end.column = folds[folds.length - 1].end.column; + } else + if (foldLine.range.isStart(fold.start.row, fold.start.column)) { + folds.shift(); + foldLine.start.row = folds[0].start.row; + foldLine.start.column = folds[0].start.column; + } else + if (fold.sameRow) { + folds.splice(folds.indexOf(fold), 1); + } else + { + var newFoldLine = foldLine.split(fold.start.row, fold.start.column); + folds = newFoldLine.folds; + folds.shift(); + newFoldLine.start.row = folds[0].start.row; + newFoldLine.start.column = folds[0].start.column; + } + + if (!this.$updating) { + if (this.$useWrapMode) + this.$updateWrapData(startRow, endRow); + else + this.$updateRowLengthCache(startRow, endRow); + } + this.$modified = true; + this._signal("changeFold", { data: fold, action: "remove" }); + }; + + this.removeFolds = function(folds) { + var cloneFolds = []; + for (var i = 0; i < folds.length; i++) { + cloneFolds.push(folds[i]); + } + + cloneFolds.forEach(function(fold) { + this.removeFold(fold); + }, this); + this.$modified = true; + }; + + this.expandFold = function(fold) { + this.removeFold(fold); + fold.subFolds.forEach(function(subFold) { + fold.restoreRange(subFold); + this.addFold(subFold); + }, this); + if (fold.collapseChildren > 0) { + this.foldAll(fold.start.row+1, fold.end.row, fold.collapseChildren-1); + } + fold.subFolds = []; + }; + + this.expandFolds = function(folds) { + folds.forEach(function(fold) { + this.expandFold(fold); + }, this); + }; + + this.unfold = function(location, expandInner) { + var range, folds; + if (location == null) { + range = new Range(0, 0, this.getLength(), 0); + expandInner = true; + } else if (typeof location == "number") + range = new Range(location, 0, location, this.getLine(location).length); + else if ("row" in location) + range = Range.fromPoints(location, location); + else + range = location; + + folds = this.getFoldsInRangeList(range); + if (expandInner) { + this.removeFolds(folds); + } else { + var subFolds = folds; + while (subFolds.length) { + this.expandFolds(subFolds); + subFolds = this.getFoldsInRangeList(range); + } + } + if (folds.length) + return folds; + }; + this.isRowFolded = function(docRow, startFoldRow) { + return !!this.getFoldLine(docRow, startFoldRow); + }; + + this.getRowFoldEnd = function(docRow, startFoldRow) { + var foldLine = this.getFoldLine(docRow, startFoldRow); + return foldLine ? foldLine.end.row : docRow; + }; + + this.getRowFoldStart = function(docRow, startFoldRow) { + var foldLine = this.getFoldLine(docRow, startFoldRow); + return foldLine ? foldLine.start.row : docRow; + }; + + this.getFoldDisplayLine = function(foldLine, endRow, endColumn, startRow, startColumn) { + if (startRow == null) + startRow = foldLine.start.row; + if (startColumn == null) + startColumn = 0; + if (endRow == null) + endRow = foldLine.end.row; + if (endColumn == null) + endColumn = this.getLine(endRow).length; + var doc = this.doc; + var textLine = ""; + + foldLine.walk(function(placeholder, row, column, lastColumn) { + if (row < startRow) + return; + if (row == startRow) { + if (column < startColumn) + return; + lastColumn = Math.max(startColumn, lastColumn); + } + + if (placeholder != null) { + textLine += placeholder; + } else { + textLine += doc.getLine(row).substring(lastColumn, column); + } + }, endRow, endColumn); + return textLine; + }; + + this.getDisplayLine = function(row, endColumn, startRow, startColumn) { + var foldLine = this.getFoldLine(row); + + if (!foldLine) { + var line; + line = this.doc.getLine(row); + return line.substring(startColumn || 0, endColumn || line.length); + } else { + return this.getFoldDisplayLine( + foldLine, row, endColumn, startRow, startColumn); + } + }; + + this.$cloneFoldData = function() { + var fd = []; + fd = this.$foldData.map(function(foldLine) { + var folds = foldLine.folds.map(function(fold) { + return fold.clone(); + }); + return new FoldLine(fd, folds); + }); + + return fd; + }; + + this.toggleFold = function(tryToUnfold) { + var selection = this.selection; + var range = selection.getRange(); + var fold; + var bracketPos; + + if (range.isEmpty()) { + var cursor = range.start; + fold = this.getFoldAt(cursor.row, cursor.column); + + if (fold) { + this.expandFold(fold); + return; + } else if (bracketPos = this.findMatchingBracket(cursor)) { + if (range.comparePoint(bracketPos) == 1) { + range.end = bracketPos; + } else { + range.start = bracketPos; + range.start.column++; + range.end.column--; + } + } else if (bracketPos = this.findMatchingBracket({row: cursor.row, column: cursor.column + 1})) { + if (range.comparePoint(bracketPos) == 1) + range.end = bracketPos; + else + range.start = bracketPos; + + range.start.column++; + } else { + range = this.getCommentFoldRange(cursor.row, cursor.column) || range; + } + } else { + var folds = this.getFoldsInRange(range); + if (tryToUnfold && folds.length) { + this.expandFolds(folds); + return; + } else if (folds.length == 1 ) { + fold = folds[0]; + } + } + + if (!fold) + fold = this.getFoldAt(range.start.row, range.start.column); + + if (fold && fold.range.toString() == range.toString()) { + this.expandFold(fold); + return; + } + + var placeholder = "..."; + if (!range.isMultiLine()) { + placeholder = this.getTextRange(range); + if (placeholder.length < 4) + return; + placeholder = placeholder.trim().substring(0, 2) + ".."; + } + + this.addFold(placeholder, range); + }; + + this.getCommentFoldRange = function(row, column, dir) { + var iterator = new TokenIterator(this, row, column); + var token = iterator.getCurrentToken(); + var type = token.type; + if (token && /^comment|string/.test(type)) { + type = type.match(/comment|string/)[0]; + if (type == "comment") + type += "|doc-start"; + var re = new RegExp(type); + var range = new Range(); + if (dir != 1) { + do { + token = iterator.stepBackward(); + } while (token && re.test(token.type)); + iterator.stepForward(); + } + + range.start.row = iterator.getCurrentTokenRow(); + range.start.column = iterator.getCurrentTokenColumn() + 2; + + iterator = new TokenIterator(this, row, column); + + if (dir != -1) { + var lastRow = -1; + do { + token = iterator.stepForward(); + if (lastRow == -1) { + var state = this.getState(iterator.$row); + if (!re.test(state)) + lastRow = iterator.$row; + } else if (iterator.$row > lastRow) { + break; + } + } while (token && re.test(token.type)); + token = iterator.stepBackward(); + } else + token = iterator.getCurrentToken(); + + range.end.row = iterator.getCurrentTokenRow(); + range.end.column = iterator.getCurrentTokenColumn() + token.value.length - 2; + return range; + } + }; + + this.foldAll = function(startRow, endRow, depth) { + if (depth == undefined) + depth = 100000; // JSON.stringify doesn't hanle Infinity + var foldWidgets = this.foldWidgets; + if (!foldWidgets) + return; // mode doesn't support folding + endRow = endRow || this.getLength(); + startRow = startRow || 0; + for (var row = startRow; row < endRow; row++) { + if (foldWidgets[row] == null) + foldWidgets[row] = this.getFoldWidget(row); + if (foldWidgets[row] != "start") + continue; + + var range = this.getFoldWidgetRange(row); + if (range && range.isMultiLine() + && range.end.row <= endRow + && range.start.row >= startRow + ) { + row = range.end.row; + try { + var fold = this.addFold("...", range); + if (fold) + fold.collapseChildren = depth; + } catch(e) {} + } + } + }; + this.$foldStyles = { + "manual": 1, + "markbegin": 1, + "markbeginend": 1 + }; + this.$foldStyle = "markbegin"; + this.setFoldStyle = function(style) { + if (!this.$foldStyles[style]) + throw new Error("invalid fold style: " + style + "[" + Object.keys(this.$foldStyles).join(", ") + "]"); + + if (this.$foldStyle == style) + return; + + this.$foldStyle = style; + + if (style == "manual") + this.unfold(); + var mode = this.$foldMode; + this.$setFolding(null); + this.$setFolding(mode); + }; + + this.$setFolding = function(foldMode) { + if (this.$foldMode == foldMode) + return; + + this.$foldMode = foldMode; + + this.off('change', this.$updateFoldWidgets); + this.off('tokenizerUpdate', this.$tokenizerUpdateFoldWidgets); + this._signal("changeAnnotation"); + + if (!foldMode || this.$foldStyle == "manual") { + this.foldWidgets = null; + return; + } + + this.foldWidgets = []; + this.getFoldWidget = foldMode.getFoldWidget.bind(foldMode, this, this.$foldStyle); + this.getFoldWidgetRange = foldMode.getFoldWidgetRange.bind(foldMode, this, this.$foldStyle); + + this.$updateFoldWidgets = this.updateFoldWidgets.bind(this); + this.$tokenizerUpdateFoldWidgets = this.tokenizerUpdateFoldWidgets.bind(this); + this.on('change', this.$updateFoldWidgets); + this.on('tokenizerUpdate', this.$tokenizerUpdateFoldWidgets); + }; + + this.getParentFoldRangeData = function (row, ignoreCurrent) { + var fw = this.foldWidgets; + if (!fw || (ignoreCurrent && fw[row])) + return {}; + + var i = row - 1, firstRange; + while (i >= 0) { + var c = fw[i]; + if (c == null) + c = fw[i] = this.getFoldWidget(i); + + if (c == "start") { + var range = this.getFoldWidgetRange(i); + if (!firstRange) + firstRange = range; + if (range && range.end.row >= row) + break; + } + i--; + } + + return { + range: i !== -1 && range, + firstRange: firstRange + }; + }; + + this.onFoldWidgetClick = function(row, e) { + e = e.domEvent; + var options = { + children: e.shiftKey, + all: e.ctrlKey || e.metaKey, + siblings: e.altKey + }; + + var range = this.$toggleFoldWidget(row, options); + if (!range) { + var el = (e.target || e.srcElement); + if (el && /ace_fold-widget/.test(el.className)) + el.className += " ace_invalid"; + } + }; + + this.$toggleFoldWidget = function(row, options) { + if (!this.getFoldWidget) + return; + var type = this.getFoldWidget(row); + var line = this.getLine(row); + + var dir = type === "end" ? -1 : 1; + var fold = this.getFoldAt(row, dir === -1 ? 0 : line.length, dir); + + if (fold) { + if (options.children || options.all) + this.removeFold(fold); + else + this.expandFold(fold); + return fold; + } + + var range = this.getFoldWidgetRange(row, true); + if (range && !range.isMultiLine()) { + fold = this.getFoldAt(range.start.row, range.start.column, 1); + if (fold && range.isEqual(fold.range)) { + this.removeFold(fold); + return fold; + } + } + + if (options.siblings) { + var data = this.getParentFoldRangeData(row); + if (data.range) { + var startRow = data.range.start.row + 1; + var endRow = data.range.end.row; + } + this.foldAll(startRow, endRow, options.all ? 10000 : 0); + } else if (options.children) { + endRow = range ? range.end.row : this.getLength(); + this.foldAll(row + 1, endRow, options.all ? 10000 : 0); + } else if (range) { + if (options.all) + range.collapseChildren = 10000; + this.addFold("...", range); + } + + return range; + }; + + + + this.toggleFoldWidget = function(toggleParent) { + var row = this.selection.getCursor().row; + row = this.getRowFoldStart(row); + var range = this.$toggleFoldWidget(row, {}); + + if (range) + return; + var data = this.getParentFoldRangeData(row, true); + range = data.range || data.firstRange; + + if (range) { + row = range.start.row; + var fold = this.getFoldAt(row, this.getLine(row).length, 1); + + if (fold) { + this.removeFold(fold); + } else { + this.addFold("...", range); + } + } + }; + + this.updateFoldWidgets = function(delta) { + var firstRow = delta.start.row; + var len = delta.end.row - firstRow; + + if (len === 0) { + this.foldWidgets[firstRow] = null; + } else if (delta.action == 'remove') { + this.foldWidgets.splice(firstRow, len + 1, null); + } else { + var args = Array(len + 1); + args.unshift(firstRow, 1); + this.foldWidgets.splice.apply(this.foldWidgets, args); + } + }; + this.tokenizerUpdateFoldWidgets = function(e) { + var rows = e.data; + if (rows.first != rows.last) { + if (this.foldWidgets.length > rows.first) + this.foldWidgets.splice(rows.first, this.foldWidgets.length); + } + }; +} + +exports.Folding = Folding; + +}); + +ace.define("ace/edit_session/bracket_match",["require","exports","module","ace/token_iterator","ace/range"], function(acequire, exports, module) { +"use strict"; + +var TokenIterator = acequire("../token_iterator").TokenIterator; +var Range = acequire("../range").Range; + + +function BracketMatch() { + + this.findMatchingBracket = function(position, chr) { + if (position.column == 0) return null; + + var charBeforeCursor = chr || this.getLine(position.row).charAt(position.column-1); + if (charBeforeCursor == "") return null; + + var match = charBeforeCursor.match(/([\(\[\{])|([\)\]\}])/); + if (!match) + return null; + + if (match[1]) + return this.$findClosingBracket(match[1], position); + else + return this.$findOpeningBracket(match[2], position); + }; + + this.getBracketRange = function(pos) { + var line = this.getLine(pos.row); + var before = true, range; + + var chr = line.charAt(pos.column-1); + var match = chr && chr.match(/([\(\[\{])|([\)\]\}])/); + if (!match) { + chr = line.charAt(pos.column); + pos = {row: pos.row, column: pos.column + 1}; + match = chr && chr.match(/([\(\[\{])|([\)\]\}])/); + before = false; + } + if (!match) + return null; + + if (match[1]) { + var bracketPos = this.$findClosingBracket(match[1], pos); + if (!bracketPos) + return null; + range = Range.fromPoints(pos, bracketPos); + if (!before) { + range.end.column++; + range.start.column--; + } + range.cursor = range.end; + } else { + var bracketPos = this.$findOpeningBracket(match[2], pos); + if (!bracketPos) + return null; + range = Range.fromPoints(bracketPos, pos); + if (!before) { + range.start.column++; + range.end.column--; + } + range.cursor = range.start; + } + + return range; + }; + + this.$brackets = { + ")": "(", + "(": ")", + "]": "[", + "[": "]", + "{": "}", + "}": "{" + }; + + this.$findOpeningBracket = function(bracket, position, typeRe) { + var openBracket = this.$brackets[bracket]; + var depth = 1; + + var iterator = new TokenIterator(this, position.row, position.column); + var token = iterator.getCurrentToken(); + if (!token) + token = iterator.stepForward(); + if (!token) + return; + + if (!typeRe){ + typeRe = new RegExp( + "(\\.?" + + token.type.replace(".", "\\.").replace("rparen", ".paren") + .replace(/\b(?:end)\b/, "(?:start|begin|end)") + + ")+" + ); + } + var valueIndex = position.column - iterator.getCurrentTokenColumn() - 2; + var value = token.value; + + while (true) { + + while (valueIndex >= 0) { + var chr = value.charAt(valueIndex); + if (chr == openBracket) { + depth -= 1; + if (depth == 0) { + return {row: iterator.getCurrentTokenRow(), + column: valueIndex + iterator.getCurrentTokenColumn()}; + } + } + else if (chr == bracket) { + depth += 1; + } + valueIndex -= 1; + } + do { + token = iterator.stepBackward(); + } while (token && !typeRe.test(token.type)); + + if (token == null) + break; + + value = token.value; + valueIndex = value.length - 1; + } + + return null; + }; + + this.$findClosingBracket = function(bracket, position, typeRe) { + var closingBracket = this.$brackets[bracket]; + var depth = 1; + + var iterator = new TokenIterator(this, position.row, position.column); + var token = iterator.getCurrentToken(); + if (!token) + token = iterator.stepForward(); + if (!token) + return; + + if (!typeRe){ + typeRe = new RegExp( + "(\\.?" + + token.type.replace(".", "\\.").replace("lparen", ".paren") + .replace(/\b(?:start|begin)\b/, "(?:start|begin|end)") + + ")+" + ); + } + var valueIndex = position.column - iterator.getCurrentTokenColumn(); + + while (true) { + + var value = token.value; + var valueLength = value.length; + while (valueIndex < valueLength) { + var chr = value.charAt(valueIndex); + if (chr == closingBracket) { + depth -= 1; + if (depth == 0) { + return {row: iterator.getCurrentTokenRow(), + column: valueIndex + iterator.getCurrentTokenColumn()}; + } + } + else if (chr == bracket) { + depth += 1; + } + valueIndex += 1; + } + do { + token = iterator.stepForward(); + } while (token && !typeRe.test(token.type)); + + if (token == null) + break; + + valueIndex = 0; + } + + return null; + }; +} +exports.BracketMatch = BracketMatch; + +}); + +ace.define("ace/edit_session",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/bidihandler","ace/config","ace/lib/event_emitter","ace/selection","ace/mode/text","ace/range","ace/document","ace/background_tokenizer","ace/search_highlight","ace/edit_session/folding","ace/edit_session/bracket_match"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var lang = acequire("./lib/lang"); +var BidiHandler = acequire("./bidihandler").BidiHandler; +var config = acequire("./config"); +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var Selection = acequire("./selection").Selection; +var TextMode = acequire("./mode/text").Mode; +var Range = acequire("./range").Range; +var Document = acequire("./document").Document; +var BackgroundTokenizer = acequire("./background_tokenizer").BackgroundTokenizer; +var SearchHighlight = acequire("./search_highlight").SearchHighlight; + +var EditSession = function(text, mode) { + this.$breakpoints = []; + this.$decorations = []; + this.$frontMarkers = {}; + this.$backMarkers = {}; + this.$markerId = 1; + this.$undoSelect = true; + + this.$foldData = []; + this.id = "session" + (++EditSession.$uid); + this.$foldData.toString = function() { + return this.join("\n"); + }; + this.on("changeFold", this.onChangeFold.bind(this)); + this.$onChange = this.onChange.bind(this); + + if (typeof text != "object" || !text.getLine) + text = new Document(text); + + this.$bidiHandler = new BidiHandler(this); + this.setDocument(text); + this.selection = new Selection(this); + + config.resetOptions(this); + this.setMode(mode); + config._signal("session", this); +}; + + +EditSession.$uid = 0; + +(function() { + + oop.implement(this, EventEmitter); + this.setDocument = function(doc) { + if (this.doc) + this.doc.removeListener("change", this.$onChange); + + this.doc = doc; + doc.on("change", this.$onChange); + + if (this.bgTokenizer) + this.bgTokenizer.setDocument(this.getDocument()); + + this.resetCaches(); + }; + this.getDocument = function() { + return this.doc; + }; + this.$resetRowCache = function(docRow) { + if (!docRow) { + this.$docRowCache = []; + this.$screenRowCache = []; + return; + } + var l = this.$docRowCache.length; + var i = this.$getRowCacheIndex(this.$docRowCache, docRow) + 1; + if (l > i) { + this.$docRowCache.splice(i, l); + this.$screenRowCache.splice(i, l); + } + }; + + this.$getRowCacheIndex = function(cacheArray, val) { + var low = 0; + var hi = cacheArray.length - 1; + + while (low <= hi) { + var mid = (low + hi) >> 1; + var c = cacheArray[mid]; + + if (val > c) + low = mid + 1; + else if (val < c) + hi = mid - 1; + else + return mid; + } + + return low -1; + }; + + this.resetCaches = function() { + this.$modified = true; + this.$wrapData = []; + this.$rowLengthCache = []; + this.$resetRowCache(0); + if (this.bgTokenizer) + this.bgTokenizer.start(0); + }; + + this.onChangeFold = function(e) { + var fold = e.data; + this.$resetRowCache(fold.start.row); + }; + + this.onChange = function(delta) { + this.$modified = true; + this.$bidiHandler.onChange(delta); + this.$resetRowCache(delta.start.row); + + var removedFolds = this.$updateInternalDataOnChange(delta); + if (!this.$fromUndo && this.$undoManager && !delta.ignore) { + this.$deltasDoc.push(delta); + if (removedFolds && removedFolds.length != 0) { + this.$deltasFold.push({ + action: "removeFolds", + folds: removedFolds + }); + } + + this.$informUndoManager.schedule(); + } + + this.bgTokenizer && this.bgTokenizer.$updateOnChange(delta); + this._signal("change", delta); + }; + this.setValue = function(text) { + this.doc.setValue(text); + this.selection.moveTo(0, 0); + + this.$resetRowCache(0); + this.$deltas = []; + this.$deltasDoc = []; + this.$deltasFold = []; + this.setUndoManager(this.$undoManager); + this.getUndoManager().reset(); + }; + this.getValue = + this.toString = function() { + return this.doc.getValue(); + }; + this.getSelection = function() { + return this.selection; + }; + this.getState = function(row) { + return this.bgTokenizer.getState(row); + }; + this.getTokens = function(row) { + return this.bgTokenizer.getTokens(row); + }; + this.getTokenAt = function(row, column) { + var tokens = this.bgTokenizer.getTokens(row); + var token, c = 0; + if (column == null) { + var i = tokens.length - 1; + c = this.getLine(row).length; + } else { + for (var i = 0; i < tokens.length; i++) { + c += tokens[i].value.length; + if (c >= column) + break; + } + } + token = tokens[i]; + if (!token) + return null; + token.index = i; + token.start = c - token.value.length; + return token; + }; + this.setUndoManager = function(undoManager) { + this.$undoManager = undoManager; + this.$deltas = []; + this.$deltasDoc = []; + this.$deltasFold = []; + + if (this.$informUndoManager) + this.$informUndoManager.cancel(); + + if (undoManager) { + var self = this; + + this.$syncInformUndoManager = function() { + self.$informUndoManager.cancel(); + + if (self.$deltasFold.length) { + self.$deltas.push({ + group: "fold", + deltas: self.$deltasFold + }); + self.$deltasFold = []; + } + + if (self.$deltasDoc.length) { + self.$deltas.push({ + group: "doc", + deltas: self.$deltasDoc + }); + self.$deltasDoc = []; + } + + if (self.$deltas.length > 0) { + undoManager.execute({ + action: "aceupdate", + args: [self.$deltas, self], + merge: self.mergeUndoDeltas + }); + } + self.mergeUndoDeltas = false; + self.$deltas = []; + }; + this.$informUndoManager = lang.delayedCall(this.$syncInformUndoManager); + } + }; + this.markUndoGroup = function() { + if (this.$syncInformUndoManager) + this.$syncInformUndoManager(); + }; + + this.$defaultUndoManager = { + undo: function() {}, + redo: function() {}, + reset: function() {} + }; + this.getUndoManager = function() { + return this.$undoManager || this.$defaultUndoManager; + }; + this.getTabString = function() { + if (this.getUseSoftTabs()) { + return lang.stringRepeat(" ", this.getTabSize()); + } else { + return "\t"; + } + }; + this.setUseSoftTabs = function(val) { + this.setOption("useSoftTabs", val); + }; + this.getUseSoftTabs = function() { + return this.$useSoftTabs && !this.$mode.$indentWithTabs; + }; + this.setTabSize = function(tabSize) { + this.setOption("tabSize", tabSize); + }; + this.getTabSize = function() { + return this.$tabSize; + }; + this.isTabStop = function(position) { + return this.$useSoftTabs && (position.column % this.$tabSize === 0); + }; + this.setNavigateWithinSoftTabs = function (navigateWithinSoftTabs) { + this.setOption("navigateWithinSoftTabs", navigateWithinSoftTabs); + }; + this.getNavigateWithinSoftTabs = function() { + return this.$navigateWithinSoftTabs; + }; + + this.$overwrite = false; + this.setOverwrite = function(overwrite) { + this.setOption("overwrite", overwrite); + }; + this.getOverwrite = function() { + return this.$overwrite; + }; + this.toggleOverwrite = function() { + this.setOverwrite(!this.$overwrite); + }; + this.addGutterDecoration = function(row, className) { + if (!this.$decorations[row]) + this.$decorations[row] = ""; + this.$decorations[row] += " " + className; + this._signal("changeBreakpoint", {}); + }; + this.removeGutterDecoration = function(row, className) { + this.$decorations[row] = (this.$decorations[row] || "").replace(" " + className, ""); + this._signal("changeBreakpoint", {}); + }; + this.getBreakpoints = function() { + return this.$breakpoints; + }; + this.setBreakpoints = function(rows) { + this.$breakpoints = []; + for (var i=0; i 0) + inToken = !!line.charAt(column - 1).match(this.tokenRe); + + if (!inToken) + inToken = !!line.charAt(column).match(this.tokenRe); + + if (inToken) + var re = this.tokenRe; + else if (/^\s+$/.test(line.slice(column-1, column+1))) + var re = /\s/; + else + var re = this.nonTokenRe; + + var start = column; + if (start > 0) { + do { + start--; + } + while (start >= 0 && line.charAt(start).match(re)); + start++; + } + + var end = column; + while (end < line.length && line.charAt(end).match(re)) { + end++; + } + + return new Range(row, start, row, end); + }; + this.getAWordRange = function(row, column) { + var wordRange = this.getWordRange(row, column); + var line = this.getLine(wordRange.end.row); + + while (line.charAt(wordRange.end.column).match(/[ \t]/)) { + wordRange.end.column += 1; + } + return wordRange; + }; + this.setNewLineMode = function(newLineMode) { + this.doc.setNewLineMode(newLineMode); + }; + this.getNewLineMode = function() { + return this.doc.getNewLineMode(); + }; + this.setUseWorker = function(useWorker) { this.setOption("useWorker", useWorker); }; + this.getUseWorker = function() { return this.$useWorker; }; + this.onReloadTokenizer = function(e) { + var rows = e.data; + this.bgTokenizer.start(rows.first); + this._signal("tokenizerUpdate", e); + }; + + this.$modes = {}; + this.$mode = null; + this.$modeId = null; + this.setMode = function(mode, cb) { + if (mode && typeof mode === "object") { + if (mode.getTokenizer) + return this.$onChangeMode(mode); + var options = mode; + var path = options.path; + } else { + path = mode || "ace/mode/text"; + } + if (!this.$modes["ace/mode/text"]) + this.$modes["ace/mode/text"] = new TextMode(); + + if (this.$modes[path] && !options) { + this.$onChangeMode(this.$modes[path]); + cb && cb(); + return; + } + this.$modeId = path; + config.loadModule(["mode", path], function(m) { + if (this.$modeId !== path) + return cb && cb(); + if (this.$modes[path] && !options) { + this.$onChangeMode(this.$modes[path]); + } else if (m && m.Mode) { + m = new m.Mode(options); + if (!options) { + this.$modes[path] = m; + m.$id = path; + } + this.$onChangeMode(m); + } + cb && cb(); + }.bind(this)); + if (!this.$mode) + this.$onChangeMode(this.$modes["ace/mode/text"], true); + }; + + this.$onChangeMode = function(mode, $isPlaceholder) { + if (!$isPlaceholder) + this.$modeId = mode.$id; + if (this.$mode === mode) + return; + + this.$mode = mode; + + this.$stopWorker(); + + if (this.$useWorker) + this.$startWorker(); + + var tokenizer = mode.getTokenizer(); + + if(tokenizer.addEventListener !== undefined) { + var onReloadTokenizer = this.onReloadTokenizer.bind(this); + tokenizer.addEventListener("update", onReloadTokenizer); + } + + if (!this.bgTokenizer) { + this.bgTokenizer = new BackgroundTokenizer(tokenizer); + var _self = this; + this.bgTokenizer.addEventListener("update", function(e) { + _self._signal("tokenizerUpdate", e); + }); + } else { + this.bgTokenizer.setTokenizer(tokenizer); + } + + this.bgTokenizer.setDocument(this.getDocument()); + + this.tokenRe = mode.tokenRe; + this.nonTokenRe = mode.nonTokenRe; + + + if (!$isPlaceholder) { + if (mode.attachToSession) + mode.attachToSession(this); + this.$options.wrapMethod.set.call(this, this.$wrapMethod); + this.$setFolding(mode.foldingRules); + this.bgTokenizer.start(0); + this._emit("changeMode"); + } + }; + + this.$stopWorker = function() { + if (this.$worker) { + this.$worker.terminate(); + this.$worker = null; + } + }; + + this.$startWorker = function() { + try { + this.$worker = this.$mode.createWorker(this); + } catch (e) { + config.warn("Could not load worker", e); + this.$worker = null; + } + }; + this.getMode = function() { + return this.$mode; + }; + + this.$scrollTop = 0; + this.setScrollTop = function(scrollTop) { + if (this.$scrollTop === scrollTop || isNaN(scrollTop)) + return; + + this.$scrollTop = scrollTop; + this._signal("changeScrollTop", scrollTop); + }; + this.getScrollTop = function() { + return this.$scrollTop; + }; + + this.$scrollLeft = 0; + this.setScrollLeft = function(scrollLeft) { + if (this.$scrollLeft === scrollLeft || isNaN(scrollLeft)) + return; + + this.$scrollLeft = scrollLeft; + this._signal("changeScrollLeft", scrollLeft); + }; + this.getScrollLeft = function() { + return this.$scrollLeft; + }; + this.getScreenWidth = function() { + this.$computeWidth(); + if (this.lineWidgets) + return Math.max(this.getLineWidgetMaxWidth(), this.screenWidth); + return this.screenWidth; + }; + + this.getLineWidgetMaxWidth = function() { + if (this.lineWidgetsWidth != null) return this.lineWidgetsWidth; + var width = 0; + this.lineWidgets.forEach(function(w) { + if (w && w.screenWidth > width) + width = w.screenWidth; + }); + return this.lineWidgetWidth = width; + }; + + this.$computeWidth = function(force) { + if (this.$modified || force) { + this.$modified = false; + + if (this.$useWrapMode) + return this.screenWidth = this.$wrapLimit; + + var lines = this.doc.getAllLines(); + var cache = this.$rowLengthCache; + var longestScreenLine = 0; + var foldIndex = 0; + var foldLine = this.$foldData[foldIndex]; + var foldStart = foldLine ? foldLine.start.row : Infinity; + var len = lines.length; + + for (var i = 0; i < len; i++) { + if (i > foldStart) { + i = foldLine.end.row + 1; + if (i >= len) + break; + foldLine = this.$foldData[foldIndex++]; + foldStart = foldLine ? foldLine.start.row : Infinity; + } + + if (cache[i] == null) + cache[i] = this.$getStringScreenWidth(lines[i])[0]; + + if (cache[i] > longestScreenLine) + longestScreenLine = cache[i]; + } + this.screenWidth = longestScreenLine; + } + }; + this.getLine = function(row) { + return this.doc.getLine(row); + }; + this.getLines = function(firstRow, lastRow) { + return this.doc.getLines(firstRow, lastRow); + }; + this.getLength = function() { + return this.doc.getLength(); + }; + this.getTextRange = function(range) { + return this.doc.getTextRange(range || this.selection.getRange()); + }; + this.insert = function(position, text) { + return this.doc.insert(position, text); + }; + this.remove = function(range) { + return this.doc.remove(range); + }; + this.removeFullLines = function(firstRow, lastRow){ + return this.doc.removeFullLines(firstRow, lastRow); + }; + this.undoChanges = function(deltas, dontSelect) { + if (!deltas.length) + return; + + this.$fromUndo = true; + var lastUndoRange = null; + for (var i = deltas.length - 1; i != -1; i--) { + var delta = deltas[i]; + if (delta.group == "doc") { + this.doc.revertDeltas(delta.deltas); + lastUndoRange = + this.$getUndoSelection(delta.deltas, true, lastUndoRange); + } else { + delta.deltas.forEach(function(foldDelta) { + this.addFolds(foldDelta.folds); + }, this); + } + } + this.$fromUndo = false; + lastUndoRange && + this.$undoSelect && + !dontSelect && + this.selection.setSelectionRange(lastUndoRange); + return lastUndoRange; + }; + this.redoChanges = function(deltas, dontSelect) { + if (!deltas.length) + return; + + this.$fromUndo = true; + var lastUndoRange = null; + for (var i = 0; i < deltas.length; i++) { + var delta = deltas[i]; + if (delta.group == "doc") { + this.doc.applyDeltas(delta.deltas); + lastUndoRange = + this.$getUndoSelection(delta.deltas, false, lastUndoRange); + } + } + this.$fromUndo = false; + lastUndoRange && + this.$undoSelect && + !dontSelect && + this.selection.setSelectionRange(lastUndoRange); + return lastUndoRange; + }; + this.setUndoSelect = function(enable) { + this.$undoSelect = enable; + }; + + this.$getUndoSelection = function(deltas, isUndo, lastUndoRange) { + function isInsert(delta) { + return isUndo ? delta.action !== "insert" : delta.action === "insert"; + } + + var delta = deltas[0]; + var range, point; + var lastDeltaIsInsert = false; + if (isInsert(delta)) { + range = Range.fromPoints(delta.start, delta.end); + lastDeltaIsInsert = true; + } else { + range = Range.fromPoints(delta.start, delta.start); + lastDeltaIsInsert = false; + } + + for (var i = 1; i < deltas.length; i++) { + delta = deltas[i]; + if (isInsert(delta)) { + point = delta.start; + if (range.compare(point.row, point.column) == -1) { + range.setStart(point); + } + point = delta.end; + if (range.compare(point.row, point.column) == 1) { + range.setEnd(point); + } + lastDeltaIsInsert = true; + } else { + point = delta.start; + if (range.compare(point.row, point.column) == -1) { + range = Range.fromPoints(delta.start, delta.start); + } + lastDeltaIsInsert = false; + } + } + if (lastUndoRange != null) { + if (Range.comparePoints(lastUndoRange.start, range.start) === 0) { + lastUndoRange.start.column += range.end.column - range.start.column; + lastUndoRange.end.column += range.end.column - range.start.column; + } + + var cmp = lastUndoRange.compareRange(range); + if (cmp == 1) { + range.setStart(lastUndoRange.start); + } else if (cmp == -1) { + range.setEnd(lastUndoRange.end); + } + } + + return range; + }; + this.replace = function(range, text) { + return this.doc.replace(range, text); + }; + this.moveText = function(fromRange, toPosition, copy) { + var text = this.getTextRange(fromRange); + var folds = this.getFoldsInRange(fromRange); + + var toRange = Range.fromPoints(toPosition, toPosition); + if (!copy) { + this.remove(fromRange); + var rowDiff = fromRange.start.row - fromRange.end.row; + var collDiff = rowDiff ? -fromRange.end.column : fromRange.start.column - fromRange.end.column; + if (collDiff) { + if (toRange.start.row == fromRange.end.row && toRange.start.column > fromRange.end.column) + toRange.start.column += collDiff; + if (toRange.end.row == fromRange.end.row && toRange.end.column > fromRange.end.column) + toRange.end.column += collDiff; + } + if (rowDiff && toRange.start.row >= fromRange.end.row) { + toRange.start.row += rowDiff; + toRange.end.row += rowDiff; + } + } + + toRange.end = this.insert(toRange.start, text); + if (folds.length) { + var oldStart = fromRange.start; + var newStart = toRange.start; + var rowDiff = newStart.row - oldStart.row; + var collDiff = newStart.column - oldStart.column; + this.addFolds(folds.map(function(x) { + x = x.clone(); + if (x.start.row == oldStart.row) + x.start.column += collDiff; + if (x.end.row == oldStart.row) + x.end.column += collDiff; + x.start.row += rowDiff; + x.end.row += rowDiff; + return x; + })); + } + + return toRange; + }; + this.indentRows = function(startRow, endRow, indentString) { + indentString = indentString.replace(/\t/g, this.getTabString()); + for (var row=startRow; row<=endRow; row++) + this.doc.insertInLine({row: row, column: 0}, indentString); + }; + this.outdentRows = function (range) { + var rowRange = range.collapseRows(); + var deleteRange = new Range(0, 0, 0, 0); + var size = this.getTabSize(); + + for (var i = rowRange.start.row; i <= rowRange.end.row; ++i) { + var line = this.getLine(i); + + deleteRange.start.row = i; + deleteRange.end.row = i; + for (var j = 0; j < size; ++j) + if (line.charAt(j) != ' ') + break; + if (j < size && line.charAt(j) == '\t') { + deleteRange.start.column = j; + deleteRange.end.column = j + 1; + } else { + deleteRange.start.column = 0; + deleteRange.end.column = j; + } + this.remove(deleteRange); + } + }; + + this.$moveLines = function(firstRow, lastRow, dir) { + firstRow = this.getRowFoldStart(firstRow); + lastRow = this.getRowFoldEnd(lastRow); + if (dir < 0) { + var row = this.getRowFoldStart(firstRow + dir); + if (row < 0) return 0; + var diff = row-firstRow; + } else if (dir > 0) { + var row = this.getRowFoldEnd(lastRow + dir); + if (row > this.doc.getLength()-1) return 0; + var diff = row-lastRow; + } else { + firstRow = this.$clipRowToDocument(firstRow); + lastRow = this.$clipRowToDocument(lastRow); + var diff = lastRow - firstRow + 1; + } + + var range = new Range(firstRow, 0, lastRow, Number.MAX_VALUE); + var folds = this.getFoldsInRange(range).map(function(x){ + x = x.clone(); + x.start.row += diff; + x.end.row += diff; + return x; + }); + + var lines = dir == 0 + ? this.doc.getLines(firstRow, lastRow) + : this.doc.removeFullLines(firstRow, lastRow); + this.doc.insertFullLines(firstRow+diff, lines); + folds.length && this.addFolds(folds); + return diff; + }; + this.moveLinesUp = function(firstRow, lastRow) { + return this.$moveLines(firstRow, lastRow, -1); + }; + this.moveLinesDown = function(firstRow, lastRow) { + return this.$moveLines(firstRow, lastRow, 1); + }; + this.duplicateLines = function(firstRow, lastRow) { + return this.$moveLines(firstRow, lastRow, 0); + }; + + + this.$clipRowToDocument = function(row) { + return Math.max(0, Math.min(row, this.doc.getLength()-1)); + }; + + this.$clipColumnToRow = function(row, column) { + if (column < 0) + return 0; + return Math.min(this.doc.getLine(row).length, column); + }; + + + this.$clipPositionToDocument = function(row, column) { + column = Math.max(0, column); + + if (row < 0) { + row = 0; + column = 0; + } else { + var len = this.doc.getLength(); + if (row >= len) { + row = len - 1; + column = this.doc.getLine(len-1).length; + } else { + column = Math.min(this.doc.getLine(row).length, column); + } + } + + return { + row: row, + column: column + }; + }; + + this.$clipRangeToDocument = function(range) { + if (range.start.row < 0) { + range.start.row = 0; + range.start.column = 0; + } else { + range.start.column = this.$clipColumnToRow( + range.start.row, + range.start.column + ); + } + + var len = this.doc.getLength() - 1; + if (range.end.row > len) { + range.end.row = len; + range.end.column = this.doc.getLine(len).length; + } else { + range.end.column = this.$clipColumnToRow( + range.end.row, + range.end.column + ); + } + return range; + }; + this.$wrapLimit = 80; + this.$useWrapMode = false; + this.$wrapLimitRange = { + min : null, + max : null + }; + this.setUseWrapMode = function(useWrapMode) { + if (useWrapMode != this.$useWrapMode) { + this.$useWrapMode = useWrapMode; + this.$modified = true; + this.$resetRowCache(0); + if (useWrapMode) { + var len = this.getLength(); + this.$wrapData = Array(len); + this.$updateWrapData(0, len - 1); + } + + this._signal("changeWrapMode"); + } + }; + this.getUseWrapMode = function() { + return this.$useWrapMode; + }; + this.setWrapLimitRange = function(min, max) { + if (this.$wrapLimitRange.min !== min || this.$wrapLimitRange.max !== max) { + this.$wrapLimitRange = { min: min, max: max }; + this.$modified = true; + this.$bidiHandler.markAsDirty(); + if (this.$useWrapMode) + this._signal("changeWrapMode"); + } + }; + this.adjustWrapLimit = function(desiredLimit, $printMargin) { + var limits = this.$wrapLimitRange; + if (limits.max < 0) + limits = {min: $printMargin, max: $printMargin}; + var wrapLimit = this.$constrainWrapLimit(desiredLimit, limits.min, limits.max); + if (wrapLimit != this.$wrapLimit && wrapLimit > 1) { + this.$wrapLimit = wrapLimit; + this.$modified = true; + if (this.$useWrapMode) { + this.$updateWrapData(0, this.getLength() - 1); + this.$resetRowCache(0); + this._signal("changeWrapLimit"); + } + return true; + } + return false; + }; + + this.$constrainWrapLimit = function(wrapLimit, min, max) { + if (min) + wrapLimit = Math.max(min, wrapLimit); + + if (max) + wrapLimit = Math.min(max, wrapLimit); + + return wrapLimit; + }; + this.getWrapLimit = function() { + return this.$wrapLimit; + }; + this.setWrapLimit = function (limit) { + this.setWrapLimitRange(limit, limit); + }; + this.getWrapLimitRange = function() { + return { + min : this.$wrapLimitRange.min, + max : this.$wrapLimitRange.max + }; + }; + + this.$updateInternalDataOnChange = function(delta) { + var useWrapMode = this.$useWrapMode; + var action = delta.action; + var start = delta.start; + var end = delta.end; + var firstRow = start.row; + var lastRow = end.row; + var len = lastRow - firstRow; + var removedFolds = null; + + this.$updating = true; + if (len != 0) { + if (action === "remove") { + this[useWrapMode ? "$wrapData" : "$rowLengthCache"].splice(firstRow, len); + + var foldLines = this.$foldData; + removedFolds = this.getFoldsInRange(delta); + this.removeFolds(removedFolds); + + var foldLine = this.getFoldLine(end.row); + var idx = 0; + if (foldLine) { + foldLine.addRemoveChars(end.row, end.column, start.column - end.column); + foldLine.shiftRow(-len); + + var foldLineBefore = this.getFoldLine(firstRow); + if (foldLineBefore && foldLineBefore !== foldLine) { + foldLineBefore.merge(foldLine); + foldLine = foldLineBefore; + } + idx = foldLines.indexOf(foldLine) + 1; + } + + for (idx; idx < foldLines.length; idx++) { + var foldLine = foldLines[idx]; + if (foldLine.start.row >= end.row) { + foldLine.shiftRow(-len); + } + } + + lastRow = firstRow; + } else { + var args = Array(len); + args.unshift(firstRow, 0); + var arr = useWrapMode ? this.$wrapData : this.$rowLengthCache; + arr.splice.apply(arr, args); + var foldLines = this.$foldData; + var foldLine = this.getFoldLine(firstRow); + var idx = 0; + if (foldLine) { + var cmp = foldLine.range.compareInside(start.row, start.column); + if (cmp == 0) { + foldLine = foldLine.split(start.row, start.column); + if (foldLine) { + foldLine.shiftRow(len); + foldLine.addRemoveChars(lastRow, 0, end.column - start.column); + } + } else + if (cmp == -1) { + foldLine.addRemoveChars(firstRow, 0, end.column - start.column); + foldLine.shiftRow(len); + } + idx = foldLines.indexOf(foldLine) + 1; + } + + for (idx; idx < foldLines.length; idx++) { + var foldLine = foldLines[idx]; + if (foldLine.start.row >= firstRow) { + foldLine.shiftRow(len); + } + } + } + } else { + len = Math.abs(delta.start.column - delta.end.column); + if (action === "remove") { + removedFolds = this.getFoldsInRange(delta); + this.removeFolds(removedFolds); + + len = -len; + } + var foldLine = this.getFoldLine(firstRow); + if (foldLine) { + foldLine.addRemoveChars(firstRow, start.column, len); + } + } + + if (useWrapMode && this.$wrapData.length != this.doc.getLength()) { + console.error("doc.getLength() and $wrapData.length have to be the same!"); + } + this.$updating = false; + + if (useWrapMode) + this.$updateWrapData(firstRow, lastRow); + else + this.$updateRowLengthCache(firstRow, lastRow); + + return removedFolds; + }; + + this.$updateRowLengthCache = function(firstRow, lastRow, b) { + this.$rowLengthCache[firstRow] = null; + this.$rowLengthCache[lastRow] = null; + }; + + this.$updateWrapData = function(firstRow, lastRow) { + var lines = this.doc.getAllLines(); + var tabSize = this.getTabSize(); + var wrapData = this.$wrapData; + var wrapLimit = this.$wrapLimit; + var tokens; + var foldLine; + + var row = firstRow; + lastRow = Math.min(lastRow, lines.length - 1); + while (row <= lastRow) { + foldLine = this.getFoldLine(row, foldLine); + if (!foldLine) { + tokens = this.$getDisplayTokens(lines[row]); + wrapData[row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize); + row ++; + } else { + tokens = []; + foldLine.walk(function(placeholder, row, column, lastColumn) { + var walkTokens; + if (placeholder != null) { + walkTokens = this.$getDisplayTokens( + placeholder, tokens.length); + walkTokens[0] = PLACEHOLDER_START; + for (var i = 1; i < walkTokens.length; i++) { + walkTokens[i] = PLACEHOLDER_BODY; + } + } else { + walkTokens = this.$getDisplayTokens( + lines[row].substring(lastColumn, column), + tokens.length); + } + tokens = tokens.concat(walkTokens); + }.bind(this), + foldLine.end.row, + lines[foldLine.end.row].length + 1 + ); + + wrapData[foldLine.start.row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize); + row = foldLine.end.row + 1; + } + } + }; + var CHAR = 1, + CHAR_EXT = 2, + PLACEHOLDER_START = 3, + PLACEHOLDER_BODY = 4, + PUNCTUATION = 9, + SPACE = 10, + TAB = 11, + TAB_SPACE = 12; + + + this.$computeWrapSplits = function(tokens, wrapLimit, tabSize) { + if (tokens.length == 0) { + return []; + } + + var splits = []; + var displayLength = tokens.length; + var lastSplit = 0, lastDocSplit = 0; + + var isCode = this.$wrapAsCode; + + var indentedSoftWrap = this.$indentedSoftWrap; + var maxIndent = wrapLimit <= Math.max(2 * tabSize, 8) + || indentedSoftWrap === false ? 0 : Math.floor(wrapLimit / 2); + + function getWrapIndent() { + var indentation = 0; + if (maxIndent === 0) + return indentation; + if (indentedSoftWrap) { + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + if (token == SPACE) + indentation += 1; + else if (token == TAB) + indentation += tabSize; + else if (token == TAB_SPACE) + continue; + else + break; + } + } + if (isCode && indentedSoftWrap !== false) + indentation += tabSize; + return Math.min(indentation, maxIndent); + } + function addSplit(screenPos) { + var displayed = tokens.slice(lastSplit, screenPos); + var len = displayed.length; + displayed.join("") + .replace(/12/g, function() { + len -= 1; + }) + .replace(/2/g, function() { + len -= 1; + }); + + if (!splits.length) { + indent = getWrapIndent(); + splits.indent = indent; + } + lastDocSplit += len; + splits.push(lastDocSplit); + lastSplit = screenPos; + } + var indent = 0; + while (displayLength - lastSplit > wrapLimit - indent) { + var split = lastSplit + wrapLimit - indent; + if (tokens[split - 1] >= SPACE && tokens[split] >= SPACE) { + addSplit(split); + continue; + } + if (tokens[split] == PLACEHOLDER_START || tokens[split] == PLACEHOLDER_BODY) { + for (split; split != lastSplit - 1; split--) { + if (tokens[split] == PLACEHOLDER_START) { + break; + } + } + if (split > lastSplit) { + addSplit(split); + continue; + } + split = lastSplit + wrapLimit; + for (split; split < tokens.length; split++) { + if (tokens[split] != PLACEHOLDER_BODY) { + break; + } + } + if (split == tokens.length) { + break; // Breaks the while-loop. + } + addSplit(split); + continue; + } + var minSplit = Math.max(split - (wrapLimit -(wrapLimit>>2)), lastSplit - 1); + while (split > minSplit && tokens[split] < PLACEHOLDER_START) { + split --; + } + if (isCode) { + while (split > minSplit && tokens[split] < PLACEHOLDER_START) { + split --; + } + while (split > minSplit && tokens[split] == PUNCTUATION) { + split --; + } + } else { + while (split > minSplit && tokens[split] < SPACE) { + split --; + } + } + if (split > minSplit) { + addSplit(++split); + continue; + } + split = lastSplit + wrapLimit; + if (tokens[split] == CHAR_EXT) + split--; + addSplit(split - indent); + } + return splits; + }; + this.$getDisplayTokens = function(str, offset) { + var arr = []; + var tabSize; + offset = offset || 0; + + for (var i = 0; i < str.length; i++) { + var c = str.charCodeAt(i); + if (c == 9) { + tabSize = this.getScreenTabSize(arr.length + offset); + arr.push(TAB); + for (var n = 1; n < tabSize; n++) { + arr.push(TAB_SPACE); + } + } + else if (c == 32) { + arr.push(SPACE); + } else if((c > 39 && c < 48) || (c > 57 && c < 64)) { + arr.push(PUNCTUATION); + } + else if (c >= 0x1100 && isFullWidth(c)) { + arr.push(CHAR, CHAR_EXT); + } else { + arr.push(CHAR); + } + } + return arr; + }; + this.$getStringScreenWidth = function(str, maxScreenColumn, screenColumn) { + if (maxScreenColumn == 0) + return [0, 0]; + if (maxScreenColumn == null) + maxScreenColumn = Infinity; + screenColumn = screenColumn || 0; + + var c, column; + for (column = 0; column < str.length; column++) { + c = str.charCodeAt(column); + if (c == 9) { + screenColumn += this.getScreenTabSize(screenColumn); + } + else if (c >= 0x1100 && isFullWidth(c)) { + screenColumn += 2; + } else { + screenColumn += 1; + } + if (screenColumn > maxScreenColumn) { + break; + } + } + + return [screenColumn, column]; + }; + + this.lineWidgets = null; + this.getRowLength = function(row) { + if (this.lineWidgets) + var h = this.lineWidgets[row] && this.lineWidgets[row].rowCount || 0; + else + h = 0; + if (!this.$useWrapMode || !this.$wrapData[row]) { + return 1 + h; + } else { + return this.$wrapData[row].length + 1 + h; + } + }; + this.getRowLineCount = function(row) { + if (!this.$useWrapMode || !this.$wrapData[row]) { + return 1; + } else { + return this.$wrapData[row].length + 1; + } + }; + + this.getRowWrapIndent = function(screenRow) { + if (this.$useWrapMode) { + var pos = this.screenToDocumentPosition(screenRow, Number.MAX_VALUE); + var splits = this.$wrapData[pos.row]; + return splits.length && splits[0] < pos.column ? splits.indent : 0; + } else { + return 0; + } + }; + this.getScreenLastRowColumn = function(screenRow) { + var pos = this.screenToDocumentPosition(screenRow, Number.MAX_VALUE); + return this.documentToScreenColumn(pos.row, pos.column); + }; + this.getDocumentLastRowColumn = function(docRow, docColumn) { + var screenRow = this.documentToScreenRow(docRow, docColumn); + return this.getScreenLastRowColumn(screenRow); + }; + this.getDocumentLastRowColumnPosition = function(docRow, docColumn) { + var screenRow = this.documentToScreenRow(docRow, docColumn); + return this.screenToDocumentPosition(screenRow, Number.MAX_VALUE / 10); + }; + this.getRowSplitData = function(row) { + if (!this.$useWrapMode) { + return undefined; + } else { + return this.$wrapData[row]; + } + }; + this.getScreenTabSize = function(screenColumn) { + return this.$tabSize - screenColumn % this.$tabSize; + }; + + + this.screenToDocumentRow = function(screenRow, screenColumn) { + return this.screenToDocumentPosition(screenRow, screenColumn).row; + }; + + + this.screenToDocumentColumn = function(screenRow, screenColumn) { + return this.screenToDocumentPosition(screenRow, screenColumn).column; + }; + this.screenToDocumentPosition = function(screenRow, screenColumn, offsetX) { + if (screenRow < 0) + return {row: 0, column: 0}; + + var line; + var docRow = 0; + var docColumn = 0; + var column; + var row = 0; + var rowLength = 0; + + var rowCache = this.$screenRowCache; + var i = this.$getRowCacheIndex(rowCache, screenRow); + var l = rowCache.length; + if (l && i >= 0) { + var row = rowCache[i]; + var docRow = this.$docRowCache[i]; + var doCache = screenRow > rowCache[l - 1]; + } else { + var doCache = !l; + } + + var maxRow = this.getLength() - 1; + var foldLine = this.getNextFoldLine(docRow); + var foldStart = foldLine ? foldLine.start.row : Infinity; + + while (row <= screenRow) { + rowLength = this.getRowLength(docRow); + if (row + rowLength > screenRow || docRow >= maxRow) { + break; + } else { + row += rowLength; + docRow++; + if (docRow > foldStart) { + docRow = foldLine.end.row+1; + foldLine = this.getNextFoldLine(docRow, foldLine); + foldStart = foldLine ? foldLine.start.row : Infinity; + } + } + + if (doCache) { + this.$docRowCache.push(docRow); + this.$screenRowCache.push(row); + } + } + + if (foldLine && foldLine.start.row <= docRow) { + line = this.getFoldDisplayLine(foldLine); + docRow = foldLine.start.row; + } else if (row + rowLength <= screenRow || docRow > maxRow) { + return { + row: maxRow, + column: this.getLine(maxRow).length + }; + } else { + line = this.getLine(docRow); + foldLine = null; + } + var wrapIndent = 0, splitIndex = Math.floor(screenRow - row); + if (this.$useWrapMode) { + var splits = this.$wrapData[docRow]; + if (splits) { + column = splits[splitIndex]; + if(splitIndex > 0 && splits.length) { + wrapIndent = splits.indent; + docColumn = splits[splitIndex - 1] || splits[splits.length - 1]; + line = line.substring(docColumn); + } + } + } + + if (offsetX !== undefined && this.$bidiHandler.isBidiRow(row + splitIndex, docRow, splitIndex)) + screenColumn = this.$bidiHandler.offsetToCol(offsetX); + + docColumn += this.$getStringScreenWidth(line, screenColumn - wrapIndent)[1]; + if (this.$useWrapMode && docColumn >= column) + docColumn = column - 1; + + if (foldLine) + return foldLine.idxToPosition(docColumn); + + return {row: docRow, column: docColumn}; + }; + this.documentToScreenPosition = function(docRow, docColumn) { + if (typeof docColumn === "undefined") + var pos = this.$clipPositionToDocument(docRow.row, docRow.column); + else + pos = this.$clipPositionToDocument(docRow, docColumn); + + docRow = pos.row; + docColumn = pos.column; + + var screenRow = 0; + var foldStartRow = null; + var fold = null; + fold = this.getFoldAt(docRow, docColumn, 1); + if (fold) { + docRow = fold.start.row; + docColumn = fold.start.column; + } + + var rowEnd, row = 0; + + + var rowCache = this.$docRowCache; + var i = this.$getRowCacheIndex(rowCache, docRow); + var l = rowCache.length; + if (l && i >= 0) { + var row = rowCache[i]; + var screenRow = this.$screenRowCache[i]; + var doCache = docRow > rowCache[l - 1]; + } else { + var doCache = !l; + } + + var foldLine = this.getNextFoldLine(row); + var foldStart = foldLine ?foldLine.start.row :Infinity; + + while (row < docRow) { + if (row >= foldStart) { + rowEnd = foldLine.end.row + 1; + if (rowEnd > docRow) + break; + foldLine = this.getNextFoldLine(rowEnd, foldLine); + foldStart = foldLine ?foldLine.start.row :Infinity; + } + else { + rowEnd = row + 1; + } + + screenRow += this.getRowLength(row); + row = rowEnd; + + if (doCache) { + this.$docRowCache.push(row); + this.$screenRowCache.push(screenRow); + } + } + var textLine = ""; + if (foldLine && row >= foldStart) { + textLine = this.getFoldDisplayLine(foldLine, docRow, docColumn); + foldStartRow = foldLine.start.row; + } else { + textLine = this.getLine(docRow).substring(0, docColumn); + foldStartRow = docRow; + } + var wrapIndent = 0; + if (this.$useWrapMode) { + var wrapRow = this.$wrapData[foldStartRow]; + if (wrapRow) { + var screenRowOffset = 0; + while (textLine.length >= wrapRow[screenRowOffset]) { + screenRow ++; + screenRowOffset++; + } + textLine = textLine.substring( + wrapRow[screenRowOffset - 1] || 0, textLine.length + ); + wrapIndent = screenRowOffset > 0 ? wrapRow.indent : 0; + } + } + + return { + row: screenRow, + column: wrapIndent + this.$getStringScreenWidth(textLine)[0] + }; + }; + this.documentToScreenColumn = function(row, docColumn) { + return this.documentToScreenPosition(row, docColumn).column; + }; + this.documentToScreenRow = function(docRow, docColumn) { + return this.documentToScreenPosition(docRow, docColumn).row; + }; + this.getScreenLength = function() { + var screenRows = 0; + var fold = null; + if (!this.$useWrapMode) { + screenRows = this.getLength(); + var foldData = this.$foldData; + for (var i = 0; i < foldData.length; i++) { + fold = foldData[i]; + screenRows -= fold.end.row - fold.start.row; + } + } else { + var lastRow = this.$wrapData.length; + var row = 0, i = 0; + var fold = this.$foldData[i++]; + var foldStart = fold ? fold.start.row :Infinity; + + while (row < lastRow) { + var splits = this.$wrapData[row]; + screenRows += splits ? splits.length + 1 : 1; + row ++; + if (row > foldStart) { + row = fold.end.row+1; + fold = this.$foldData[i++]; + foldStart = fold ?fold.start.row :Infinity; + } + } + } + if (this.lineWidgets) + screenRows += this.$getWidgetScreenLength(); + + return screenRows; + }; + this.$setFontMetrics = function(fm) { + if (!this.$enableVarChar) return; + this.$getStringScreenWidth = function(str, maxScreenColumn, screenColumn) { + if (maxScreenColumn === 0) + return [0, 0]; + if (!maxScreenColumn) + maxScreenColumn = Infinity; + screenColumn = screenColumn || 0; + + var c, column; + for (column = 0; column < str.length; column++) { + c = str.charAt(column); + if (c === "\t") { + screenColumn += this.getScreenTabSize(screenColumn); + } else { + screenColumn += fm.getCharacterWidth(c); + } + if (screenColumn > maxScreenColumn) { + break; + } + } + + return [screenColumn, column]; + }; + }; + + this.destroy = function() { + if (this.bgTokenizer) { + this.bgTokenizer.setDocument(null); + this.bgTokenizer = null; + } + this.$stopWorker(); + }; + + this.isFullWidth = isFullWidth; + function isFullWidth(c) { + if (c < 0x1100) + return false; + return c >= 0x1100 && c <= 0x115F || + c >= 0x11A3 && c <= 0x11A7 || + c >= 0x11FA && c <= 0x11FF || + c >= 0x2329 && c <= 0x232A || + c >= 0x2E80 && c <= 0x2E99 || + c >= 0x2E9B && c <= 0x2EF3 || + c >= 0x2F00 && c <= 0x2FD5 || + c >= 0x2FF0 && c <= 0x2FFB || + c >= 0x3000 && c <= 0x303E || + c >= 0x3041 && c <= 0x3096 || + c >= 0x3099 && c <= 0x30FF || + c >= 0x3105 && c <= 0x312D || + c >= 0x3131 && c <= 0x318E || + c >= 0x3190 && c <= 0x31BA || + c >= 0x31C0 && c <= 0x31E3 || + c >= 0x31F0 && c <= 0x321E || + c >= 0x3220 && c <= 0x3247 || + c >= 0x3250 && c <= 0x32FE || + c >= 0x3300 && c <= 0x4DBF || + c >= 0x4E00 && c <= 0xA48C || + c >= 0xA490 && c <= 0xA4C6 || + c >= 0xA960 && c <= 0xA97C || + c >= 0xAC00 && c <= 0xD7A3 || + c >= 0xD7B0 && c <= 0xD7C6 || + c >= 0xD7CB && c <= 0xD7FB || + c >= 0xF900 && c <= 0xFAFF || + c >= 0xFE10 && c <= 0xFE19 || + c >= 0xFE30 && c <= 0xFE52 || + c >= 0xFE54 && c <= 0xFE66 || + c >= 0xFE68 && c <= 0xFE6B || + c >= 0xFF01 && c <= 0xFF60 || + c >= 0xFFE0 && c <= 0xFFE6; + } + +}).call(EditSession.prototype); + +acequire("./edit_session/folding").Folding.call(EditSession.prototype); +acequire("./edit_session/bracket_match").BracketMatch.call(EditSession.prototype); + + +config.defineOptions(EditSession.prototype, "session", { + wrap: { + set: function(value) { + if (!value || value == "off") + value = false; + else if (value == "free") + value = true; + else if (value == "printMargin") + value = -1; + else if (typeof value == "string") + value = parseInt(value, 10) || false; + + if (this.$wrap == value) + return; + this.$wrap = value; + if (!value) { + this.setUseWrapMode(false); + } else { + var col = typeof value == "number" ? value : null; + this.setWrapLimitRange(col, col); + this.setUseWrapMode(true); + } + }, + get: function() { + if (this.getUseWrapMode()) { + if (this.$wrap == -1) + return "printMargin"; + if (!this.getWrapLimitRange().min) + return "free"; + return this.$wrap; + } + return "off"; + }, + handlesSet: true + }, + wrapMethod: { + set: function(val) { + val = val == "auto" + ? this.$mode.type != "text" + : val != "text"; + if (val != this.$wrapAsCode) { + this.$wrapAsCode = val; + if (this.$useWrapMode) { + this.$modified = true; + this.$resetRowCache(0); + this.$updateWrapData(0, this.getLength() - 1); + } + } + }, + initialValue: "auto" + }, + indentedSoftWrap: { initialValue: true }, + firstLineNumber: { + set: function() {this._signal("changeBreakpoint");}, + initialValue: 1 + }, + useWorker: { + set: function(useWorker) { + this.$useWorker = useWorker; + + this.$stopWorker(); + if (useWorker) + this.$startWorker(); + }, + initialValue: true + }, + useSoftTabs: {initialValue: true}, + tabSize: { + set: function(tabSize) { + if (isNaN(tabSize) || this.$tabSize === tabSize) return; + + this.$modified = true; + this.$rowLengthCache = []; + this.$tabSize = tabSize; + this._signal("changeTabSize"); + }, + initialValue: 4, + handlesSet: true + }, + navigateWithinSoftTabs: {initialValue: false}, + overwrite: { + set: function(val) {this._signal("changeOverwrite");}, + initialValue: false + }, + newLineMode: { + set: function(val) {this.doc.setNewLineMode(val);}, + get: function() {return this.doc.getNewLineMode();}, + handlesSet: true + }, + mode: { + set: function(val) { this.setMode(val); }, + get: function() { return this.$modeId; } + } +}); + +exports.EditSession = EditSession; +}); + +ace.define("ace/search",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"], function(acequire, exports, module) { +"use strict"; + +var lang = acequire("./lib/lang"); +var oop = acequire("./lib/oop"); +var Range = acequire("./range").Range; + +var Search = function() { + this.$options = {}; +}; + +(function() { + this.set = function(options) { + oop.mixin(this.$options, options); + return this; + }; + this.getOptions = function() { + return lang.copyObject(this.$options); + }; + this.setOptions = function(options) { + this.$options = options; + }; + this.find = function(session) { + var options = this.$options; + var iterator = this.$matchIterator(session, options); + if (!iterator) + return false; + + var firstRange = null; + iterator.forEach(function(sr, sc, er, ec) { + firstRange = new Range(sr, sc, er, ec); + if (sc == ec && options.start && options.start.start + && options.skipCurrent != false && firstRange.isEqual(options.start) + ) { + firstRange = null; + return false; + } + + return true; + }); + + return firstRange; + }; + this.findAll = function(session) { + var options = this.$options; + if (!options.needle) + return []; + this.$assembleRegExp(options); + + var range = options.range; + var lines = range + ? session.getLines(range.start.row, range.end.row) + : session.doc.getAllLines(); + + var ranges = []; + var re = options.re; + if (options.$isMultiLine) { + var len = re.length; + var maxRow = lines.length - len; + var prevRange; + outer: for (var row = re.offset || 0; row <= maxRow; row++) { + for (var j = 0; j < len; j++) + if (lines[row + j].search(re[j]) == -1) + continue outer; + + var startLine = lines[row]; + var line = lines[row + len - 1]; + var startIndex = startLine.length - startLine.match(re[0])[0].length; + var endIndex = line.match(re[len - 1])[0].length; + + if (prevRange && prevRange.end.row === row && + prevRange.end.column > startIndex + ) { + continue; + } + ranges.push(prevRange = new Range( + row, startIndex, row + len - 1, endIndex + )); + if (len > 2) + row = row + len - 2; + } + } else { + for (var i = 0; i < lines.length; i++) { + var matches = lang.getMatchOffsets(lines[i], re); + for (var j = 0; j < matches.length; j++) { + var match = matches[j]; + ranges.push(new Range(i, match.offset, i, match.offset + match.length)); + } + } + } + + if (range) { + var startColumn = range.start.column; + var endColumn = range.start.column; + var i = 0, j = ranges.length - 1; + while (i < j && ranges[i].start.column < startColumn && ranges[i].start.row == range.start.row) + i++; + + while (i < j && ranges[j].end.column > endColumn && ranges[j].end.row == range.end.row) + j--; + + ranges = ranges.slice(i, j + 1); + for (i = 0, j = ranges.length; i < j; i++) { + ranges[i].start.row += range.start.row; + ranges[i].end.row += range.start.row; + } + } + + return ranges; + }; + this.replace = function(input, replacement) { + var options = this.$options; + + var re = this.$assembleRegExp(options); + if (options.$isMultiLine) + return replacement; + + if (!re) + return; + + var match = re.exec(input); + if (!match || match[0].length != input.length) + return null; + + replacement = input.replace(re, replacement); + if (options.preserveCase) { + replacement = replacement.split(""); + for (var i = Math.min(input.length, input.length); i--; ) { + var ch = input[i]; + if (ch && ch.toLowerCase() != ch) + replacement[i] = replacement[i].toUpperCase(); + else + replacement[i] = replacement[i].toLowerCase(); + } + replacement = replacement.join(""); + } + + return replacement; + }; + + this.$assembleRegExp = function(options, $disableFakeMultiline) { + if (options.needle instanceof RegExp) + return options.re = options.needle; + + var needle = options.needle; + + if (!options.needle) + return options.re = false; + + if (!options.regExp) + needle = lang.escapeRegExp(needle); + + if (options.wholeWord) + needle = addWordBoundary(needle, options); + + var modifier = options.caseSensitive ? "gm" : "gmi"; + + options.$isMultiLine = !$disableFakeMultiline && /[\n\r]/.test(needle); + if (options.$isMultiLine) + return options.re = this.$assembleMultilineRegExp(needle, modifier); + + try { + var re = new RegExp(needle, modifier); + } catch(e) { + re = false; + } + return options.re = re; + }; + + this.$assembleMultilineRegExp = function(needle, modifier) { + var parts = needle.replace(/\r\n|\r|\n/g, "$\n^").split("\n"); + var re = []; + for (var i = 0; i < parts.length; i++) try { + re.push(new RegExp(parts[i], modifier)); + } catch(e) { + return false; + } + return re; + }; + + this.$matchIterator = function(session, options) { + var re = this.$assembleRegExp(options); + if (!re) + return false; + var backwards = options.backwards == true; + var skipCurrent = options.skipCurrent != false; + + var range = options.range; + var start = options.start; + if (!start) + start = range ? range[backwards ? "end" : "start"] : session.selection.getRange(); + + if (start.start) + start = start[skipCurrent != backwards ? "end" : "start"]; + + var firstRow = range ? range.start.row : 0; + var lastRow = range ? range.end.row : session.getLength() - 1; + + if (backwards) { + var forEach = function(callback) { + var row = start.row; + if (forEachInLine(row, start.column, callback)) + return; + for (row--; row >= firstRow; row--) + if (forEachInLine(row, Number.MAX_VALUE, callback)) + return; + if (options.wrap == false) + return; + for (row = lastRow, firstRow = start.row; row >= firstRow; row--) + if (forEachInLine(row, Number.MAX_VALUE, callback)) + return; + }; + } + else { + var forEach = function(callback) { + var row = start.row; + if (forEachInLine(row, start.column, callback)) + return; + for (row = row + 1; row <= lastRow; row++) + if (forEachInLine(row, 0, callback)) + return; + if (options.wrap == false) + return; + for (row = firstRow, lastRow = start.row; row <= lastRow; row++) + if (forEachInLine(row, 0, callback)) + return; + }; + } + + if (options.$isMultiLine) { + var len = re.length; + var forEachInLine = function(row, offset, callback) { + var startRow = backwards ? row - len + 1 : row; + if (startRow < 0) return; + var line = session.getLine(startRow); + var startIndex = line.search(re[0]); + if (!backwards && startIndex < offset || startIndex === -1) return; + for (var i = 1; i < len; i++) { + line = session.getLine(startRow + i); + if (line.search(re[i]) == -1) + return; + } + var endIndex = line.match(re[len - 1])[0].length; + if (backwards && endIndex > offset) return; + if (callback(startRow, startIndex, startRow + len - 1, endIndex)) + return true; + }; + } + else if (backwards) { + var forEachInLine = function(row, endIndex, callback) { + var line = session.getLine(row); + var matches = []; + var m, last = 0; + re.lastIndex = 0; + while((m = re.exec(line))) { + var length = m[0].length; + last = m.index; + if (!length) { + if (last >= line.length) break; + re.lastIndex = last += 1; + } + if (m.index + length > endIndex) + break; + matches.push(m.index, length); + } + for (var i = matches.length - 1; i >= 0; i -= 2) { + var column = matches[i - 1]; + var length = matches[i]; + if (callback(row, column, row, column + length)) + return true; + } + }; + } + else { + var forEachInLine = function(row, startIndex, callback) { + var line = session.getLine(row); + var m; + var last = startIndex; + re.lastIndex = startIndex; + while((m = re.exec(line))) { + var length = m[0].length; + last = m.index; + if (callback(row, last, row,last + length)) + return true; + if (!length) { + re.lastIndex = last += 1; + if (last >= line.length) return false; + } + } + }; + } + return {forEach: forEach}; + }; + +}).call(Search.prototype); + +function addWordBoundary(needle, options) { + function wordBoundary(c) { + if (/\w/.test(c) || options.regExp) return "\\b"; + return ""; + } + return wordBoundary(needle[0]) + needle + + wordBoundary(needle[needle.length - 1]); +} + +exports.Search = Search; +}); + +ace.define("ace/keyboard/hash_handler",["require","exports","module","ace/lib/keys","ace/lib/useragent"], function(acequire, exports, module) { +"use strict"; + +var keyUtil = acequire("../lib/keys"); +var useragent = acequire("../lib/useragent"); +var KEY_MODS = keyUtil.KEY_MODS; + +function HashHandler(config, platform) { + this.platform = platform || (useragent.isMac ? "mac" : "win"); + this.commands = {}; + this.commandKeyBinding = {}; + this.addCommands(config); + this.$singleCommand = true; +} + +function MultiHashHandler(config, platform) { + HashHandler.call(this, config, platform); + this.$singleCommand = false; +} + +MultiHashHandler.prototype = HashHandler.prototype; + +(function() { + + + this.addCommand = function(command) { + if (this.commands[command.name]) + this.removeCommand(command); + + this.commands[command.name] = command; + + if (command.bindKey) + this._buildKeyHash(command); + }; + + this.removeCommand = function(command, keepCommand) { + var name = command && (typeof command === 'string' ? command : command.name); + command = this.commands[name]; + if (!keepCommand) + delete this.commands[name]; + var ckb = this.commandKeyBinding; + for (var keyId in ckb) { + var cmdGroup = ckb[keyId]; + if (cmdGroup == command) { + delete ckb[keyId]; + } else if (Array.isArray(cmdGroup)) { + var i = cmdGroup.indexOf(command); + if (i != -1) { + cmdGroup.splice(i, 1); + if (cmdGroup.length == 1) + ckb[keyId] = cmdGroup[0]; + } + } + } + }; + + this.bindKey = function(key, command, position) { + if (typeof key == "object" && key) { + if (position == undefined) + position = key.position; + key = key[this.platform]; + } + if (!key) + return; + if (typeof command == "function") + return this.addCommand({exec: command, bindKey: key, name: command.name || key}); + + key.split("|").forEach(function(keyPart) { + var chain = ""; + if (keyPart.indexOf(" ") != -1) { + var parts = keyPart.split(/\s+/); + keyPart = parts.pop(); + parts.forEach(function(keyPart) { + var binding = this.parseKeys(keyPart); + var id = KEY_MODS[binding.hashId] + binding.key; + chain += (chain ? " " : "") + id; + this._addCommandToBinding(chain, "chainKeys"); + }, this); + chain += " "; + } + var binding = this.parseKeys(keyPart); + var id = KEY_MODS[binding.hashId] + binding.key; + this._addCommandToBinding(chain + id, command, position); + }, this); + }; + + function getPosition(command) { + return typeof command == "object" && command.bindKey + && command.bindKey.position + || (command.isDefault ? -100 : 0); + } + this._addCommandToBinding = function(keyId, command, position) { + var ckb = this.commandKeyBinding, i; + if (!command) { + delete ckb[keyId]; + } else if (!ckb[keyId] || this.$singleCommand) { + ckb[keyId] = command; + } else { + if (!Array.isArray(ckb[keyId])) { + ckb[keyId] = [ckb[keyId]]; + } else if ((i = ckb[keyId].indexOf(command)) != -1) { + ckb[keyId].splice(i, 1); + } + + if (typeof position != "number") { + position = getPosition(command); + } + + var commands = ckb[keyId]; + for (i = 0; i < commands.length; i++) { + var other = commands[i]; + var otherPos = getPosition(other); + if (otherPos > position) + break; + } + commands.splice(i, 0, command); + } + }; + + this.addCommands = function(commands) { + commands && Object.keys(commands).forEach(function(name) { + var command = commands[name]; + if (!command) + return; + + if (typeof command === "string") + return this.bindKey(command, name); + + if (typeof command === "function") + command = { exec: command }; + + if (typeof command !== "object") + return; + + if (!command.name) + command.name = name; + + this.addCommand(command); + }, this); + }; + + this.removeCommands = function(commands) { + Object.keys(commands).forEach(function(name) { + this.removeCommand(commands[name]); + }, this); + }; + + this.bindKeys = function(keyList) { + Object.keys(keyList).forEach(function(key) { + this.bindKey(key, keyList[key]); + }, this); + }; + + this._buildKeyHash = function(command) { + this.bindKey(command.bindKey, command); + }; + this.parseKeys = function(keys) { + var parts = keys.toLowerCase().split(/[\-\+]([\-\+])?/).filter(function(x){return x;}); + var key = parts.pop(); + + var keyCode = keyUtil[key]; + if (keyUtil.FUNCTION_KEYS[keyCode]) + key = keyUtil.FUNCTION_KEYS[keyCode].toLowerCase(); + else if (!parts.length) + return {key: key, hashId: -1}; + else if (parts.length == 1 && parts[0] == "shift") + return {key: key.toUpperCase(), hashId: -1}; + + var hashId = 0; + for (var i = parts.length; i--;) { + var modifier = keyUtil.KEY_MODS[parts[i]]; + if (modifier == null) { + if (typeof console != "undefined") + console.error("invalid modifier " + parts[i] + " in " + keys); + return false; + } + hashId |= modifier; + } + return {key: key, hashId: hashId}; + }; + + this.findKeyCommand = function findKeyCommand(hashId, keyString) { + var key = KEY_MODS[hashId] + keyString; + return this.commandKeyBinding[key]; + }; + + this.handleKeyboard = function(data, hashId, keyString, keyCode) { + if (keyCode < 0) return; + var key = KEY_MODS[hashId] + keyString; + var command = this.commandKeyBinding[key]; + if (data.$keyChain) { + data.$keyChain += " " + key; + command = this.commandKeyBinding[data.$keyChain] || command; + } + + if (command) { + if (command == "chainKeys" || command[command.length - 1] == "chainKeys") { + data.$keyChain = data.$keyChain || key; + return {command: "null"}; + } + } + + if (data.$keyChain) { + if ((!hashId || hashId == 4) && keyString.length == 1) + data.$keyChain = data.$keyChain.slice(0, -key.length - 1); // wait for input + else if (hashId == -1 || keyCode > 0) + data.$keyChain = ""; // reset keyChain + } + return {command: command}; + }; + + this.getStatusText = function(editor, data) { + return data.$keyChain || ""; + }; + +}).call(HashHandler.prototype); + +exports.HashHandler = HashHandler; +exports.MultiHashHandler = MultiHashHandler; +}); + +ace.define("ace/commands/command_manager",["require","exports","module","ace/lib/oop","ace/keyboard/hash_handler","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var MultiHashHandler = acequire("../keyboard/hash_handler").MultiHashHandler; +var EventEmitter = acequire("../lib/event_emitter").EventEmitter; + +var CommandManager = function(platform, commands) { + MultiHashHandler.call(this, commands, platform); + this.byName = this.commands; + this.setDefaultHandler("exec", function(e) { + return e.command.exec(e.editor, e.args || {}); + }); +}; + +oop.inherits(CommandManager, MultiHashHandler); + +(function() { + + oop.implement(this, EventEmitter); + + this.exec = function(command, editor, args) { + if (Array.isArray(command)) { + for (var i = command.length; i--; ) { + if (this.exec(command[i], editor, args)) return true; + } + return false; + } + + if (typeof command === "string") + command = this.commands[command]; + + if (!command) + return false; + + if (editor && editor.$readOnly && !command.readOnly) + return false; + + if (command.isAvailable && !command.isAvailable(editor)) + return false; + + var e = {editor: editor, command: command, args: args}; + e.returnValue = this._emit("exec", e); + this._signal("afterExec", e); + + return e.returnValue === false ? false : true; + }; + + this.toggleRecording = function(editor) { + if (this.$inReplay) + return; + + editor && editor._emit("changeStatus"); + if (this.recording) { + this.macro.pop(); + this.removeEventListener("exec", this.$addCommandToMacro); + + if (!this.macro.length) + this.macro = this.oldMacro; + + return this.recording = false; + } + if (!this.$addCommandToMacro) { + this.$addCommandToMacro = function(e) { + this.macro.push([e.command, e.args]); + }.bind(this); + } + + this.oldMacro = this.macro; + this.macro = []; + this.on("exec", this.$addCommandToMacro); + return this.recording = true; + }; + + this.replay = function(editor) { + if (this.$inReplay || !this.macro) + return; + + if (this.recording) + return this.toggleRecording(editor); + + try { + this.$inReplay = true; + this.macro.forEach(function(x) { + if (typeof x == "string") + this.exec(x, editor); + else + this.exec(x[0], editor, x[1]); + }, this); + } finally { + this.$inReplay = false; + } + }; + + this.trimMacro = function(m) { + return m.map(function(x){ + if (typeof x[0] != "string") + x[0] = x[0].name; + if (!x[1]) + x = x[0]; + return x; + }); + }; + +}).call(CommandManager.prototype); + +exports.CommandManager = CommandManager; + +}); + +ace.define("ace/commands/default_commands",["require","exports","module","ace/lib/lang","ace/config","ace/range"], function(acequire, exports, module) { +"use strict"; + +var lang = acequire("../lib/lang"); +var config = acequire("../config"); +var Range = acequire("../range").Range; + +function bindKey(win, mac) { + return {win: win, mac: mac}; +} +exports.commands = [{ + name: "showSettingsMenu", + bindKey: bindKey("Ctrl-,", "Command-,"), + exec: function(editor) { + config.loadModule("ace/ext/settings_menu", function(module) { + module.init(editor); + editor.showSettingsMenu(); + }); + }, + readOnly: true +}, { + name: "goToNextError", + bindKey: bindKey("Alt-E", "F4"), + exec: function(editor) { + config.loadModule("ace/ext/error_marker", function(module) { + module.showErrorMarker(editor, 1); + }); + }, + scrollIntoView: "animate", + readOnly: true +}, { + name: "goToPreviousError", + bindKey: bindKey("Alt-Shift-E", "Shift-F4"), + exec: function(editor) { + config.loadModule("ace/ext/error_marker", function(module) { + module.showErrorMarker(editor, -1); + }); + }, + scrollIntoView: "animate", + readOnly: true +}, { + name: "selectall", + bindKey: bindKey("Ctrl-A", "Command-A"), + exec: function(editor) { editor.selectAll(); }, + readOnly: true +}, { + name: "centerselection", + bindKey: bindKey(null, "Ctrl-L"), + exec: function(editor) { editor.centerSelection(); }, + readOnly: true +}, { + name: "gotoline", + bindKey: bindKey("Ctrl-L", "Command-L"), + exec: function(editor) { + var line = parseInt(prompt("Enter line number:"), 10); + if (!isNaN(line)) { + editor.gotoLine(line); + } + }, + readOnly: true +}, { + name: "fold", + bindKey: bindKey("Alt-L|Ctrl-F1", "Command-Alt-L|Command-F1"), + exec: function(editor) { editor.session.toggleFold(false); }, + multiSelectAction: "forEach", + scrollIntoView: "center", + readOnly: true +}, { + name: "unfold", + bindKey: bindKey("Alt-Shift-L|Ctrl-Shift-F1", "Command-Alt-Shift-L|Command-Shift-F1"), + exec: function(editor) { editor.session.toggleFold(true); }, + multiSelectAction: "forEach", + scrollIntoView: "center", + readOnly: true +}, { + name: "toggleFoldWidget", + bindKey: bindKey("F2", "F2"), + exec: function(editor) { editor.session.toggleFoldWidget(); }, + multiSelectAction: "forEach", + scrollIntoView: "center", + readOnly: true +}, { + name: "toggleParentFoldWidget", + bindKey: bindKey("Alt-F2", "Alt-F2"), + exec: function(editor) { editor.session.toggleFoldWidget(true); }, + multiSelectAction: "forEach", + scrollIntoView: "center", + readOnly: true +}, { + name: "foldall", + bindKey: bindKey(null, "Ctrl-Command-Option-0"), + exec: function(editor) { editor.session.foldAll(); }, + scrollIntoView: "center", + readOnly: true +}, { + name: "foldOther", + bindKey: bindKey("Alt-0", "Command-Option-0"), + exec: function(editor) { + editor.session.foldAll(); + editor.session.unfold(editor.selection.getAllRanges()); + }, + scrollIntoView: "center", + readOnly: true +}, { + name: "unfoldall", + bindKey: bindKey("Alt-Shift-0", "Command-Option-Shift-0"), + exec: function(editor) { editor.session.unfold(); }, + scrollIntoView: "center", + readOnly: true +}, { + name: "findnext", + bindKey: bindKey("Ctrl-K", "Command-G"), + exec: function(editor) { editor.findNext(); }, + multiSelectAction: "forEach", + scrollIntoView: "center", + readOnly: true +}, { + name: "findprevious", + bindKey: bindKey("Ctrl-Shift-K", "Command-Shift-G"), + exec: function(editor) { editor.findPrevious(); }, + multiSelectAction: "forEach", + scrollIntoView: "center", + readOnly: true +}, { + name: "selectOrFindNext", + bindKey: bindKey("Alt-K", "Ctrl-G"), + exec: function(editor) { + if (editor.selection.isEmpty()) + editor.selection.selectWord(); + else + editor.findNext(); + }, + readOnly: true +}, { + name: "selectOrFindPrevious", + bindKey: bindKey("Alt-Shift-K", "Ctrl-Shift-G"), + exec: function(editor) { + if (editor.selection.isEmpty()) + editor.selection.selectWord(); + else + editor.findPrevious(); + }, + readOnly: true +}, { + name: "find", + bindKey: bindKey("Ctrl-F", "Command-F"), + exec: function(editor) { + config.loadModule("ace/ext/searchbox", function(e) {e.Search(editor);}); + }, + readOnly: true +}, { + name: "overwrite", + bindKey: "Insert", + exec: function(editor) { editor.toggleOverwrite(); }, + readOnly: true +}, { + name: "selecttostart", + bindKey: bindKey("Ctrl-Shift-Home", "Command-Shift-Home|Command-Shift-Up"), + exec: function(editor) { editor.getSelection().selectFileStart(); }, + multiSelectAction: "forEach", + readOnly: true, + scrollIntoView: "animate", + aceCommandGroup: "fileJump" +}, { + name: "gotostart", + bindKey: bindKey("Ctrl-Home", "Command-Home|Command-Up"), + exec: function(editor) { editor.navigateFileStart(); }, + multiSelectAction: "forEach", + readOnly: true, + scrollIntoView: "animate", + aceCommandGroup: "fileJump" +}, { + name: "selectup", + bindKey: bindKey("Shift-Up", "Shift-Up|Ctrl-Shift-P"), + exec: function(editor) { editor.getSelection().selectUp(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "golineup", + bindKey: bindKey("Up", "Up|Ctrl-P"), + exec: function(editor, args) { editor.navigateUp(args.times); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selecttoend", + bindKey: bindKey("Ctrl-Shift-End", "Command-Shift-End|Command-Shift-Down"), + exec: function(editor) { editor.getSelection().selectFileEnd(); }, + multiSelectAction: "forEach", + readOnly: true, + scrollIntoView: "animate", + aceCommandGroup: "fileJump" +}, { + name: "gotoend", + bindKey: bindKey("Ctrl-End", "Command-End|Command-Down"), + exec: function(editor) { editor.navigateFileEnd(); }, + multiSelectAction: "forEach", + readOnly: true, + scrollIntoView: "animate", + aceCommandGroup: "fileJump" +}, { + name: "selectdown", + bindKey: bindKey("Shift-Down", "Shift-Down|Ctrl-Shift-N"), + exec: function(editor) { editor.getSelection().selectDown(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "golinedown", + bindKey: bindKey("Down", "Down|Ctrl-N"), + exec: function(editor, args) { editor.navigateDown(args.times); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectwordleft", + bindKey: bindKey("Ctrl-Shift-Left", "Option-Shift-Left"), + exec: function(editor) { editor.getSelection().selectWordLeft(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "gotowordleft", + bindKey: bindKey("Ctrl-Left", "Option-Left"), + exec: function(editor) { editor.navigateWordLeft(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selecttolinestart", + bindKey: bindKey("Alt-Shift-Left", "Command-Shift-Left|Ctrl-Shift-A"), + exec: function(editor) { editor.getSelection().selectLineStart(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "gotolinestart", + bindKey: bindKey("Alt-Left|Home", "Command-Left|Home|Ctrl-A"), + exec: function(editor) { editor.navigateLineStart(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectleft", + bindKey: bindKey("Shift-Left", "Shift-Left|Ctrl-Shift-B"), + exec: function(editor) { editor.getSelection().selectLeft(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "gotoleft", + bindKey: bindKey("Left", "Left|Ctrl-B"), + exec: function(editor, args) { editor.navigateLeft(args.times); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectwordright", + bindKey: bindKey("Ctrl-Shift-Right", "Option-Shift-Right"), + exec: function(editor) { editor.getSelection().selectWordRight(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "gotowordright", + bindKey: bindKey("Ctrl-Right", "Option-Right"), + exec: function(editor) { editor.navigateWordRight(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selecttolineend", + bindKey: bindKey("Alt-Shift-Right", "Command-Shift-Right|Shift-End|Ctrl-Shift-E"), + exec: function(editor) { editor.getSelection().selectLineEnd(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "gotolineend", + bindKey: bindKey("Alt-Right|End", "Command-Right|End|Ctrl-E"), + exec: function(editor) { editor.navigateLineEnd(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectright", + bindKey: bindKey("Shift-Right", "Shift-Right"), + exec: function(editor) { editor.getSelection().selectRight(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "gotoright", + bindKey: bindKey("Right", "Right|Ctrl-F"), + exec: function(editor, args) { editor.navigateRight(args.times); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectpagedown", + bindKey: "Shift-PageDown", + exec: function(editor) { editor.selectPageDown(); }, + readOnly: true +}, { + name: "pagedown", + bindKey: bindKey(null, "Option-PageDown"), + exec: function(editor) { editor.scrollPageDown(); }, + readOnly: true +}, { + name: "gotopagedown", + bindKey: bindKey("PageDown", "PageDown|Ctrl-V"), + exec: function(editor) { editor.gotoPageDown(); }, + readOnly: true +}, { + name: "selectpageup", + bindKey: "Shift-PageUp", + exec: function(editor) { editor.selectPageUp(); }, + readOnly: true +}, { + name: "pageup", + bindKey: bindKey(null, "Option-PageUp"), + exec: function(editor) { editor.scrollPageUp(); }, + readOnly: true +}, { + name: "gotopageup", + bindKey: "PageUp", + exec: function(editor) { editor.gotoPageUp(); }, + readOnly: true +}, { + name: "scrollup", + bindKey: bindKey("Ctrl-Up", null), + exec: function(e) { e.renderer.scrollBy(0, -2 * e.renderer.layerConfig.lineHeight); }, + readOnly: true +}, { + name: "scrolldown", + bindKey: bindKey("Ctrl-Down", null), + exec: function(e) { e.renderer.scrollBy(0, 2 * e.renderer.layerConfig.lineHeight); }, + readOnly: true +}, { + name: "selectlinestart", + bindKey: "Shift-Home", + exec: function(editor) { editor.getSelection().selectLineStart(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectlineend", + bindKey: "Shift-End", + exec: function(editor) { editor.getSelection().selectLineEnd(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "togglerecording", + bindKey: bindKey("Ctrl-Alt-E", "Command-Option-E"), + exec: function(editor) { editor.commands.toggleRecording(editor); }, + readOnly: true +}, { + name: "replaymacro", + bindKey: bindKey("Ctrl-Shift-E", "Command-Shift-E"), + exec: function(editor) { editor.commands.replay(editor); }, + readOnly: true +}, { + name: "jumptomatching", + bindKey: bindKey("Ctrl-P", "Ctrl-P"), + exec: function(editor) { editor.jumpToMatching(); }, + multiSelectAction: "forEach", + scrollIntoView: "animate", + readOnly: true +}, { + name: "selecttomatching", + bindKey: bindKey("Ctrl-Shift-P", "Ctrl-Shift-P"), + exec: function(editor) { editor.jumpToMatching(true); }, + multiSelectAction: "forEach", + scrollIntoView: "animate", + readOnly: true +}, { + name: "expandToMatching", + bindKey: bindKey("Ctrl-Shift-M", "Ctrl-Shift-M"), + exec: function(editor) { editor.jumpToMatching(true, true); }, + multiSelectAction: "forEach", + scrollIntoView: "animate", + readOnly: true +}, { + name: "passKeysToBrowser", + bindKey: bindKey(null, null), + exec: function() {}, + passEvent: true, + readOnly: true +}, { + name: "copy", + exec: function(editor) { + }, + readOnly: true +}, +{ + name: "cut", + exec: function(editor) { + var range = editor.getSelectionRange(); + editor._emit("cut", range); + + if (!editor.selection.isEmpty()) { + editor.session.remove(range); + editor.clearSelection(); + } + }, + scrollIntoView: "cursor", + multiSelectAction: "forEach" +}, { + name: "paste", + exec: function(editor, args) { + editor.$handlePaste(args); + }, + scrollIntoView: "cursor" +}, { + name: "removeline", + bindKey: bindKey("Ctrl-D", "Command-D"), + exec: function(editor) { editor.removeLines(); }, + scrollIntoView: "cursor", + multiSelectAction: "forEachLine" +}, { + name: "duplicateSelection", + bindKey: bindKey("Ctrl-Shift-D", "Command-Shift-D"), + exec: function(editor) { editor.duplicateSelection(); }, + scrollIntoView: "cursor", + multiSelectAction: "forEach" +}, { + name: "sortlines", + bindKey: bindKey("Ctrl-Alt-S", "Command-Alt-S"), + exec: function(editor) { editor.sortLines(); }, + scrollIntoView: "selection", + multiSelectAction: "forEachLine" +}, { + name: "togglecomment", + bindKey: bindKey("Ctrl-/", "Command-/"), + exec: function(editor) { editor.toggleCommentLines(); }, + multiSelectAction: "forEachLine", + scrollIntoView: "selectionPart" +}, { + name: "toggleBlockComment", + bindKey: bindKey("Ctrl-Shift-/", "Command-Shift-/"), + exec: function(editor) { editor.toggleBlockComment(); }, + multiSelectAction: "forEach", + scrollIntoView: "selectionPart" +}, { + name: "modifyNumberUp", + bindKey: bindKey("Ctrl-Shift-Up", "Alt-Shift-Up"), + exec: function(editor) { editor.modifyNumber(1); }, + scrollIntoView: "cursor", + multiSelectAction: "forEach" +}, { + name: "modifyNumberDown", + bindKey: bindKey("Ctrl-Shift-Down", "Alt-Shift-Down"), + exec: function(editor) { editor.modifyNumber(-1); }, + scrollIntoView: "cursor", + multiSelectAction: "forEach" +}, { + name: "replace", + bindKey: bindKey("Ctrl-H", "Command-Option-F"), + exec: function(editor) { + config.loadModule("ace/ext/searchbox", function(e) {e.Search(editor, true);}); + } +}, { + name: "undo", + bindKey: bindKey("Ctrl-Z", "Command-Z"), + exec: function(editor) { editor.undo(); } +}, { + name: "redo", + bindKey: bindKey("Ctrl-Shift-Z|Ctrl-Y", "Command-Shift-Z|Command-Y"), + exec: function(editor) { editor.redo(); } +}, { + name: "copylinesup", + bindKey: bindKey("Alt-Shift-Up", "Command-Option-Up"), + exec: function(editor) { editor.copyLinesUp(); }, + scrollIntoView: "cursor" +}, { + name: "movelinesup", + bindKey: bindKey("Alt-Up", "Option-Up"), + exec: function(editor) { editor.moveLinesUp(); }, + scrollIntoView: "cursor" +}, { + name: "copylinesdown", + bindKey: bindKey("Alt-Shift-Down", "Command-Option-Down"), + exec: function(editor) { editor.copyLinesDown(); }, + scrollIntoView: "cursor" +}, { + name: "movelinesdown", + bindKey: bindKey("Alt-Down", "Option-Down"), + exec: function(editor) { editor.moveLinesDown(); }, + scrollIntoView: "cursor" +}, { + name: "del", + bindKey: bindKey("Delete", "Delete|Ctrl-D|Shift-Delete"), + exec: function(editor) { editor.remove("right"); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "backspace", + bindKey: bindKey( + "Shift-Backspace|Backspace", + "Ctrl-Backspace|Shift-Backspace|Backspace|Ctrl-H" + ), + exec: function(editor) { editor.remove("left"); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "cut_or_delete", + bindKey: bindKey("Shift-Delete", null), + exec: function(editor) { + if (editor.selection.isEmpty()) { + editor.remove("left"); + } else { + return false; + } + }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "removetolinestart", + bindKey: bindKey("Alt-Backspace", "Command-Backspace"), + exec: function(editor) { editor.removeToLineStart(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "removetolineend", + bindKey: bindKey("Alt-Delete", "Ctrl-K|Command-Delete"), + exec: function(editor) { editor.removeToLineEnd(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "removetolinestarthard", + bindKey: bindKey("Ctrl-Shift-Backspace", null), + exec: function(editor) { + var range = editor.selection.getRange(); + range.start.column = 0; + editor.session.remove(range); + }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "removetolineendhard", + bindKey: bindKey("Ctrl-Shift-Delete", null), + exec: function(editor) { + var range = editor.selection.getRange(); + range.end.column = Number.MAX_VALUE; + editor.session.remove(range); + }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "removewordleft", + bindKey: bindKey("Ctrl-Backspace", "Alt-Backspace|Ctrl-Alt-Backspace"), + exec: function(editor) { editor.removeWordLeft(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "removewordright", + bindKey: bindKey("Ctrl-Delete", "Alt-Delete"), + exec: function(editor) { editor.removeWordRight(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "outdent", + bindKey: bindKey("Shift-Tab", "Shift-Tab"), + exec: function(editor) { editor.blockOutdent(); }, + multiSelectAction: "forEach", + scrollIntoView: "selectionPart" +}, { + name: "indent", + bindKey: bindKey("Tab", "Tab"), + exec: function(editor) { editor.indent(); }, + multiSelectAction: "forEach", + scrollIntoView: "selectionPart" +}, { + name: "blockoutdent", + bindKey: bindKey("Ctrl-[", "Ctrl-["), + exec: function(editor) { editor.blockOutdent(); }, + multiSelectAction: "forEachLine", + scrollIntoView: "selectionPart" +}, { + name: "blockindent", + bindKey: bindKey("Ctrl-]", "Ctrl-]"), + exec: function(editor) { editor.blockIndent(); }, + multiSelectAction: "forEachLine", + scrollIntoView: "selectionPart" +}, { + name: "insertstring", + exec: function(editor, str) { editor.insert(str); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "inserttext", + exec: function(editor, args) { + editor.insert(lang.stringRepeat(args.text || "", args.times || 1)); + }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "splitline", + bindKey: bindKey(null, "Ctrl-O"), + exec: function(editor) { editor.splitLine(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "transposeletters", + bindKey: bindKey("Alt-Shift-X", "Ctrl-T"), + exec: function(editor) { editor.transposeLetters(); }, + multiSelectAction: function(editor) {editor.transposeSelections(1); }, + scrollIntoView: "cursor" +}, { + name: "touppercase", + bindKey: bindKey("Ctrl-U", "Ctrl-U"), + exec: function(editor) { editor.toUpperCase(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "tolowercase", + bindKey: bindKey("Ctrl-Shift-U", "Ctrl-Shift-U"), + exec: function(editor) { editor.toLowerCase(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "expandtoline", + bindKey: bindKey("Ctrl-Shift-L", "Command-Shift-L"), + exec: function(editor) { + var range = editor.selection.getRange(); + + range.start.column = range.end.column = 0; + range.end.row++; + editor.selection.setRange(range, false); + }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "joinlines", + bindKey: bindKey(null, null), + exec: function(editor) { + var isBackwards = editor.selection.isBackwards(); + var selectionStart = isBackwards ? editor.selection.getSelectionLead() : editor.selection.getSelectionAnchor(); + var selectionEnd = isBackwards ? editor.selection.getSelectionAnchor() : editor.selection.getSelectionLead(); + var firstLineEndCol = editor.session.doc.getLine(selectionStart.row).length; + var selectedText = editor.session.doc.getTextRange(editor.selection.getRange()); + var selectedCount = selectedText.replace(/\n\s*/, " ").length; + var insertLine = editor.session.doc.getLine(selectionStart.row); + + for (var i = selectionStart.row + 1; i <= selectionEnd.row + 1; i++) { + var curLine = lang.stringTrimLeft(lang.stringTrimRight(editor.session.doc.getLine(i))); + if (curLine.length !== 0) { + curLine = " " + curLine; + } + insertLine += curLine; + } + + if (selectionEnd.row + 1 < (editor.session.doc.getLength() - 1)) { + insertLine += editor.session.doc.getNewLineCharacter(); + } + + editor.clearSelection(); + editor.session.doc.replace(new Range(selectionStart.row, 0, selectionEnd.row + 2, 0), insertLine); + + if (selectedCount > 0) { + editor.selection.moveCursorTo(selectionStart.row, selectionStart.column); + editor.selection.selectTo(selectionStart.row, selectionStart.column + selectedCount); + } else { + firstLineEndCol = editor.session.doc.getLine(selectionStart.row).length > firstLineEndCol ? (firstLineEndCol + 1) : firstLineEndCol; + editor.selection.moveCursorTo(selectionStart.row, firstLineEndCol); + } + }, + multiSelectAction: "forEach", + readOnly: true +}, { + name: "invertSelection", + bindKey: bindKey(null, null), + exec: function(editor) { + var endRow = editor.session.doc.getLength() - 1; + var endCol = editor.session.doc.getLine(endRow).length; + var ranges = editor.selection.rangeList.ranges; + var newRanges = []; + if (ranges.length < 1) { + ranges = [editor.selection.getRange()]; + } + + for (var i = 0; i < ranges.length; i++) { + if (i == (ranges.length - 1)) { + if (!(ranges[i].end.row === endRow && ranges[i].end.column === endCol)) { + newRanges.push(new Range(ranges[i].end.row, ranges[i].end.column, endRow, endCol)); + } + } + + if (i === 0) { + if (!(ranges[i].start.row === 0 && ranges[i].start.column === 0)) { + newRanges.push(new Range(0, 0, ranges[i].start.row, ranges[i].start.column)); + } + } else { + newRanges.push(new Range(ranges[i-1].end.row, ranges[i-1].end.column, ranges[i].start.row, ranges[i].start.column)); + } + } + + editor.exitMultiSelectMode(); + editor.clearSelection(); + + for(var i = 0; i < newRanges.length; i++) { + editor.selection.addRange(newRanges[i], false); + } + }, + readOnly: true, + scrollIntoView: "none" +}]; + +}); + +ace.define("ace/editor",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/keyboard/textinput","ace/mouse/mouse_handler","ace/mouse/fold_handler","ace/keyboard/keybinding","ace/edit_session","ace/search","ace/range","ace/lib/event_emitter","ace/commands/command_manager","ace/commands/default_commands","ace/config","ace/token_iterator"], function(acequire, exports, module) { +"use strict"; + +acequire("./lib/fixoldbrowsers"); + +var oop = acequire("./lib/oop"); +var dom = acequire("./lib/dom"); +var lang = acequire("./lib/lang"); +var useragent = acequire("./lib/useragent"); +var TextInput = acequire("./keyboard/textinput").TextInput; +var MouseHandler = acequire("./mouse/mouse_handler").MouseHandler; +var FoldHandler = acequire("./mouse/fold_handler").FoldHandler; +var KeyBinding = acequire("./keyboard/keybinding").KeyBinding; +var EditSession = acequire("./edit_session").EditSession; +var Search = acequire("./search").Search; +var Range = acequire("./range").Range; +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var CommandManager = acequire("./commands/command_manager").CommandManager; +var defaultCommands = acequire("./commands/default_commands").commands; +var config = acequire("./config"); +var TokenIterator = acequire("./token_iterator").TokenIterator; +var Editor = function(renderer, session) { + var container = renderer.getContainerElement(); + this.container = container; + this.renderer = renderer; + this.id = "editor" + (++Editor.$uid); + + this.commands = new CommandManager(useragent.isMac ? "mac" : "win", defaultCommands); + if (typeof document == "object") { + this.textInput = new TextInput(renderer.getTextAreaContainer(), this); + this.renderer.textarea = this.textInput.getElement(); + this.$mouseHandler = new MouseHandler(this); + new FoldHandler(this); + } + + this.keyBinding = new KeyBinding(this); + + this.$blockScrolling = 0; + this.$search = new Search().set({ + wrap: true + }); + + this.$historyTracker = this.$historyTracker.bind(this); + this.commands.on("exec", this.$historyTracker); + + this.$initOperationListeners(); + + this._$emitInputEvent = lang.delayedCall(function() { + this._signal("input", {}); + if (this.session && this.session.bgTokenizer) + this.session.bgTokenizer.scheduleStart(); + }.bind(this)); + + this.on("change", function(_, _self) { + _self._$emitInputEvent.schedule(31); + }); + + this.setSession(session || new EditSession("")); + config.resetOptions(this); + config._signal("editor", this); +}; + +Editor.$uid = 0; + +(function(){ + + oop.implement(this, EventEmitter); + + this.$initOperationListeners = function() { + function last(a) {return a[a.length - 1];} + + this.selections = []; + this.commands.on("exec", this.startOperation.bind(this), true); + this.commands.on("afterExec", this.endOperation.bind(this), true); + + this.$opResetTimer = lang.delayedCall(this.endOperation.bind(this)); + + this.on("change", function() { + this.curOp || this.startOperation(); + this.curOp.docChanged = true; + }.bind(this), true); + + this.on("changeSelection", function() { + this.curOp || this.startOperation(); + this.curOp.selectionChanged = true; + }.bind(this), true); + }; + + this.curOp = null; + this.prevOp = {}; + this.startOperation = function(commadEvent) { + if (this.curOp) { + if (!commadEvent || this.curOp.command) + return; + this.prevOp = this.curOp; + } + if (!commadEvent) { + this.previousCommand = null; + commadEvent = {}; + } + + this.$opResetTimer.schedule(); + this.curOp = { + command: commadEvent.command || {}, + args: commadEvent.args, + scrollTop: this.renderer.scrollTop + }; + if (this.curOp.command.name && this.curOp.command.scrollIntoView !== undefined) + this.$blockScrolling++; + }; + + this.endOperation = function(e) { + if (this.curOp) { + if (e && e.returnValue === false) + return this.curOp = null; + this._signal("beforeEndOperation"); + var command = this.curOp.command; + if (command.name && this.$blockScrolling > 0) + this.$blockScrolling--; + var scrollIntoView = command && command.scrollIntoView; + if (scrollIntoView) { + switch (scrollIntoView) { + case "center-animate": + scrollIntoView = "animate"; + case "center": + this.renderer.scrollCursorIntoView(null, 0.5); + break; + case "animate": + case "cursor": + this.renderer.scrollCursorIntoView(); + break; + case "selectionPart": + var range = this.selection.getRange(); + var config = this.renderer.layerConfig; + if (range.start.row >= config.lastRow || range.end.row <= config.firstRow) { + this.renderer.scrollSelectionIntoView(this.selection.anchor, this.selection.lead); + } + break; + default: + break; + } + if (scrollIntoView == "animate") + this.renderer.animateScrolling(this.curOp.scrollTop); + } + + this.prevOp = this.curOp; + this.curOp = null; + } + }; + this.$mergeableCommands = ["backspace", "del", "insertstring"]; + this.$historyTracker = function(e) { + if (!this.$mergeUndoDeltas) + return; + + var prev = this.prevOp; + var mergeableCommands = this.$mergeableCommands; + var shouldMerge = prev.command && (e.command.name == prev.command.name); + if (e.command.name == "insertstring") { + var text = e.args; + if (this.mergeNextCommand === undefined) + this.mergeNextCommand = true; + + shouldMerge = shouldMerge + && this.mergeNextCommand // previous command allows to coalesce with + && (!/\s/.test(text) || /\s/.test(prev.args)); // previous insertion was of same type + + this.mergeNextCommand = true; + } else { + shouldMerge = shouldMerge + && mergeableCommands.indexOf(e.command.name) !== -1; // the command is mergeable + } + + if ( + this.$mergeUndoDeltas != "always" + && Date.now() - this.sequenceStartTime > 2000 + ) { + shouldMerge = false; // the sequence is too long + } + + if (shouldMerge) + this.session.mergeUndoDeltas = true; + else if (mergeableCommands.indexOf(e.command.name) !== -1) + this.sequenceStartTime = Date.now(); + }; + this.setKeyboardHandler = function(keyboardHandler, cb) { + if (keyboardHandler && typeof keyboardHandler === "string") { + this.$keybindingId = keyboardHandler; + var _self = this; + config.loadModule(["keybinding", keyboardHandler], function(module) { + if (_self.$keybindingId == keyboardHandler) + _self.keyBinding.setKeyboardHandler(module && module.handler); + cb && cb(); + }); + } else { + this.$keybindingId = null; + this.keyBinding.setKeyboardHandler(keyboardHandler); + cb && cb(); + } + }; + this.getKeyboardHandler = function() { + return this.keyBinding.getKeyboardHandler(); + }; + this.setSession = function(session) { + if (this.session == session) + return; + if (this.curOp) this.endOperation(); + this.curOp = {}; + + var oldSession = this.session; + if (oldSession) { + this.session.off("change", this.$onDocumentChange); + this.session.off("changeMode", this.$onChangeMode); + this.session.off("tokenizerUpdate", this.$onTokenizerUpdate); + this.session.off("changeTabSize", this.$onChangeTabSize); + this.session.off("changeWrapLimit", this.$onChangeWrapLimit); + this.session.off("changeWrapMode", this.$onChangeWrapMode); + this.session.off("changeFold", this.$onChangeFold); + this.session.off("changeFrontMarker", this.$onChangeFrontMarker); + this.session.off("changeBackMarker", this.$onChangeBackMarker); + this.session.off("changeBreakpoint", this.$onChangeBreakpoint); + this.session.off("changeAnnotation", this.$onChangeAnnotation); + this.session.off("changeOverwrite", this.$onCursorChange); + this.session.off("changeScrollTop", this.$onScrollTopChange); + this.session.off("changeScrollLeft", this.$onScrollLeftChange); + + var selection = this.session.getSelection(); + selection.off("changeCursor", this.$onCursorChange); + selection.off("changeSelection", this.$onSelectionChange); + } + + this.session = session; + if (session) { + this.$onDocumentChange = this.onDocumentChange.bind(this); + session.on("change", this.$onDocumentChange); + this.renderer.setSession(session); + + this.$onChangeMode = this.onChangeMode.bind(this); + session.on("changeMode", this.$onChangeMode); + + this.$onTokenizerUpdate = this.onTokenizerUpdate.bind(this); + session.on("tokenizerUpdate", this.$onTokenizerUpdate); + + this.$onChangeTabSize = this.renderer.onChangeTabSize.bind(this.renderer); + session.on("changeTabSize", this.$onChangeTabSize); + + this.$onChangeWrapLimit = this.onChangeWrapLimit.bind(this); + session.on("changeWrapLimit", this.$onChangeWrapLimit); + + this.$onChangeWrapMode = this.onChangeWrapMode.bind(this); + session.on("changeWrapMode", this.$onChangeWrapMode); + + this.$onChangeFold = this.onChangeFold.bind(this); + session.on("changeFold", this.$onChangeFold); + + this.$onChangeFrontMarker = this.onChangeFrontMarker.bind(this); + this.session.on("changeFrontMarker", this.$onChangeFrontMarker); + + this.$onChangeBackMarker = this.onChangeBackMarker.bind(this); + this.session.on("changeBackMarker", this.$onChangeBackMarker); + + this.$onChangeBreakpoint = this.onChangeBreakpoint.bind(this); + this.session.on("changeBreakpoint", this.$onChangeBreakpoint); + + this.$onChangeAnnotation = this.onChangeAnnotation.bind(this); + this.session.on("changeAnnotation", this.$onChangeAnnotation); + + this.$onCursorChange = this.onCursorChange.bind(this); + this.session.on("changeOverwrite", this.$onCursorChange); + + this.$onScrollTopChange = this.onScrollTopChange.bind(this); + this.session.on("changeScrollTop", this.$onScrollTopChange); + + this.$onScrollLeftChange = this.onScrollLeftChange.bind(this); + this.session.on("changeScrollLeft", this.$onScrollLeftChange); + + this.selection = session.getSelection(); + this.selection.on("changeCursor", this.$onCursorChange); + + this.$onSelectionChange = this.onSelectionChange.bind(this); + this.selection.on("changeSelection", this.$onSelectionChange); + + this.onChangeMode(); + + this.$blockScrolling += 1; + this.onCursorChange(); + this.$blockScrolling -= 1; + + this.onScrollTopChange(); + this.onScrollLeftChange(); + this.onSelectionChange(); + this.onChangeFrontMarker(); + this.onChangeBackMarker(); + this.onChangeBreakpoint(); + this.onChangeAnnotation(); + this.session.getUseWrapMode() && this.renderer.adjustWrapLimit(); + this.renderer.updateFull(); + } else { + this.selection = null; + this.renderer.setSession(session); + } + + this._signal("changeSession", { + session: session, + oldSession: oldSession + }); + + this.curOp = null; + + oldSession && oldSession._signal("changeEditor", {oldEditor: this}); + session && session._signal("changeEditor", {editor: this}); + + if (session && session.bgTokenizer) + session.bgTokenizer.scheduleStart(); + }; + this.getSession = function() { + return this.session; + }; + this.setValue = function(val, cursorPos) { + this.session.doc.setValue(val); + + if (!cursorPos) + this.selectAll(); + else if (cursorPos == 1) + this.navigateFileEnd(); + else if (cursorPos == -1) + this.navigateFileStart(); + + return val; + }; + this.getValue = function() { + return this.session.getValue(); + }; + this.getSelection = function() { + return this.selection; + }; + this.resize = function(force) { + this.renderer.onResize(force); + }; + this.setTheme = function(theme, cb) { + this.renderer.setTheme(theme, cb); + }; + this.getTheme = function() { + return this.renderer.getTheme(); + }; + this.setStyle = function(style) { + this.renderer.setStyle(style); + }; + this.unsetStyle = function(style) { + this.renderer.unsetStyle(style); + }; + this.getFontSize = function () { + return this.getOption("fontSize") || + dom.computedStyle(this.container, "fontSize"); + }; + this.setFontSize = function(size) { + this.setOption("fontSize", size); + }; + + this.$highlightBrackets = function() { + if (this.session.$bracketHighlight) { + this.session.removeMarker(this.session.$bracketHighlight); + this.session.$bracketHighlight = null; + } + + if (this.$highlightPending) { + return; + } + var self = this; + this.$highlightPending = true; + setTimeout(function() { + self.$highlightPending = false; + var session = self.session; + if (!session || !session.bgTokenizer) return; + var pos = session.findMatchingBracket(self.getCursorPosition()); + if (pos) { + var range = new Range(pos.row, pos.column, pos.row, pos.column + 1); + } else if (session.$mode.getMatching) { + var range = session.$mode.getMatching(self.session); + } + if (range) + session.$bracketHighlight = session.addMarker(range, "ace_bracket", "text"); + }, 50); + }; + this.$highlightTags = function() { + if (this.$highlightTagPending) + return; + var self = this; + this.$highlightTagPending = true; + setTimeout(function() { + self.$highlightTagPending = false; + + var session = self.session; + if (!session || !session.bgTokenizer) return; + + var pos = self.getCursorPosition(); + var iterator = new TokenIterator(self.session, pos.row, pos.column); + var token = iterator.getCurrentToken(); + + if (!token || !/\b(?:tag-open|tag-name)/.test(token.type)) { + session.removeMarker(session.$tagHighlight); + session.$tagHighlight = null; + return; + } + + if (token.type.indexOf("tag-open") != -1) { + token = iterator.stepForward(); + if (!token) + return; + } + + var tag = token.value; + var depth = 0; + var prevToken = iterator.stepBackward(); + + if (prevToken.value == '<'){ + do { + prevToken = token; + token = iterator.stepForward(); + + if (token && token.value === tag && token.type.indexOf('tag-name') !== -1) { + if (prevToken.value === '<'){ + depth++; + } else if (prevToken.value === '= 0); + } else { + do { + token = prevToken; + prevToken = iterator.stepBackward(); + + if (token && token.value === tag && token.type.indexOf('tag-name') !== -1) { + if (prevToken.value === '<') { + depth++; + } else if (prevToken.value === ' 1)) + highlight = false; + } + + if (session.$highlightLineMarker && !highlight) { + session.removeMarker(session.$highlightLineMarker.id); + session.$highlightLineMarker = null; + } else if (!session.$highlightLineMarker && highlight) { + var range = new Range(highlight.row, highlight.column, highlight.row, Infinity); + range.id = session.addMarker(range, "ace_active-line", "screenLine"); + session.$highlightLineMarker = range; + } else if (highlight) { + session.$highlightLineMarker.start.row = highlight.row; + session.$highlightLineMarker.end.row = highlight.row; + session.$highlightLineMarker.start.column = highlight.column; + session._signal("changeBackMarker"); + } + }; + + this.onSelectionChange = function(e) { + var session = this.session; + + if (session.$selectionMarker) { + session.removeMarker(session.$selectionMarker); + } + session.$selectionMarker = null; + + if (!this.selection.isEmpty()) { + var range = this.selection.getRange(); + var style = this.getSelectionStyle(); + session.$selectionMarker = session.addMarker(range, "ace_selection", style); + } else { + this.$updateHighlightActiveLine(); + } + + var re = this.$highlightSelectedWord && this.$getSelectionHighLightRegexp(); + this.session.highlight(re); + + this._signal("changeSelection"); + }; + + this.$getSelectionHighLightRegexp = function() { + var session = this.session; + + var selection = this.getSelectionRange(); + if (selection.isEmpty() || selection.isMultiLine()) + return; + + var startOuter = selection.start.column - 1; + var endOuter = selection.end.column + 1; + var line = session.getLine(selection.start.row); + var lineCols = line.length; + var needle = line.substring(Math.max(startOuter, 0), + Math.min(endOuter, lineCols)); + if ((startOuter >= 0 && /^[\w\d]/.test(needle)) || + (endOuter <= lineCols && /[\w\d]$/.test(needle))) + return; + + needle = line.substring(selection.start.column, selection.end.column); + if (!/^[\w\d]+$/.test(needle)) + return; + + var re = this.$search.$assembleRegExp({ + wholeWord: true, + caseSensitive: true, + needle: needle + }); + + return re; + }; + + + this.onChangeFrontMarker = function() { + this.renderer.updateFrontMarkers(); + }; + + this.onChangeBackMarker = function() { + this.renderer.updateBackMarkers(); + }; + + + this.onChangeBreakpoint = function() { + this.renderer.updateBreakpoints(); + }; + + this.onChangeAnnotation = function() { + this.renderer.setAnnotations(this.session.getAnnotations()); + }; + + + this.onChangeMode = function(e) { + this.renderer.updateText(); + this._emit("changeMode", e); + }; + + + this.onChangeWrapLimit = function() { + this.renderer.updateFull(); + }; + + this.onChangeWrapMode = function() { + this.renderer.onResize(true); + }; + + + this.onChangeFold = function() { + this.$updateHighlightActiveLine(); + this.renderer.updateFull(); + }; + this.getSelectedText = function() { + return this.session.getTextRange(this.getSelectionRange()); + }; + this.getCopyText = function() { + var text = this.getSelectedText(); + this._signal("copy", text); + return text; + }; + this.onCopy = function() { + this.commands.exec("copy", this); + }; + this.onCut = function() { + this.commands.exec("cut", this); + }; + this.onPaste = function(text, event) { + var e = {text: text, event: event}; + this.commands.exec("paste", this, e); + }; + + this.$handlePaste = function(e) { + if (typeof e == "string") + e = {text: e}; + this._signal("paste", e); + var text = e.text; + if (!this.inMultiSelectMode || this.inVirtualSelectionMode) { + this.insert(text); + } else { + var lines = text.split(/\r\n|\r|\n/); + var ranges = this.selection.rangeList.ranges; + + if (lines.length > ranges.length || lines.length < 2 || !lines[1]) + return this.commands.exec("insertstring", this, text); + + for (var i = ranges.length; i--;) { + var range = ranges[i]; + if (!range.isEmpty()) + this.session.remove(range); + + this.session.insert(range.start, lines[i]); + } + } + }; + + this.execCommand = function(command, args) { + return this.commands.exec(command, this, args); + }; + this.insert = function(text, pasted) { + var session = this.session; + var mode = session.getMode(); + var cursor = this.getCursorPosition(); + + if (this.getBehavioursEnabled() && !pasted) { + var transform = mode.transformAction(session.getState(cursor.row), 'insertion', this, session, text); + if (transform) { + if (text !== transform.text) { + this.session.mergeUndoDeltas = false; + this.$mergeNextCommand = false; + } + text = transform.text; + + } + } + + if (text == "\t") + text = this.session.getTabString(); + if (!this.selection.isEmpty()) { + var range = this.getSelectionRange(); + cursor = this.session.remove(range); + this.clearSelection(); + } + else if (this.session.getOverwrite() && text.indexOf("\n") == -1) { + var range = new Range.fromPoints(cursor, cursor); + range.end.column += text.length; + this.session.remove(range); + } + + if (text == "\n" || text == "\r\n") { + var line = session.getLine(cursor.row); + if (cursor.column > line.search(/\S|$/)) { + var d = line.substr(cursor.column).search(/\S|$/); + session.doc.removeInLine(cursor.row, cursor.column, cursor.column + d); + } + } + this.clearSelection(); + + var start = cursor.column; + var lineState = session.getState(cursor.row); + var line = session.getLine(cursor.row); + var shouldOutdent = mode.checkOutdent(lineState, line, text); + var end = session.insert(cursor, text); + + if (transform && transform.selection) { + if (transform.selection.length == 2) { // Transform relative to the current column + this.selection.setSelectionRange( + new Range(cursor.row, start + transform.selection[0], + cursor.row, start + transform.selection[1])); + } else { // Transform relative to the current row. + this.selection.setSelectionRange( + new Range(cursor.row + transform.selection[0], + transform.selection[1], + cursor.row + transform.selection[2], + transform.selection[3])); + } + } + + if (session.getDocument().isNewLine(text)) { + var lineIndent = mode.getNextLineIndent(lineState, line.slice(0, cursor.column), session.getTabString()); + + session.insert({row: cursor.row+1, column: 0}, lineIndent); + } + if (shouldOutdent) + mode.autoOutdent(lineState, session, cursor.row); + }; + + this.onTextInput = function(text) { + this.keyBinding.onTextInput(text); + }; + + this.onCommandKey = function(e, hashId, keyCode) { + this.keyBinding.onCommandKey(e, hashId, keyCode); + }; + this.setOverwrite = function(overwrite) { + this.session.setOverwrite(overwrite); + }; + this.getOverwrite = function() { + return this.session.getOverwrite(); + }; + this.toggleOverwrite = function() { + this.session.toggleOverwrite(); + }; + this.setScrollSpeed = function(speed) { + this.setOption("scrollSpeed", speed); + }; + this.getScrollSpeed = function() { + return this.getOption("scrollSpeed"); + }; + this.setDragDelay = function(dragDelay) { + this.setOption("dragDelay", dragDelay); + }; + this.getDragDelay = function() { + return this.getOption("dragDelay"); + }; + this.setSelectionStyle = function(val) { + this.setOption("selectionStyle", val); + }; + this.getSelectionStyle = function() { + return this.getOption("selectionStyle"); + }; + this.setHighlightActiveLine = function(shouldHighlight) { + this.setOption("highlightActiveLine", shouldHighlight); + }; + this.getHighlightActiveLine = function() { + return this.getOption("highlightActiveLine"); + }; + this.setHighlightGutterLine = function(shouldHighlight) { + this.setOption("highlightGutterLine", shouldHighlight); + }; + + this.getHighlightGutterLine = function() { + return this.getOption("highlightGutterLine"); + }; + this.setHighlightSelectedWord = function(shouldHighlight) { + this.setOption("highlightSelectedWord", shouldHighlight); + }; + this.getHighlightSelectedWord = function() { + return this.$highlightSelectedWord; + }; + + this.setAnimatedScroll = function(shouldAnimate){ + this.renderer.setAnimatedScroll(shouldAnimate); + }; + + this.getAnimatedScroll = function(){ + return this.renderer.getAnimatedScroll(); + }; + this.setShowInvisibles = function(showInvisibles) { + this.renderer.setShowInvisibles(showInvisibles); + }; + this.getShowInvisibles = function() { + return this.renderer.getShowInvisibles(); + }; + + this.setDisplayIndentGuides = function(display) { + this.renderer.setDisplayIndentGuides(display); + }; + + this.getDisplayIndentGuides = function() { + return this.renderer.getDisplayIndentGuides(); + }; + this.setShowPrintMargin = function(showPrintMargin) { + this.renderer.setShowPrintMargin(showPrintMargin); + }; + this.getShowPrintMargin = function() { + return this.renderer.getShowPrintMargin(); + }; + this.setPrintMarginColumn = function(showPrintMargin) { + this.renderer.setPrintMarginColumn(showPrintMargin); + }; + this.getPrintMarginColumn = function() { + return this.renderer.getPrintMarginColumn(); + }; + this.setReadOnly = function(readOnly) { + this.setOption("readOnly", readOnly); + }; + this.getReadOnly = function() { + return this.getOption("readOnly"); + }; + this.setBehavioursEnabled = function (enabled) { + this.setOption("behavioursEnabled", enabled); + }; + this.getBehavioursEnabled = function () { + return this.getOption("behavioursEnabled"); + }; + this.setWrapBehavioursEnabled = function (enabled) { + this.setOption("wrapBehavioursEnabled", enabled); + }; + this.getWrapBehavioursEnabled = function () { + return this.getOption("wrapBehavioursEnabled"); + }; + this.setShowFoldWidgets = function(show) { + this.setOption("showFoldWidgets", show); + + }; + this.getShowFoldWidgets = function() { + return this.getOption("showFoldWidgets"); + }; + + this.setFadeFoldWidgets = function(fade) { + this.setOption("fadeFoldWidgets", fade); + }; + + this.getFadeFoldWidgets = function() { + return this.getOption("fadeFoldWidgets"); + }; + this.remove = function(dir) { + if (this.selection.isEmpty()){ + if (dir == "left") + this.selection.selectLeft(); + else + this.selection.selectRight(); + } + + var range = this.getSelectionRange(); + if (this.getBehavioursEnabled()) { + var session = this.session; + var state = session.getState(range.start.row); + var new_range = session.getMode().transformAction(state, 'deletion', this, session, range); + + if (range.end.column === 0) { + var text = session.getTextRange(range); + if (text[text.length - 1] == "\n") { + var line = session.getLine(range.end.row); + if (/^\s+$/.test(line)) { + range.end.column = line.length; + } + } + } + if (new_range) + range = new_range; + } + + this.session.remove(range); + this.clearSelection(); + }; + this.removeWordRight = function() { + if (this.selection.isEmpty()) + this.selection.selectWordRight(); + + this.session.remove(this.getSelectionRange()); + this.clearSelection(); + }; + this.removeWordLeft = function() { + if (this.selection.isEmpty()) + this.selection.selectWordLeft(); + + this.session.remove(this.getSelectionRange()); + this.clearSelection(); + }; + this.removeToLineStart = function() { + if (this.selection.isEmpty()) + this.selection.selectLineStart(); + + this.session.remove(this.getSelectionRange()); + this.clearSelection(); + }; + this.removeToLineEnd = function() { + if (this.selection.isEmpty()) + this.selection.selectLineEnd(); + + var range = this.getSelectionRange(); + if (range.start.column == range.end.column && range.start.row == range.end.row) { + range.end.column = 0; + range.end.row++; + } + + this.session.remove(range); + this.clearSelection(); + }; + this.splitLine = function() { + if (!this.selection.isEmpty()) { + this.session.remove(this.getSelectionRange()); + this.clearSelection(); + } + + var cursor = this.getCursorPosition(); + this.insert("\n"); + this.moveCursorToPosition(cursor); + }; + this.transposeLetters = function() { + if (!this.selection.isEmpty()) { + return; + } + + var cursor = this.getCursorPosition(); + var column = cursor.column; + if (column === 0) + return; + + var line = this.session.getLine(cursor.row); + var swap, range; + if (column < line.length) { + swap = line.charAt(column) + line.charAt(column-1); + range = new Range(cursor.row, column-1, cursor.row, column+1); + } + else { + swap = line.charAt(column-1) + line.charAt(column-2); + range = new Range(cursor.row, column-2, cursor.row, column); + } + this.session.replace(range, swap); + this.session.selection.moveToPosition(range.end); + }; + this.toLowerCase = function() { + var originalRange = this.getSelectionRange(); + if (this.selection.isEmpty()) { + this.selection.selectWord(); + } + + var range = this.getSelectionRange(); + var text = this.session.getTextRange(range); + this.session.replace(range, text.toLowerCase()); + this.selection.setSelectionRange(originalRange); + }; + this.toUpperCase = function() { + var originalRange = this.getSelectionRange(); + if (this.selection.isEmpty()) { + this.selection.selectWord(); + } + + var range = this.getSelectionRange(); + var text = this.session.getTextRange(range); + this.session.replace(range, text.toUpperCase()); + this.selection.setSelectionRange(originalRange); + }; + this.indent = function() { + var session = this.session; + var range = this.getSelectionRange(); + + if (range.start.row < range.end.row) { + var rows = this.$getSelectedRows(); + session.indentRows(rows.first, rows.last, "\t"); + return; + } else if (range.start.column < range.end.column) { + var text = session.getTextRange(range); + if (!/^\s+$/.test(text)) { + var rows = this.$getSelectedRows(); + session.indentRows(rows.first, rows.last, "\t"); + return; + } + } + + var line = session.getLine(range.start.row); + var position = range.start; + var size = session.getTabSize(); + var column = session.documentToScreenColumn(position.row, position.column); + + if (this.session.getUseSoftTabs()) { + var count = (size - column % size); + var indentString = lang.stringRepeat(" ", count); + } else { + var count = column % size; + while (line[range.start.column - 1] == " " && count) { + range.start.column--; + count--; + } + this.selection.setSelectionRange(range); + indentString = "\t"; + } + return this.insert(indentString); + }; + this.blockIndent = function() { + var rows = this.$getSelectedRows(); + this.session.indentRows(rows.first, rows.last, "\t"); + }; + this.blockOutdent = function() { + var selection = this.session.getSelection(); + this.session.outdentRows(selection.getRange()); + }; + this.sortLines = function() { + var rows = this.$getSelectedRows(); + var session = this.session; + + var lines = []; + for (var i = rows.first; i <= rows.last; i++) + lines.push(session.getLine(i)); + + lines.sort(function(a, b) { + if (a.toLowerCase() < b.toLowerCase()) return -1; + if (a.toLowerCase() > b.toLowerCase()) return 1; + return 0; + }); + + var deleteRange = new Range(0, 0, 0, 0); + for (var i = rows.first; i <= rows.last; i++) { + var line = session.getLine(i); + deleteRange.start.row = i; + deleteRange.end.row = i; + deleteRange.end.column = line.length; + session.replace(deleteRange, lines[i-rows.first]); + } + }; + this.toggleCommentLines = function() { + var state = this.session.getState(this.getCursorPosition().row); + var rows = this.$getSelectedRows(); + this.session.getMode().toggleCommentLines(state, this.session, rows.first, rows.last); + }; + + this.toggleBlockComment = function() { + var cursor = this.getCursorPosition(); + var state = this.session.getState(cursor.row); + var range = this.getSelectionRange(); + this.session.getMode().toggleBlockComment(state, this.session, range, cursor); + }; + this.getNumberAt = function(row, column) { + var _numberRx = /[\-]?[0-9]+(?:\.[0-9]+)?/g; + _numberRx.lastIndex = 0; + + var s = this.session.getLine(row); + while (_numberRx.lastIndex < column) { + var m = _numberRx.exec(s); + if(m.index <= column && m.index+m[0].length >= column){ + var number = { + value: m[0], + start: m.index, + end: m.index+m[0].length + }; + return number; + } + } + return null; + }; + this.modifyNumber = function(amount) { + var row = this.selection.getCursor().row; + var column = this.selection.getCursor().column; + var charRange = new Range(row, column-1, row, column); + + var c = this.session.getTextRange(charRange); + if (!isNaN(parseFloat(c)) && isFinite(c)) { + var nr = this.getNumberAt(row, column); + if (nr) { + var fp = nr.value.indexOf(".") >= 0 ? nr.start + nr.value.indexOf(".") + 1 : nr.end; + var decimals = nr.start + nr.value.length - fp; + + var t = parseFloat(nr.value); + t *= Math.pow(10, decimals); + + + if(fp !== nr.end && column < fp){ + amount *= Math.pow(10, nr.end - column - 1); + } else { + amount *= Math.pow(10, nr.end - column); + } + + t += amount; + t /= Math.pow(10, decimals); + var nnr = t.toFixed(decimals); + var replaceRange = new Range(row, nr.start, row, nr.end); + this.session.replace(replaceRange, nnr); + this.moveCursorTo(row, Math.max(nr.start +1, column + nnr.length - nr.value.length)); + + } + } + }; + this.removeLines = function() { + var rows = this.$getSelectedRows(); + this.session.removeFullLines(rows.first, rows.last); + this.clearSelection(); + }; + + this.duplicateSelection = function() { + var sel = this.selection; + var doc = this.session; + var range = sel.getRange(); + var reverse = sel.isBackwards(); + if (range.isEmpty()) { + var row = range.start.row; + doc.duplicateLines(row, row); + } else { + var point = reverse ? range.start : range.end; + var endPoint = doc.insert(point, doc.getTextRange(range), false); + range.start = point; + range.end = endPoint; + + sel.setSelectionRange(range, reverse); + } + }; + this.moveLinesDown = function() { + this.$moveLines(1, false); + }; + this.moveLinesUp = function() { + this.$moveLines(-1, false); + }; + this.moveText = function(range, toPosition, copy) { + return this.session.moveText(range, toPosition, copy); + }; + this.copyLinesUp = function() { + this.$moveLines(-1, true); + }; + this.copyLinesDown = function() { + this.$moveLines(1, true); + }; + this.$moveLines = function(dir, copy) { + var rows, moved; + var selection = this.selection; + if (!selection.inMultiSelectMode || this.inVirtualSelectionMode) { + var range = selection.toOrientedRange(); + rows = this.$getSelectedRows(range); + moved = this.session.$moveLines(rows.first, rows.last, copy ? 0 : dir); + if (copy && dir == -1) moved = 0; + range.moveBy(moved, 0); + selection.fromOrientedRange(range); + } else { + var ranges = selection.rangeList.ranges; + selection.rangeList.detach(this.session); + this.inVirtualSelectionMode = true; + + var diff = 0; + var totalDiff = 0; + var l = ranges.length; + for (var i = 0; i < l; i++) { + var rangeIndex = i; + ranges[i].moveBy(diff, 0); + rows = this.$getSelectedRows(ranges[i]); + var first = rows.first; + var last = rows.last; + while (++i < l) { + if (totalDiff) ranges[i].moveBy(totalDiff, 0); + var subRows = this.$getSelectedRows(ranges[i]); + if (copy && subRows.first != last) + break; + else if (!copy && subRows.first > last + 1) + break; + last = subRows.last; + } + i--; + diff = this.session.$moveLines(first, last, copy ? 0 : dir); + if (copy && dir == -1) rangeIndex = i + 1; + while (rangeIndex <= i) { + ranges[rangeIndex].moveBy(diff, 0); + rangeIndex++; + } + if (!copy) diff = 0; + totalDiff += diff; + } + + selection.fromOrientedRange(selection.ranges[0]); + selection.rangeList.attach(this.session); + this.inVirtualSelectionMode = false; + } + }; + this.$getSelectedRows = function(range) { + range = (range || this.getSelectionRange()).collapseRows(); + + return { + first: this.session.getRowFoldStart(range.start.row), + last: this.session.getRowFoldEnd(range.end.row) + }; + }; + + this.onCompositionStart = function(text) { + this.renderer.showComposition(this.getCursorPosition()); + }; + + this.onCompositionUpdate = function(text) { + this.renderer.setCompositionText(text); + }; + + this.onCompositionEnd = function() { + this.renderer.hideComposition(); + }; + this.getFirstVisibleRow = function() { + return this.renderer.getFirstVisibleRow(); + }; + this.getLastVisibleRow = function() { + return this.renderer.getLastVisibleRow(); + }; + this.isRowVisible = function(row) { + return (row >= this.getFirstVisibleRow() && row <= this.getLastVisibleRow()); + }; + this.isRowFullyVisible = function(row) { + return (row >= this.renderer.getFirstFullyVisibleRow() && row <= this.renderer.getLastFullyVisibleRow()); + }; + this.$getVisibleRowCount = function() { + return this.renderer.getScrollBottomRow() - this.renderer.getScrollTopRow() + 1; + }; + + this.$moveByPage = function(dir, select) { + var renderer = this.renderer; + var config = this.renderer.layerConfig; + var rows = dir * Math.floor(config.height / config.lineHeight); + + this.$blockScrolling++; + if (select === true) { + this.selection.$moveSelection(function(){ + this.moveCursorBy(rows, 0); + }); + } else if (select === false) { + this.selection.moveCursorBy(rows, 0); + this.selection.clearSelection(); + } + this.$blockScrolling--; + + var scrollTop = renderer.scrollTop; + + renderer.scrollBy(0, rows * config.lineHeight); + if (select != null) + renderer.scrollCursorIntoView(null, 0.5); + + renderer.animateScrolling(scrollTop); + }; + this.selectPageDown = function() { + this.$moveByPage(1, true); + }; + this.selectPageUp = function() { + this.$moveByPage(-1, true); + }; + this.gotoPageDown = function() { + this.$moveByPage(1, false); + }; + this.gotoPageUp = function() { + this.$moveByPage(-1, false); + }; + this.scrollPageDown = function() { + this.$moveByPage(1); + }; + this.scrollPageUp = function() { + this.$moveByPage(-1); + }; + this.scrollToRow = function(row) { + this.renderer.scrollToRow(row); + }; + this.scrollToLine = function(line, center, animate, callback) { + this.renderer.scrollToLine(line, center, animate, callback); + }; + this.centerSelection = function() { + var range = this.getSelectionRange(); + var pos = { + row: Math.floor(range.start.row + (range.end.row - range.start.row) / 2), + column: Math.floor(range.start.column + (range.end.column - range.start.column) / 2) + }; + this.renderer.alignCursor(pos, 0.5); + }; + this.getCursorPosition = function() { + return this.selection.getCursor(); + }; + this.getCursorPositionScreen = function() { + return this.session.documentToScreenPosition(this.getCursorPosition()); + }; + this.getSelectionRange = function() { + return this.selection.getRange(); + }; + this.selectAll = function() { + this.$blockScrolling += 1; + this.selection.selectAll(); + this.$blockScrolling -= 1; + }; + this.clearSelection = function() { + this.selection.clearSelection(); + }; + this.moveCursorTo = function(row, column) { + this.selection.moveCursorTo(row, column); + }; + this.moveCursorToPosition = function(pos) { + this.selection.moveCursorToPosition(pos); + }; + this.jumpToMatching = function(select, expand) { + var cursor = this.getCursorPosition(); + var iterator = new TokenIterator(this.session, cursor.row, cursor.column); + var prevToken = iterator.getCurrentToken(); + var token = prevToken || iterator.stepForward(); + + if (!token) return; + var matchType; + var found = false; + var depth = {}; + var i = cursor.column - token.start; + var bracketType; + var brackets = { + ")": "(", + "(": "(", + "]": "[", + "[": "[", + "{": "{", + "}": "{" + }; + + do { + if (token.value.match(/[{}()\[\]]/g)) { + for (; i < token.value.length && !found; i++) { + if (!brackets[token.value[i]]) { + continue; + } + + bracketType = brackets[token.value[i]] + '.' + token.type.replace("rparen", "lparen"); + + if (isNaN(depth[bracketType])) { + depth[bracketType] = 0; + } + + switch (token.value[i]) { + case '(': + case '[': + case '{': + depth[bracketType]++; + break; + case ')': + case ']': + case '}': + depth[bracketType]--; + + if (depth[bracketType] === -1) { + matchType = 'bracket'; + found = true; + } + break; + } + } + } + else if (token && token.type.indexOf('tag-name') !== -1) { + if (isNaN(depth[token.value])) { + depth[token.value] = 0; + } + + if (prevToken.value === '<') { + depth[token.value]++; + } + else if (prevToken.value === '= 0; --i) { + if(this.$tryReplace(ranges[i], replacement)) { + replaced++; + } + } + + this.selection.setSelectionRange(selection); + this.$blockScrolling -= 1; + + return replaced; + }; + + this.$tryReplace = function(range, replacement) { + var input = this.session.getTextRange(range); + replacement = this.$search.replace(input, replacement); + if (replacement !== null) { + range.end = this.session.replace(range, replacement); + return range; + } else { + return null; + } + }; + this.getLastSearchOptions = function() { + return this.$search.getOptions(); + }; + this.find = function(needle, options, animate) { + if (!options) + options = {}; + + if (typeof needle == "string" || needle instanceof RegExp) + options.needle = needle; + else if (typeof needle == "object") + oop.mixin(options, needle); + + var range = this.selection.getRange(); + if (options.needle == null) { + needle = this.session.getTextRange(range) + || this.$search.$options.needle; + if (!needle) { + range = this.session.getWordRange(range.start.row, range.start.column); + needle = this.session.getTextRange(range); + } + this.$search.set({needle: needle}); + } + + this.$search.set(options); + if (!options.start) + this.$search.set({start: range}); + + var newRange = this.$search.find(this.session); + if (options.preventScroll) + return newRange; + if (newRange) { + this.revealRange(newRange, animate); + return newRange; + } + if (options.backwards) + range.start = range.end; + else + range.end = range.start; + this.selection.setRange(range); + }; + this.findNext = function(options, animate) { + this.find({skipCurrent: true, backwards: false}, options, animate); + }; + this.findPrevious = function(options, animate) { + this.find(options, {skipCurrent: true, backwards: true}, animate); + }; + + this.revealRange = function(range, animate) { + this.$blockScrolling += 1; + this.session.unfold(range); + this.selection.setSelectionRange(range); + this.$blockScrolling -= 1; + + var scrollTop = this.renderer.scrollTop; + this.renderer.scrollSelectionIntoView(range.start, range.end, 0.5); + if (animate !== false) + this.renderer.animateScrolling(scrollTop); + }; + this.undo = function() { + this.$blockScrolling++; + this.session.getUndoManager().undo(); + this.$blockScrolling--; + this.renderer.scrollCursorIntoView(null, 0.5); + }; + this.redo = function() { + this.$blockScrolling++; + this.session.getUndoManager().redo(); + this.$blockScrolling--; + this.renderer.scrollCursorIntoView(null, 0.5); + }; + this.destroy = function() { + this.renderer.destroy(); + this._signal("destroy", this); + if (this.session) { + this.session.destroy(); + } + }; + this.setAutoScrollEditorIntoView = function(enable) { + if (!enable) + return; + var rect; + var self = this; + var shouldScroll = false; + if (!this.$scrollAnchor) + this.$scrollAnchor = document.createElement("div"); + var scrollAnchor = this.$scrollAnchor; + scrollAnchor.style.cssText = "position:absolute"; + this.container.insertBefore(scrollAnchor, this.container.firstChild); + var onChangeSelection = this.on("changeSelection", function() { + shouldScroll = true; + }); + var onBeforeRender = this.renderer.on("beforeRender", function() { + if (shouldScroll) + rect = self.renderer.container.getBoundingClientRect(); + }); + var onAfterRender = this.renderer.on("afterRender", function() { + if (shouldScroll && rect && (self.isFocused() + || self.searchBox && self.searchBox.isFocused()) + ) { + var renderer = self.renderer; + var pos = renderer.$cursorLayer.$pixelPos; + var config = renderer.layerConfig; + var top = pos.top - config.offset; + if (pos.top >= 0 && top + rect.top < 0) { + shouldScroll = true; + } else if (pos.top < config.height && + pos.top + rect.top + config.lineHeight > window.innerHeight) { + shouldScroll = false; + } else { + shouldScroll = null; + } + if (shouldScroll != null) { + scrollAnchor.style.top = top + "px"; + scrollAnchor.style.left = pos.left + "px"; + scrollAnchor.style.height = config.lineHeight + "px"; + scrollAnchor.scrollIntoView(shouldScroll); + } + shouldScroll = rect = null; + } + }); + this.setAutoScrollEditorIntoView = function(enable) { + if (enable) + return; + delete this.setAutoScrollEditorIntoView; + this.off("changeSelection", onChangeSelection); + this.renderer.off("afterRender", onAfterRender); + this.renderer.off("beforeRender", onBeforeRender); + }; + }; + + + this.$resetCursorStyle = function() { + var style = this.$cursorStyle || "ace"; + var cursorLayer = this.renderer.$cursorLayer; + if (!cursorLayer) + return; + cursorLayer.setSmoothBlinking(/smooth/.test(style)); + cursorLayer.isBlinking = !this.$readOnly && style != "wide"; + dom.setCssClass(cursorLayer.element, "ace_slim-cursors", /slim/.test(style)); + }; + +}).call(Editor.prototype); + + + +config.defineOptions(Editor.prototype, "editor", { + selectionStyle: { + set: function(style) { + this.onSelectionChange(); + this._signal("changeSelectionStyle", {data: style}); + }, + initialValue: "line" + }, + highlightActiveLine: { + set: function() {this.$updateHighlightActiveLine();}, + initialValue: true + }, + highlightSelectedWord: { + set: function(shouldHighlight) {this.$onSelectionChange();}, + initialValue: true + }, + readOnly: { + set: function(readOnly) { + this.$resetCursorStyle(); + }, + initialValue: false + }, + cursorStyle: { + set: function(val) { this.$resetCursorStyle(); }, + values: ["ace", "slim", "smooth", "wide"], + initialValue: "ace" + }, + mergeUndoDeltas: { + values: [false, true, "always"], + initialValue: true + }, + behavioursEnabled: {initialValue: true}, + wrapBehavioursEnabled: {initialValue: true}, + autoScrollEditorIntoView: { + set: function(val) {this.setAutoScrollEditorIntoView(val);} + }, + keyboardHandler: { + set: function(val) { this.setKeyboardHandler(val); }, + get: function() { return this.keybindingId; }, + handlesSet: true + }, + + hScrollBarAlwaysVisible: "renderer", + vScrollBarAlwaysVisible: "renderer", + highlightGutterLine: "renderer", + animatedScroll: "renderer", + showInvisibles: "renderer", + showPrintMargin: "renderer", + printMarginColumn: "renderer", + printMargin: "renderer", + fadeFoldWidgets: "renderer", + showFoldWidgets: "renderer", + showLineNumbers: "renderer", + showGutter: "renderer", + displayIndentGuides: "renderer", + fontSize: "renderer", + fontFamily: "renderer", + maxLines: "renderer", + minLines: "renderer", + scrollPastEnd: "renderer", + fixedWidthGutter: "renderer", + theme: "renderer", + + scrollSpeed: "$mouseHandler", + dragDelay: "$mouseHandler", + dragEnabled: "$mouseHandler", + focusTimout: "$mouseHandler", + tooltipFollowsMouse: "$mouseHandler", + + firstLineNumber: "session", + overwrite: "session", + newLineMode: "session", + useWorker: "session", + useSoftTabs: "session", + tabSize: "session", + wrap: "session", + indentedSoftWrap: "session", + foldStyle: "session", + mode: "session" +}); + +exports.Editor = Editor; +}); + +ace.define("ace/undomanager",["require","exports","module"], function(acequire, exports, module) { +"use strict"; +var UndoManager = function() { + this.reset(); +}; + +(function() { + this.execute = function(options) { + var deltaSets = options.args[0]; + this.$doc = options.args[1]; + if (options.merge && this.hasUndo()){ + this.dirtyCounter--; + deltaSets = this.$undoStack.pop().concat(deltaSets); + } + this.$undoStack.push(deltaSets); + this.$redoStack = []; + if (this.dirtyCounter < 0) { + this.dirtyCounter = NaN; + } + this.dirtyCounter++; + }; + this.undo = function(dontSelect) { + var deltaSets = this.$undoStack.pop(); + var undoSelectionRange = null; + if (deltaSets) { + undoSelectionRange = this.$doc.undoChanges(deltaSets, dontSelect); + this.$redoStack.push(deltaSets); + this.dirtyCounter--; + } + + return undoSelectionRange; + }; + this.redo = function(dontSelect) { + var deltaSets = this.$redoStack.pop(); + var redoSelectionRange = null; + if (deltaSets) { + redoSelectionRange = + this.$doc.redoChanges(this.$deserializeDeltas(deltaSets), dontSelect); + this.$undoStack.push(deltaSets); + this.dirtyCounter++; + } + return redoSelectionRange; + }; + this.reset = function() { + this.$undoStack = []; + this.$redoStack = []; + this.dirtyCounter = 0; + }; + this.hasUndo = function() { + return this.$undoStack.length > 0; + }; + this.hasRedo = function() { + return this.$redoStack.length > 0; + }; + this.markClean = function() { + this.dirtyCounter = 0; + }; + this.isClean = function() { + return this.dirtyCounter === 0; + }; + this.$serializeDeltas = function(deltaSets) { + return cloneDeltaSetsObj(deltaSets, $serializeDelta); + }; + this.$deserializeDeltas = function(deltaSets) { + return cloneDeltaSetsObj(deltaSets, $deserializeDelta); + }; + + function $serializeDelta(delta){ + return { + action: delta.action, + start: delta.start, + end: delta.end, + lines: delta.lines.length == 1 ? null : delta.lines, + text: delta.lines.length == 1 ? delta.lines[0] : null + }; + } + + function $deserializeDelta(delta) { + return { + action: delta.action, + start: delta.start, + end: delta.end, + lines: delta.lines || [delta.text] + }; + } + + function cloneDeltaSetsObj(deltaSets_old, fnGetModifiedDelta) { + var deltaSets_new = new Array(deltaSets_old.length); + for (var i = 0; i < deltaSets_old.length; i++) { + var deltaSet_old = deltaSets_old[i]; + var deltaSet_new = { group: deltaSet_old.group, deltas: new Array(deltaSet_old.length)}; + + for (var j = 0; j < deltaSet_old.deltas.length; j++) { + var delta_old = deltaSet_old.deltas[j]; + deltaSet_new.deltas[j] = fnGetModifiedDelta(delta_old); + } + + deltaSets_new[i] = deltaSet_new; + } + return deltaSets_new; + } + +}).call(UndoManager.prototype); + +exports.UndoManager = UndoManager; +}); + +ace.define("ace/layer/gutter",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var dom = acequire("../lib/dom"); +var oop = acequire("../lib/oop"); +var lang = acequire("../lib/lang"); +var EventEmitter = acequire("../lib/event_emitter").EventEmitter; + +var Gutter = function(parentEl) { + this.element = dom.createElement("div"); + this.element.className = "ace_layer ace_gutter-layer"; + parentEl.appendChild(this.element); + this.setShowFoldWidgets(this.$showFoldWidgets); + + this.gutterWidth = 0; + + this.$annotations = []; + this.$updateAnnotations = this.$updateAnnotations.bind(this); + + this.$cells = []; +}; + +(function() { + + oop.implement(this, EventEmitter); + + this.setSession = function(session) { + if (this.session) + this.session.removeEventListener("change", this.$updateAnnotations); + this.session = session; + if (session) + session.on("change", this.$updateAnnotations); + }; + + this.addGutterDecoration = function(row, className){ + if (window.console) + console.warn && console.warn("deprecated use session.addGutterDecoration"); + this.session.addGutterDecoration(row, className); + }; + + this.removeGutterDecoration = function(row, className){ + if (window.console) + console.warn && console.warn("deprecated use session.removeGutterDecoration"); + this.session.removeGutterDecoration(row, className); + }; + + this.setAnnotations = function(annotations) { + this.$annotations = []; + for (var i = 0; i < annotations.length; i++) { + var annotation = annotations[i]; + var row = annotation.row; + var rowInfo = this.$annotations[row]; + if (!rowInfo) + rowInfo = this.$annotations[row] = {text: []}; + + var annoText = annotation.text; + annoText = annoText ? lang.escapeHTML(annoText) : annotation.html || ""; + + if (rowInfo.text.indexOf(annoText) === -1) + rowInfo.text.push(annoText); + + var type = annotation.type; + if (type == "error") + rowInfo.className = " ace_error"; + else if (type == "warning" && rowInfo.className != " ace_error") + rowInfo.className = " ace_warning"; + else if (type == "info" && (!rowInfo.className)) + rowInfo.className = " ace_info"; + } + }; + + this.$updateAnnotations = function (delta) { + if (!this.$annotations.length) + return; + var firstRow = delta.start.row; + var len = delta.end.row - firstRow; + if (len === 0) { + } else if (delta.action == 'remove') { + this.$annotations.splice(firstRow, len + 1, null); + } else { + var args = new Array(len + 1); + args.unshift(firstRow, 1); + this.$annotations.splice.apply(this.$annotations, args); + } + }; + + this.update = function(config) { + var session = this.session; + var firstRow = config.firstRow; + var lastRow = Math.min(config.lastRow + config.gutterOffset, // needed to compensate for hor scollbar + session.getLength() - 1); + var fold = session.getNextFoldLine(firstRow); + var foldStart = fold ? fold.start.row : Infinity; + var foldWidgets = this.$showFoldWidgets && session.foldWidgets; + var breakpoints = session.$breakpoints; + var decorations = session.$decorations; + var firstLineNumber = session.$firstLineNumber; + var lastLineNumber = 0; + + var gutterRenderer = session.gutterRenderer || this.$renderer; + + var cell = null; + var index = -1; + var row = firstRow; + while (true) { + if (row > foldStart) { + row = fold.end.row + 1; + fold = session.getNextFoldLine(row, fold); + foldStart = fold ? fold.start.row : Infinity; + } + if (row > lastRow) { + while (this.$cells.length > index + 1) { + cell = this.$cells.pop(); + this.element.removeChild(cell.element); + } + break; + } + + cell = this.$cells[++index]; + if (!cell) { + cell = {element: null, textNode: null, foldWidget: null}; + cell.element = dom.createElement("div"); + cell.textNode = document.createTextNode(''); + cell.element.appendChild(cell.textNode); + this.element.appendChild(cell.element); + this.$cells[index] = cell; + } + + var className = "ace_gutter-cell "; + if (breakpoints[row]) + className += breakpoints[row]; + if (decorations[row]) + className += decorations[row]; + if (this.$annotations[row]) + className += this.$annotations[row].className; + if (cell.element.className != className) + cell.element.className = className; + + var height = session.getRowLength(row) * config.lineHeight + "px"; + if (height != cell.element.style.height) + cell.element.style.height = height; + + if (foldWidgets) { + var c = foldWidgets[row]; + if (c == null) + c = foldWidgets[row] = session.getFoldWidget(row); + } + + if (c) { + if (!cell.foldWidget) { + cell.foldWidget = dom.createElement("span"); + cell.element.appendChild(cell.foldWidget); + } + var className = "ace_fold-widget ace_" + c; + if (c == "start" && row == foldStart && row < fold.end.row) + className += " ace_closed"; + else + className += " ace_open"; + if (cell.foldWidget.className != className) + cell.foldWidget.className = className; + + var height = config.lineHeight + "px"; + if (cell.foldWidget.style.height != height) + cell.foldWidget.style.height = height; + } else { + if (cell.foldWidget) { + cell.element.removeChild(cell.foldWidget); + cell.foldWidget = null; + } + } + + var text = lastLineNumber = gutterRenderer + ? gutterRenderer.getText(session, row) + : row + firstLineNumber; + if (text !== cell.textNode.data) + cell.textNode.data = text; + + row++; + } + + this.element.style.height = config.minHeight + "px"; + + if (this.$fixedWidth || session.$useWrapMode) + lastLineNumber = session.getLength() + firstLineNumber; + + var gutterWidth = gutterRenderer + ? gutterRenderer.getWidth(session, lastLineNumber, config) + : lastLineNumber.toString().length * config.characterWidth; + + var padding = this.$padding || this.$computePadding(); + gutterWidth += padding.left + padding.right; + if (gutterWidth !== this.gutterWidth && !isNaN(gutterWidth)) { + this.gutterWidth = gutterWidth; + this.element.style.width = Math.ceil(this.gutterWidth) + "px"; + this._emit("changeGutterWidth", gutterWidth); + } + }; + + this.$fixedWidth = false; + + this.$showLineNumbers = true; + this.$renderer = ""; + this.setShowLineNumbers = function(show) { + this.$renderer = !show && { + getWidth: function() {return "";}, + getText: function() {return "";} + }; + }; + + this.getShowLineNumbers = function() { + return this.$showLineNumbers; + }; + + this.$showFoldWidgets = true; + this.setShowFoldWidgets = function(show) { + if (show) + dom.addCssClass(this.element, "ace_folding-enabled"); + else + dom.removeCssClass(this.element, "ace_folding-enabled"); + + this.$showFoldWidgets = show; + this.$padding = null; + }; + + this.getShowFoldWidgets = function() { + return this.$showFoldWidgets; + }; + + this.$computePadding = function() { + if (!this.element.firstChild) + return {left: 0, right: 0}; + var style = dom.computedStyle(this.element.firstChild); + this.$padding = {}; + this.$padding.left = parseInt(style.paddingLeft) + 1 || 0; + this.$padding.right = parseInt(style.paddingRight) || 0; + return this.$padding; + }; + + this.getRegion = function(point) { + var padding = this.$padding || this.$computePadding(); + var rect = this.element.getBoundingClientRect(); + if (point.x < padding.left + rect.left) + return "markers"; + if (this.$showFoldWidgets && point.x > rect.right - padding.right) + return "foldWidgets"; + }; + +}).call(Gutter.prototype); + +exports.Gutter = Gutter; + +}); + +ace.define("ace/layer/marker",["require","exports","module","ace/range","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; +var dom = acequire("../lib/dom"); + +var Marker = function(parentEl) { + this.element = dom.createElement("div"); + this.element.className = "ace_layer ace_marker-layer"; + parentEl.appendChild(this.element); +}; + +(function() { + + this.$padding = 0; + + this.setPadding = function(padding) { + this.$padding = padding; + }; + this.setSession = function(session) { + this.session = session; + }; + + this.setMarkers = function(markers) { + this.markers = markers; + }; + + this.update = function(config) { + if (!config) return; + + this.config = config; + + + var html = []; + for (var key in this.markers) { + var marker = this.markers[key]; + + if (!marker.range) { + marker.update(html, this, this.session, config); + continue; + } + + var range = marker.range.clipRows(config.firstRow, config.lastRow); + if (range.isEmpty()) continue; + + range = range.toScreenRange(this.session); + if (marker.renderer) { + var top = this.$getTop(range.start.row, config); + var left = this.$padding + (this.session.$bidiHandler.isBidiRow(range.start.row) + ? this.session.$bidiHandler.getPosLeft(range.start.column) + : range.start.column * config.characterWidth); + marker.renderer(html, range, left, top, config); + } else if (marker.type == "fullLine") { + this.drawFullLineMarker(html, range, marker.clazz, config); + } else if (marker.type == "screenLine") { + this.drawScreenLineMarker(html, range, marker.clazz, config); + } else if (range.isMultiLine()) { + if (marker.type == "text") + this.drawTextMarker(html, range, marker.clazz, config); + else + this.drawMultiLineMarker(html, range, marker.clazz, config); + } else { + if (this.session.$bidiHandler.isBidiRow(range.start.row)) { + this.drawBidiSingleLineMarker(html, range, marker.clazz + " ace_start" + " ace_br15", config); + } else { + this.drawSingleLineMarker(html, range, marker.clazz + " ace_start" + " ace_br15", config); + } + } + } + this.element.innerHTML = html.join(""); + }; + + this.$getTop = function(row, layerConfig) { + return (row - layerConfig.firstRowScreen) * layerConfig.lineHeight; + }; + + function getBorderClass(tl, tr, br, bl) { + return (tl ? 1 : 0) | (tr ? 2 : 0) | (br ? 4 : 0) | (bl ? 8 : 0); + } + this.drawTextMarker = function(stringBuilder, range, clazz, layerConfig, extraStyle) { + var session = this.session; + var start = range.start.row; + var end = range.end.row; + var row = start; + var prev = 0; + var curr = 0; + var next = session.getScreenLastRowColumn(row); + var clazzModified = null; + var lineRange = new Range(row, range.start.column, row, curr); + for (; row <= end; row++) { + lineRange.start.row = lineRange.end.row = row; + lineRange.start.column = row == start ? range.start.column : session.getRowWrapIndent(row); + lineRange.end.column = next; + prev = curr; + curr = next; + next = row + 1 < end ? session.getScreenLastRowColumn(row + 1) : row == end ? 0 : range.end.column; + clazzModified = clazz + (row == start ? " ace_start" : "") + " ace_br" + + getBorderClass(row == start || row == start + 1 && range.start.column, prev < curr, curr > next, row == end); + + if (this.session.$bidiHandler.isBidiRow(row)) { + this.drawBidiSingleLineMarker(stringBuilder, lineRange, clazzModified, + layerConfig, row == end ? 0 : 1, extraStyle); + } else { + this.drawSingleLineMarker(stringBuilder, lineRange, clazzModified, + layerConfig, row == end ? 0 : 1, extraStyle); + } + } + }; + this.drawMultiLineMarker = function(stringBuilder, range, clazz, config, extraStyle) { + var padding = this.$padding; + var height, top, left; + extraStyle = extraStyle || ""; + if (this.session.$bidiHandler.isBidiRow(range.start.row)) { + var range1 = range.clone(); + range1.end.row = range1.start.row; + range1.end.column = this.session.getLine(range1.start.row).length; + this.drawBidiSingleLineMarker(stringBuilder, range1, clazz + " ace_br1 ace_start", config, null, extraStyle); + } else { + height = config.lineHeight; + top = this.$getTop(range.start.row, config); + left = padding + range.start.column * config.characterWidth; + stringBuilder.push( + "
" + ); + } + if (this.session.$bidiHandler.isBidiRow(range.end.row)) { + var range1 = range.clone(); + range1.start.row = range1.end.row; + range1.start.column = 0; + this.drawBidiSingleLineMarker(stringBuilder, range1, clazz + " ace_br12", config, null, extraStyle); + } else { + var width = range.end.column * config.characterWidth; + height = config.lineHeight; + top = this.$getTop(range.end.row, config); + stringBuilder.push( + "
" + ); + } + height = (range.end.row - range.start.row - 1) * config.lineHeight; + if (height <= 0) + return; + top = this.$getTop(range.start.row + 1, config); + + var radiusClass = (range.start.column ? 1 : 0) | (range.end.column ? 0 : 8); + + stringBuilder.push( + "
" + ); + }; + this.drawSingleLineMarker = function(stringBuilder, range, clazz, config, extraLength, extraStyle) { + var height = config.lineHeight; + var width = (range.end.column + (extraLength || 0) - range.start.column) * config.characterWidth; + + var top = this.$getTop(range.start.row, config); + var left = this.$padding + range.start.column * config.characterWidth; + + stringBuilder.push( + "
" + ); + }; + this.drawBidiSingleLineMarker = function(stringBuilder, range, clazz, config, extraLength, extraStyle) { + var height = config.lineHeight, top = this.$getTop(range.start.row, config), padding = this.$padding; + var selections = this.session.$bidiHandler.getSelections(range.start.column, range.end.column); + + selections.forEach(function(selection) { + stringBuilder.push( + "
" + ); + }); + }; + + this.drawFullLineMarker = function(stringBuilder, range, clazz, config, extraStyle) { + var top = this.$getTop(range.start.row, config); + var height = config.lineHeight; + if (range.start.row != range.end.row) + height += this.$getTop(range.end.row, config) - top; + + stringBuilder.push( + "
" + ); + }; + + this.drawScreenLineMarker = function(stringBuilder, range, clazz, config, extraStyle) { + var top = this.$getTop(range.start.row, config); + var height = config.lineHeight; + + stringBuilder.push( + "
" + ); + }; + +}).call(Marker.prototype); + +exports.Marker = Marker; + +}); + +ace.define("ace/layer/text",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var dom = acequire("../lib/dom"); +var lang = acequire("../lib/lang"); +var useragent = acequire("../lib/useragent"); +var EventEmitter = acequire("../lib/event_emitter").EventEmitter; + +var Text = function(parentEl) { + this.element = dom.createElement("div"); + this.element.className = "ace_layer ace_text-layer"; + parentEl.appendChild(this.element); + this.$updateEolChar = this.$updateEolChar.bind(this); +}; + +(function() { + + oop.implement(this, EventEmitter); + + this.EOF_CHAR = "\xB6"; + this.EOL_CHAR_LF = "\xAC"; + this.EOL_CHAR_CRLF = "\xa4"; + this.EOL_CHAR = this.EOL_CHAR_LF; + this.TAB_CHAR = "\u2014"; //"\u21E5"; + this.SPACE_CHAR = "\xB7"; + this.$padding = 0; + + this.$updateEolChar = function() { + var EOL_CHAR = this.session.doc.getNewLineCharacter() == "\n" + ? this.EOL_CHAR_LF + : this.EOL_CHAR_CRLF; + if (this.EOL_CHAR != EOL_CHAR) { + this.EOL_CHAR = EOL_CHAR; + return true; + } + }; + + this.setPadding = function(padding) { + this.$padding = padding; + this.element.style.padding = "0 " + padding + "px"; + }; + + this.getLineHeight = function() { + return this.$fontMetrics.$characterSize.height || 0; + }; + + this.getCharacterWidth = function() { + return this.$fontMetrics.$characterSize.width || 0; + }; + + this.$setFontMetrics = function(measure) { + this.$fontMetrics = measure; + this.$fontMetrics.on("changeCharacterSize", function(e) { + this._signal("changeCharacterSize", e); + }.bind(this)); + this.$pollSizeChanges(); + }; + + this.checkForSizeChanges = function() { + this.$fontMetrics.checkForSizeChanges(); + }; + this.$pollSizeChanges = function() { + return this.$pollSizeChangesTimer = this.$fontMetrics.$pollSizeChanges(); + }; + this.setSession = function(session) { + this.session = session; + if (session) + this.$computeTabString(); + }; + + this.showInvisibles = false; + this.setShowInvisibles = function(showInvisibles) { + if (this.showInvisibles == showInvisibles) + return false; + + this.showInvisibles = showInvisibles; + this.$computeTabString(); + return true; + }; + + this.displayIndentGuides = true; + this.setDisplayIndentGuides = function(display) { + if (this.displayIndentGuides == display) + return false; + + this.displayIndentGuides = display; + this.$computeTabString(); + return true; + }; + + this.$tabStrings = []; + this.onChangeTabSize = + this.$computeTabString = function() { + var tabSize = this.session.getTabSize(); + this.tabSize = tabSize; + var tabStr = this.$tabStrings = [0]; + for (var i = 1; i < tabSize + 1; i++) { + if (this.showInvisibles) { + tabStr.push("" + + lang.stringRepeat(this.TAB_CHAR, i) + + ""); + } else { + tabStr.push(lang.stringRepeat(" ", i)); + } + } + if (this.displayIndentGuides) { + this.$indentGuideRe = /\s\S| \t|\t |\s$/; + var className = "ace_indent-guide"; + var spaceClass = ""; + var tabClass = ""; + if (this.showInvisibles) { + className += " ace_invisible"; + spaceClass = " ace_invisible_space"; + tabClass = " ace_invisible_tab"; + var spaceContent = lang.stringRepeat(this.SPACE_CHAR, this.tabSize); + var tabContent = lang.stringRepeat(this.TAB_CHAR, this.tabSize); + } else{ + var spaceContent = lang.stringRepeat(" ", this.tabSize); + var tabContent = spaceContent; + } + + this.$tabStrings[" "] = "" + spaceContent + ""; + this.$tabStrings["\t"] = "" + tabContent + ""; + } + }; + + this.updateLines = function(config, firstRow, lastRow) { + if (this.config.lastRow != config.lastRow || + this.config.firstRow != config.firstRow) { + this.scrollLines(config); + } + this.config = config; + + var first = Math.max(firstRow, config.firstRow); + var last = Math.min(lastRow, config.lastRow); + + var lineElements = this.element.childNodes; + var lineElementsIdx = 0; + + for (var row = config.firstRow; row < first; row++) { + var foldLine = this.session.getFoldLine(row); + if (foldLine) { + if (foldLine.containsRow(first)) { + first = foldLine.start.row; + break; + } else { + row = foldLine.end.row; + } + } + lineElementsIdx ++; + } + + var row = first; + var foldLine = this.session.getNextFoldLine(row); + var foldStart = foldLine ? foldLine.start.row : Infinity; + + while (true) { + if (row > foldStart) { + row = foldLine.end.row+1; + foldLine = this.session.getNextFoldLine(row, foldLine); + foldStart = foldLine ? foldLine.start.row :Infinity; + } + if (row > last) + break; + + var lineElement = lineElements[lineElementsIdx++]; + if (lineElement) { + var html = []; + this.$renderLine( + html, row, !this.$useLineGroups(), row == foldStart ? foldLine : false + ); + lineElement.style.height = config.lineHeight * this.session.getRowLength(row) + "px"; + lineElement.innerHTML = html.join(""); + } + row++; + } + }; + + this.scrollLines = function(config) { + var oldConfig = this.config; + this.config = config; + + if (!oldConfig || oldConfig.lastRow < config.firstRow) + return this.update(config); + + if (config.lastRow < oldConfig.firstRow) + return this.update(config); + + var el = this.element; + if (oldConfig.firstRow < config.firstRow) + for (var row=this.session.getFoldedRowCount(oldConfig.firstRow, config.firstRow - 1); row>0; row--) + el.removeChild(el.firstChild); + + if (oldConfig.lastRow > config.lastRow) + for (var row=this.session.getFoldedRowCount(config.lastRow + 1, oldConfig.lastRow); row>0; row--) + el.removeChild(el.lastChild); + + if (config.firstRow < oldConfig.firstRow) { + var fragment = this.$renderLinesFragment(config, config.firstRow, oldConfig.firstRow - 1); + if (el.firstChild) + el.insertBefore(fragment, el.firstChild); + else + el.appendChild(fragment); + } + + if (config.lastRow > oldConfig.lastRow) { + var fragment = this.$renderLinesFragment(config, oldConfig.lastRow + 1, config.lastRow); + el.appendChild(fragment); + } + }; + + this.$renderLinesFragment = function(config, firstRow, lastRow) { + var fragment = this.element.ownerDocument.createDocumentFragment(); + var row = firstRow; + var foldLine = this.session.getNextFoldLine(row); + var foldStart = foldLine ? foldLine.start.row : Infinity; + + while (true) { + if (row > foldStart) { + row = foldLine.end.row+1; + foldLine = this.session.getNextFoldLine(row, foldLine); + foldStart = foldLine ? foldLine.start.row : Infinity; + } + if (row > lastRow) + break; + + var container = dom.createElement("div"); + + var html = []; + this.$renderLine(html, row, false, row == foldStart ? foldLine : false); + container.innerHTML = html.join(""); + if (this.$useLineGroups()) { + container.className = 'ace_line_group'; + fragment.appendChild(container); + container.style.height = config.lineHeight * this.session.getRowLength(row) + "px"; + + } else { + while(container.firstChild) + fragment.appendChild(container.firstChild); + } + + row++; + } + return fragment; + }; + + this.update = function(config) { + this.config = config; + + var html = []; + var firstRow = config.firstRow, lastRow = config.lastRow; + + var row = firstRow; + var foldLine = this.session.getNextFoldLine(row); + var foldStart = foldLine ? foldLine.start.row : Infinity; + + while (true) { + if (row > foldStart) { + row = foldLine.end.row+1; + foldLine = this.session.getNextFoldLine(row, foldLine); + foldStart = foldLine ? foldLine.start.row :Infinity; + } + if (row > lastRow) + break; + + if (this.$useLineGroups()) + html.push("
"); + + this.$renderLine(html, row, false, row == foldStart ? foldLine : false); + + if (this.$useLineGroups()) + html.push("
"); // end the line group + + row++; + } + this.element.innerHTML = html.join(""); + }; + + this.$textToken = { + "text": true, + "rparen": true, + "lparen": true + }; + + this.$renderToken = function(stringBuilder, screenColumn, token, value) { + var self = this; + var replaceReg = /\t|&|<|>|( +)|([\x00-\x1f\x80-\xa0\xad\u1680\u180E\u2000-\u200f\u2028\u2029\u202F\u205F\u3000\uFEFF\uFFF9-\uFFFC])|[\u1100-\u115F\u11A3-\u11A7\u11FA-\u11FF\u2329-\u232A\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3000-\u303E\u3041-\u3096\u3099-\u30FF\u3105-\u312D\u3131-\u318E\u3190-\u31BA\u31C0-\u31E3\u31F0-\u321E\u3220-\u3247\u3250-\u32FE\u3300-\u4DBF\u4E00-\uA48C\uA490-\uA4C6\uA960-\uA97C\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFF01-\uFF60\uFFE0-\uFFE6]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + var replaceFunc = function(c, a, b, tabIdx, idx4) { + if (a) { + return self.showInvisibles + ? "" + lang.stringRepeat(self.SPACE_CHAR, c.length) + "" + : c; + } else if (c == "&") { + return "&"; + } else if (c == "<") { + return "<"; + } else if (c == ">") { + return ">"; + } else if (c == "\t") { + var tabSize = self.session.getScreenTabSize(screenColumn + tabIdx); + screenColumn += tabSize - 1; + return self.$tabStrings[tabSize]; + } else if (c == "\u3000") { + var classToUse = self.showInvisibles ? "ace_cjk ace_invisible ace_invisible_space" : "ace_cjk"; + var space = self.showInvisibles ? self.SPACE_CHAR : ""; + screenColumn += 1; + return "" + space + ""; + } else if (b) { + return "" + self.SPACE_CHAR + ""; + } else { + screenColumn += 1; + return "" + c + ""; + } + }; + + var output = value.replace(replaceReg, replaceFunc); + + if (!this.$textToken[token.type]) { + var classes = "ace_" + token.type.replace(/\./g, " ace_"); + var style = ""; + if (token.type == "fold") + style = " style='width:" + (token.value.length * this.config.characterWidth) + "px;' "; + stringBuilder.push("", output, ""); + } + else { + stringBuilder.push(output); + } + return screenColumn + value.length; + }; + + this.renderIndentGuide = function(stringBuilder, value, max) { + var cols = value.search(this.$indentGuideRe); + if (cols <= 0 || cols >= max) + return value; + if (value[0] == " ") { + cols -= cols % this.tabSize; + stringBuilder.push(lang.stringRepeat(this.$tabStrings[" "], cols/this.tabSize)); + return value.substr(cols); + } else if (value[0] == "\t") { + stringBuilder.push(lang.stringRepeat(this.$tabStrings["\t"], cols)); + return value.substr(cols); + } + return value; + }; + + this.$renderWrappedLine = function(stringBuilder, tokens, splits, onlyContents) { + var chars = 0; + var split = 0; + var splitChars = splits[0]; + var screenColumn = 0; + + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + var value = token.value; + if (i == 0 && this.displayIndentGuides) { + chars = value.length; + value = this.renderIndentGuide(stringBuilder, value, splitChars); + if (!value) + continue; + chars -= value.length; + } + + if (chars + value.length < splitChars) { + screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value); + chars += value.length; + } else { + while (chars + value.length >= splitChars) { + screenColumn = this.$renderToken( + stringBuilder, screenColumn, + token, value.substring(0, splitChars - chars) + ); + value = value.substring(splitChars - chars); + chars = splitChars; + + if (!onlyContents) { + stringBuilder.push("", + "
" + ); + } + + stringBuilder.push(lang.stringRepeat("\xa0", splits.indent)); + + split ++; + screenColumn = 0; + splitChars = splits[split] || Number.MAX_VALUE; + } + if (value.length != 0) { + chars += value.length; + screenColumn = this.$renderToken( + stringBuilder, screenColumn, token, value + ); + } + } + } + }; + + this.$renderSimpleLine = function(stringBuilder, tokens) { + var screenColumn = 0; + var token = tokens[0]; + var value = token.value; + if (this.displayIndentGuides) + value = this.renderIndentGuide(stringBuilder, value); + if (value) + screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value); + for (var i = 1; i < tokens.length; i++) { + token = tokens[i]; + value = token.value; + screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value); + } + }; + this.$renderLine = function(stringBuilder, row, onlyContents, foldLine) { + if (!foldLine && foldLine != false) + foldLine = this.session.getFoldLine(row); + + if (foldLine) + var tokens = this.$getFoldLineTokens(row, foldLine); + else + var tokens = this.session.getTokens(row); + + + if (!onlyContents) { + stringBuilder.push( + "
" + ); + } + + if (tokens.length) { + var splits = this.session.getRowSplitData(row); + if (splits && splits.length) + this.$renderWrappedLine(stringBuilder, tokens, splits, onlyContents); + else + this.$renderSimpleLine(stringBuilder, tokens); + } + + if (this.showInvisibles) { + if (foldLine) + row = foldLine.end.row; + + stringBuilder.push( + "", + row == this.session.getLength() - 1 ? this.EOF_CHAR : this.EOL_CHAR, + "" + ); + } + if (!onlyContents) + stringBuilder.push("
"); + }; + + this.$getFoldLineTokens = function(row, foldLine) { + var session = this.session; + var renderTokens = []; + + function addTokens(tokens, from, to) { + var idx = 0, col = 0; + while ((col + tokens[idx].value.length) < from) { + col += tokens[idx].value.length; + idx++; + + if (idx == tokens.length) + return; + } + if (col != from) { + var value = tokens[idx].value.substring(from - col); + if (value.length > (to - from)) + value = value.substring(0, to - from); + + renderTokens.push({ + type: tokens[idx].type, + value: value + }); + + col = from + value.length; + idx += 1; + } + + while (col < to && idx < tokens.length) { + var value = tokens[idx].value; + if (value.length + col > to) { + renderTokens.push({ + type: tokens[idx].type, + value: value.substring(0, to - col) + }); + } else + renderTokens.push(tokens[idx]); + col += value.length; + idx += 1; + } + } + + var tokens = session.getTokens(row); + foldLine.walk(function(placeholder, row, column, lastColumn, isNewRow) { + if (placeholder != null) { + renderTokens.push({ + type: "fold", + value: placeholder + }); + } else { + if (isNewRow) + tokens = session.getTokens(row); + + if (tokens.length) + addTokens(tokens, lastColumn, column); + } + }, foldLine.end.row, this.session.getLine(foldLine.end.row).length); + + return renderTokens; + }; + + this.$useLineGroups = function() { + return this.session.getUseWrapMode(); + }; + + this.destroy = function() { + clearInterval(this.$pollSizeChangesTimer); + if (this.$measureNode) + this.$measureNode.parentNode.removeChild(this.$measureNode); + delete this.$measureNode; + }; + +}).call(Text.prototype); + +exports.Text = Text; + +}); + +ace.define("ace/layer/cursor",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; + +var dom = acequire("../lib/dom"); +var isIE8; + +var Cursor = function(parentEl) { + this.element = dom.createElement("div"); + this.element.className = "ace_layer ace_cursor-layer"; + parentEl.appendChild(this.element); + + if (isIE8 === undefined) + isIE8 = !("opacity" in this.element.style); + + this.isVisible = false; + this.isBlinking = true; + this.blinkInterval = 1000; + this.smoothBlinking = false; + + this.cursors = []; + this.cursor = this.addCursor(); + dom.addCssClass(this.element, "ace_hidden-cursors"); + this.$updateCursors = (isIE8 + ? this.$updateVisibility + : this.$updateOpacity).bind(this); +}; + +(function() { + + this.$updateVisibility = function(val) { + var cursors = this.cursors; + for (var i = cursors.length; i--; ) + cursors[i].style.visibility = val ? "" : "hidden"; + }; + this.$updateOpacity = function(val) { + var cursors = this.cursors; + for (var i = cursors.length; i--; ) + cursors[i].style.opacity = val ? "" : "0"; + }; + + + this.$padding = 0; + this.setPadding = function(padding) { + this.$padding = padding; + }; + + this.setSession = function(session) { + this.session = session; + }; + + this.setBlinking = function(blinking) { + if (blinking != this.isBlinking){ + this.isBlinking = blinking; + this.restartTimer(); + } + }; + + this.setBlinkInterval = function(blinkInterval) { + if (blinkInterval != this.blinkInterval){ + this.blinkInterval = blinkInterval; + this.restartTimer(); + } + }; + + this.setSmoothBlinking = function(smoothBlinking) { + if (smoothBlinking != this.smoothBlinking && !isIE8) { + this.smoothBlinking = smoothBlinking; + dom.setCssClass(this.element, "ace_smooth-blinking", smoothBlinking); + this.$updateCursors(true); + this.$updateCursors = (this.$updateOpacity).bind(this); + this.restartTimer(); + } + }; + + this.addCursor = function() { + var el = dom.createElement("div"); + el.className = "ace_cursor"; + this.element.appendChild(el); + this.cursors.push(el); + return el; + }; + + this.removeCursor = function() { + if (this.cursors.length > 1) { + var el = this.cursors.pop(); + el.parentNode.removeChild(el); + return el; + } + }; + + this.hideCursor = function() { + this.isVisible = false; + dom.addCssClass(this.element, "ace_hidden-cursors"); + this.restartTimer(); + }; + + this.showCursor = function() { + this.isVisible = true; + dom.removeCssClass(this.element, "ace_hidden-cursors"); + this.restartTimer(); + }; + + this.restartTimer = function() { + var update = this.$updateCursors; + clearInterval(this.intervalId); + clearTimeout(this.timeoutId); + if (this.smoothBlinking) { + dom.removeCssClass(this.element, "ace_smooth-blinking"); + } + + update(true); + + if (!this.isBlinking || !this.blinkInterval || !this.isVisible) + return; + + if (this.smoothBlinking) { + setTimeout(function(){ + dom.addCssClass(this.element, "ace_smooth-blinking"); + }.bind(this)); + } + + var blink = function(){ + this.timeoutId = setTimeout(function() { + update(false); + }, 0.6 * this.blinkInterval); + }.bind(this); + + this.intervalId = setInterval(function() { + update(true); + blink(); + }, this.blinkInterval); + + blink(); + }; + + this.getPixelPosition = function(position, onScreen) { + if (!this.config || !this.session) + return {left : 0, top : 0}; + + if (!position) + position = this.session.selection.getCursor(); + var pos = this.session.documentToScreenPosition(position); + var cursorLeft = this.$padding + (this.session.$bidiHandler.isBidiRow(pos.row, position.row) + ? this.session.$bidiHandler.getPosLeft(pos.column) + : pos.column * this.config.characterWidth); + + var cursorTop = (pos.row - (onScreen ? this.config.firstRowScreen : 0)) * + this.config.lineHeight; + + return {left : cursorLeft, top : cursorTop}; + }; + + this.update = function(config) { + this.config = config; + + var selections = this.session.$selectionMarkers; + var i = 0, cursorIndex = 0; + + if (selections === undefined || selections.length === 0){ + selections = [{cursor: null}]; + } + + for (var i = 0, n = selections.length; i < n; i++) { + var pixelPos = this.getPixelPosition(selections[i].cursor, true); + if ((pixelPos.top > config.height + config.offset || + pixelPos.top < 0) && i > 1) { + continue; + } + + var style = (this.cursors[cursorIndex++] || this.addCursor()).style; + + if (!this.drawCursor) { + style.left = pixelPos.left + "px"; + style.top = pixelPos.top + "px"; + style.width = config.characterWidth + "px"; + style.height = config.lineHeight + "px"; + } else { + this.drawCursor(style, pixelPos, config, selections[i], this.session); + } + } + while (this.cursors.length > cursorIndex) + this.removeCursor(); + + var overwrite = this.session.getOverwrite(); + this.$setOverwrite(overwrite); + this.$pixelPos = pixelPos; + this.restartTimer(); + }; + + this.drawCursor = null; + + this.$setOverwrite = function(overwrite) { + if (overwrite != this.overwrite) { + this.overwrite = overwrite; + if (overwrite) + dom.addCssClass(this.element, "ace_overwrite-cursors"); + else + dom.removeCssClass(this.element, "ace_overwrite-cursors"); + } + }; + + this.destroy = function() { + clearInterval(this.intervalId); + clearTimeout(this.timeoutId); + }; + +}).call(Cursor.prototype); + +exports.Cursor = Cursor; + +}); + +ace.define("ace/scrollbar",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var dom = acequire("./lib/dom"); +var event = acequire("./lib/event"); +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var MAX_SCROLL_H = 0x8000; +var ScrollBar = function(parent) { + this.element = dom.createElement("div"); + this.element.className = "ace_scrollbar ace_scrollbar" + this.classSuffix; + + this.inner = dom.createElement("div"); + this.inner.className = "ace_scrollbar-inner"; + this.element.appendChild(this.inner); + + parent.appendChild(this.element); + + this.setVisible(false); + this.skipEvent = false; + + event.addListener(this.element, "scroll", this.onScroll.bind(this)); + event.addListener(this.element, "mousedown", event.preventDefault); +}; + +(function() { + oop.implement(this, EventEmitter); + + this.setVisible = function(isVisible) { + this.element.style.display = isVisible ? "" : "none"; + this.isVisible = isVisible; + this.coeff = 1; + }; +}).call(ScrollBar.prototype); +var VScrollBar = function(parent, renderer) { + ScrollBar.call(this, parent); + this.scrollTop = 0; + this.scrollHeight = 0; + renderer.$scrollbarWidth = + this.width = dom.scrollbarWidth(parent.ownerDocument); + this.inner.style.width = + this.element.style.width = (this.width || 15) + 5 + "px"; + this.$minWidth = 0; +}; + +oop.inherits(VScrollBar, ScrollBar); + +(function() { + + this.classSuffix = '-v'; + this.onScroll = function() { + if (!this.skipEvent) { + this.scrollTop = this.element.scrollTop; + if (this.coeff != 1) { + var h = this.element.clientHeight / this.scrollHeight; + this.scrollTop = this.scrollTop * (1 - h) / (this.coeff - h); + } + this._emit("scroll", {data: this.scrollTop}); + } + this.skipEvent = false; + }; + this.getWidth = function() { + return Math.max(this.isVisible ? this.width : 0, this.$minWidth || 0); + }; + this.setHeight = function(height) { + this.element.style.height = height + "px"; + }; + this.setInnerHeight = + this.setScrollHeight = function(height) { + this.scrollHeight = height; + if (height > MAX_SCROLL_H) { + this.coeff = MAX_SCROLL_H / height; + height = MAX_SCROLL_H; + } else if (this.coeff != 1) { + this.coeff = 1; + } + this.inner.style.height = height + "px"; + }; + this.setScrollTop = function(scrollTop) { + if (this.scrollTop != scrollTop) { + this.skipEvent = true; + this.scrollTop = scrollTop; + this.element.scrollTop = scrollTop * this.coeff; + } + }; + +}).call(VScrollBar.prototype); +var HScrollBar = function(parent, renderer) { + ScrollBar.call(this, parent); + this.scrollLeft = 0; + this.height = renderer.$scrollbarWidth; + this.inner.style.height = + this.element.style.height = (this.height || 15) + 5 + "px"; +}; + +oop.inherits(HScrollBar, ScrollBar); + +(function() { + + this.classSuffix = '-h'; + this.onScroll = function() { + if (!this.skipEvent) { + this.scrollLeft = this.element.scrollLeft; + this._emit("scroll", {data: this.scrollLeft}); + } + this.skipEvent = false; + }; + this.getHeight = function() { + return this.isVisible ? this.height : 0; + }; + this.setWidth = function(width) { + this.element.style.width = width + "px"; + }; + this.setInnerWidth = function(width) { + this.inner.style.width = width + "px"; + }; + this.setScrollWidth = function(width) { + this.inner.style.width = width + "px"; + }; + this.setScrollLeft = function(scrollLeft) { + if (this.scrollLeft != scrollLeft) { + this.skipEvent = true; + this.scrollLeft = this.element.scrollLeft = scrollLeft; + } + }; + +}).call(HScrollBar.prototype); + + +exports.ScrollBar = VScrollBar; // backward compatibility +exports.ScrollBarV = VScrollBar; // backward compatibility +exports.ScrollBarH = HScrollBar; // backward compatibility + +exports.VScrollBar = VScrollBar; +exports.HScrollBar = HScrollBar; +}); + +ace.define("ace/renderloop",["require","exports","module","ace/lib/event"], function(acequire, exports, module) { +"use strict"; + +var event = acequire("./lib/event"); + + +var RenderLoop = function(onRender, win) { + this.onRender = onRender; + this.pending = false; + this.changes = 0; + this.window = win || window; +}; + +(function() { + + + this.schedule = function(change) { + this.changes = this.changes | change; + if (!this.pending && this.changes) { + this.pending = true; + var _self = this; + event.nextFrame(function() { + _self.pending = false; + var changes; + while (changes = _self.changes) { + _self.changes = 0; + _self.onRender(changes); + } + }, this.window); + } + }; + +}).call(RenderLoop.prototype); + +exports.RenderLoop = RenderLoop; +}); + +ace.define("ace/layer/font_metrics",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"], function(acequire, exports, module) { + +var oop = acequire("../lib/oop"); +var dom = acequire("../lib/dom"); +var lang = acequire("../lib/lang"); +var useragent = acequire("../lib/useragent"); +var EventEmitter = acequire("../lib/event_emitter").EventEmitter; + +var CHAR_COUNT = 0; + +var FontMetrics = exports.FontMetrics = function(parentEl) { + this.el = dom.createElement("div"); + this.$setMeasureNodeStyles(this.el.style, true); + + this.$main = dom.createElement("div"); + this.$setMeasureNodeStyles(this.$main.style); + + this.$measureNode = dom.createElement("div"); + this.$setMeasureNodeStyles(this.$measureNode.style); + + + this.el.appendChild(this.$main); + this.el.appendChild(this.$measureNode); + parentEl.appendChild(this.el); + + if (!CHAR_COUNT) + this.$testFractionalRect(); + this.$measureNode.innerHTML = lang.stringRepeat("X", CHAR_COUNT); + + this.$characterSize = {width: 0, height: 0}; + this.checkForSizeChanges(); +}; + +(function() { + + oop.implement(this, EventEmitter); + + this.$characterSize = {width: 0, height: 0}; + + this.$testFractionalRect = function() { + var el = dom.createElement("div"); + this.$setMeasureNodeStyles(el.style); + el.style.width = "0.2px"; + document.documentElement.appendChild(el); + var w = el.getBoundingClientRect().width; + if (w > 0 && w < 1) + CHAR_COUNT = 50; + else + CHAR_COUNT = 100; + el.parentNode.removeChild(el); + }; + + this.$setMeasureNodeStyles = function(style, isRoot) { + style.width = style.height = "auto"; + style.left = style.top = "0px"; + style.visibility = "hidden"; + style.position = "absolute"; + style.whiteSpace = "pre"; + + if (useragent.isIE < 8) { + style["font-family"] = "inherit"; + } else { + style.font = "inherit"; + } + style.overflow = isRoot ? "hidden" : "visible"; + }; + + this.checkForSizeChanges = function() { + var size = this.$measureSizes(); + if (size && (this.$characterSize.width !== size.width || this.$characterSize.height !== size.height)) { + this.$measureNode.style.fontWeight = "bold"; + var boldSize = this.$measureSizes(); + this.$measureNode.style.fontWeight = ""; + this.$characterSize = size; + this.charSizes = Object.create(null); + this.allowBoldFonts = boldSize && boldSize.width === size.width && boldSize.height === size.height; + this._emit("changeCharacterSize", {data: size}); + } + }; + + this.$pollSizeChanges = function() { + if (this.$pollSizeChangesTimer) + return this.$pollSizeChangesTimer; + var self = this; + return this.$pollSizeChangesTimer = setInterval(function() { + self.checkForSizeChanges(); + }, 500); + }; + + this.setPolling = function(val) { + if (val) { + this.$pollSizeChanges(); + } else if (this.$pollSizeChangesTimer) { + clearInterval(this.$pollSizeChangesTimer); + this.$pollSizeChangesTimer = 0; + } + }; + + this.$measureSizes = function() { + if (CHAR_COUNT === 50) { + var rect = null; + try { + rect = this.$measureNode.getBoundingClientRect(); + } catch(e) { + rect = {width: 0, height:0 }; + } + var size = { + height: rect.height, + width: rect.width / CHAR_COUNT + }; + } else { + var size = { + height: this.$measureNode.clientHeight, + width: this.$measureNode.clientWidth / CHAR_COUNT + }; + } + if (size.width === 0 || size.height === 0) + return null; + return size; + }; + + this.$measureCharWidth = function(ch) { + this.$main.innerHTML = lang.stringRepeat(ch, CHAR_COUNT); + var rect = this.$main.getBoundingClientRect(); + return rect.width / CHAR_COUNT; + }; + + this.getCharacterWidth = function(ch) { + var w = this.charSizes[ch]; + if (w === undefined) { + w = this.charSizes[ch] = this.$measureCharWidth(ch) / this.$characterSize.width; + } + return w; + }; + + this.destroy = function() { + clearInterval(this.$pollSizeChangesTimer); + if (this.el && this.el.parentNode) + this.el.parentNode.removeChild(this.el); + }; + +}).call(FontMetrics.prototype); + +}); + +ace.define("ace/virtual_renderer",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/config","ace/lib/useragent","ace/layer/gutter","ace/layer/marker","ace/layer/text","ace/layer/cursor","ace/scrollbar","ace/scrollbar","ace/renderloop","ace/layer/font_metrics","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var dom = acequire("./lib/dom"); +var config = acequire("./config"); +var useragent = acequire("./lib/useragent"); +var GutterLayer = acequire("./layer/gutter").Gutter; +var MarkerLayer = acequire("./layer/marker").Marker; +var TextLayer = acequire("./layer/text").Text; +var CursorLayer = acequire("./layer/cursor").Cursor; +var HScrollBar = acequire("./scrollbar").HScrollBar; +var VScrollBar = acequire("./scrollbar").VScrollBar; +var RenderLoop = acequire("./renderloop").RenderLoop; +var FontMetrics = acequire("./layer/font_metrics").FontMetrics; +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var editorCss = ".ace_editor {\ +position: relative;\ +overflow: hidden;\ +font: 12px/normal 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;\ +direction: ltr;\ +text-align: left;\ +-webkit-tap-highlight-color: rgba(0, 0, 0, 0);\ +}\ +.ace_scroller {\ +position: absolute;\ +overflow: hidden;\ +top: 0;\ +bottom: 0;\ +background-color: inherit;\ +-ms-user-select: none;\ +-moz-user-select: none;\ +-webkit-user-select: none;\ +user-select: none;\ +cursor: text;\ +}\ +.ace_content {\ +position: absolute;\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +min-width: 100%;\ +}\ +.ace_dragging .ace_scroller:before{\ +position: absolute;\ +top: 0;\ +left: 0;\ +right: 0;\ +bottom: 0;\ +content: '';\ +background: rgba(250, 250, 250, 0.01);\ +z-index: 1000;\ +}\ +.ace_dragging.ace_dark .ace_scroller:before{\ +background: rgba(0, 0, 0, 0.01);\ +}\ +.ace_selecting, .ace_selecting * {\ +cursor: text !important;\ +}\ +.ace_gutter {\ +position: absolute;\ +overflow : hidden;\ +width: auto;\ +top: 0;\ +bottom: 0;\ +left: 0;\ +cursor: default;\ +z-index: 4;\ +-ms-user-select: none;\ +-moz-user-select: none;\ +-webkit-user-select: none;\ +user-select: none;\ +}\ +.ace_gutter-active-line {\ +position: absolute;\ +left: 0;\ +right: 0;\ +}\ +.ace_scroller.ace_scroll-left {\ +box-shadow: 17px 0 16px -16px rgba(0, 0, 0, 0.4) inset;\ +}\ +.ace_gutter-cell {\ +padding-left: 19px;\ +padding-right: 6px;\ +background-repeat: no-repeat;\ +}\ +.ace_gutter-cell.ace_error {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAABOFBMVEX/////////QRswFAb/Ui4wFAYwFAYwFAaWGAfDRymzOSH/PxswFAb/SiUwFAYwFAbUPRvjQiDllog5HhHdRybsTi3/Tyv9Tir+Syj/UC3////XurebMBIwFAb/RSHbPx/gUzfdwL3kzMivKBAwFAbbvbnhPx66NhowFAYwFAaZJg8wFAaxKBDZurf/RB6mMxb/SCMwFAYwFAbxQB3+RB4wFAb/Qhy4Oh+4QifbNRcwFAYwFAYwFAb/QRzdNhgwFAYwFAbav7v/Uy7oaE68MBK5LxLewr/r2NXewLswFAaxJw4wFAbkPRy2PyYwFAaxKhLm1tMwFAazPiQwFAaUGAb/QBrfOx3bvrv/VC/maE4wFAbRPBq6MRO8Qynew8Dp2tjfwb0wFAbx6eju5+by6uns4uH9/f36+vr/GkHjAAAAYnRSTlMAGt+64rnWu/bo8eAA4InH3+DwoN7j4eLi4xP99Nfg4+b+/u9B/eDs1MD1mO7+4PHg2MXa347g7vDizMLN4eG+Pv7i5evs/v79yu7S3/DV7/498Yv24eH+4ufQ3Ozu/v7+y13sRqwAAADLSURBVHjaZc/XDsFgGIBhtDrshlitmk2IrbHFqL2pvXf/+78DPokj7+Fz9qpU/9UXJIlhmPaTaQ6QPaz0mm+5gwkgovcV6GZzd5JtCQwgsxoHOvJO15kleRLAnMgHFIESUEPmawB9ngmelTtipwwfASilxOLyiV5UVUyVAfbG0cCPHig+GBkzAENHS0AstVF6bacZIOzgLmxsHbt2OecNgJC83JERmePUYq8ARGkJx6XtFsdddBQgZE2nPR6CICZhawjA4Fb/chv+399kfR+MMMDGOQAAAABJRU5ErkJggg==\");\ +background-repeat: no-repeat;\ +background-position: 2px center;\ +}\ +.ace_gutter-cell.ace_warning {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAmVBMVEX///8AAAD///8AAAAAAABPSzb/5sAAAAB/blH/73z/ulkAAAAAAAD85pkAAAAAAAACAgP/vGz/rkDerGbGrV7/pkQICAf////e0IsAAAD/oED/qTvhrnUAAAD/yHD/njcAAADuv2r/nz//oTj/p064oGf/zHAAAAA9Nir/tFIAAAD/tlTiuWf/tkIAAACynXEAAAAAAAAtIRW7zBpBAAAAM3RSTlMAABR1m7RXO8Ln31Z36zT+neXe5OzooRDfn+TZ4p3h2hTf4t3k3ucyrN1K5+Xaks52Sfs9CXgrAAAAjklEQVR42o3PbQ+CIBQFYEwboPhSYgoYunIqqLn6/z8uYdH8Vmdnu9vz4WwXgN/xTPRD2+sgOcZjsge/whXZgUaYYvT8QnuJaUrjrHUQreGczuEafQCO/SJTufTbroWsPgsllVhq3wJEk2jUSzX3CUEDJC84707djRc5MTAQxoLgupWRwW6UB5fS++NV8AbOZgnsC7BpEAAAAABJRU5ErkJggg==\");\ +background-position: 2px center;\ +}\ +.ace_gutter-cell.ace_info {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAAAAAA6mKC9AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAJ0Uk5TAAB2k804AAAAPklEQVQY02NgIB68QuO3tiLznjAwpKTgNyDbMegwisCHZUETUZV0ZqOquBpXj2rtnpSJT1AEnnRmL2OgGgAAIKkRQap2htgAAAAASUVORK5CYII=\");\ +background-position: 2px center;\ +}\ +.ace_dark .ace_gutter-cell.ace_info {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAJFBMVEUAAAChoaGAgIAqKiq+vr6tra1ZWVmUlJSbm5s8PDxubm56enrdgzg3AAAAAXRSTlMAQObYZgAAAClJREFUeNpjYMAPdsMYHegyJZFQBlsUlMFVCWUYKkAZMxZAGdxlDMQBAG+TBP4B6RyJAAAAAElFTkSuQmCC\");\ +}\ +.ace_scrollbar {\ +position: absolute;\ +right: 0;\ +bottom: 0;\ +z-index: 6;\ +}\ +.ace_scrollbar-inner {\ +position: absolute;\ +cursor: text;\ +left: 0;\ +top: 0;\ +}\ +.ace_scrollbar-v{\ +overflow-x: hidden;\ +overflow-y: scroll;\ +top: 0;\ +}\ +.ace_scrollbar-h {\ +overflow-x: scroll;\ +overflow-y: hidden;\ +left: 0;\ +}\ +.ace_print-margin {\ +position: absolute;\ +height: 100%;\ +}\ +.ace_text-input {\ +position: absolute;\ +z-index: 0;\ +width: 0.5em;\ +height: 1em;\ +opacity: 0;\ +background: transparent;\ +-moz-appearance: none;\ +appearance: none;\ +border: none;\ +resize: none;\ +outline: none;\ +overflow: hidden;\ +font: inherit;\ +padding: 0 1px;\ +margin: 0 -1px;\ +text-indent: -1em;\ +-ms-user-select: text;\ +-moz-user-select: text;\ +-webkit-user-select: text;\ +user-select: text;\ +white-space: pre!important;\ +}\ +.ace_text-input.ace_composition {\ +background: inherit;\ +color: inherit;\ +z-index: 1000;\ +opacity: 1;\ +text-indent: 0;\ +}\ +.ace_layer {\ +z-index: 1;\ +position: absolute;\ +overflow: hidden;\ +word-wrap: normal;\ +white-space: pre;\ +height: 100%;\ +width: 100%;\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +pointer-events: none;\ +}\ +.ace_gutter-layer {\ +position: relative;\ +width: auto;\ +text-align: right;\ +pointer-events: auto;\ +}\ +.ace_text-layer {\ +font: inherit !important;\ +}\ +.ace_cjk {\ +display: inline-block;\ +text-align: center;\ +}\ +.ace_cursor-layer {\ +z-index: 4;\ +}\ +.ace_cursor {\ +z-index: 4;\ +position: absolute;\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +border-left: 2px solid;\ +transform: translatez(0);\ +}\ +.ace_multiselect .ace_cursor {\ +border-left-width: 1px;\ +}\ +.ace_slim-cursors .ace_cursor {\ +border-left-width: 1px;\ +}\ +.ace_overwrite-cursors .ace_cursor {\ +border-left-width: 0;\ +border-bottom: 1px solid;\ +}\ +.ace_hidden-cursors .ace_cursor {\ +opacity: 0.2;\ +}\ +.ace_smooth-blinking .ace_cursor {\ +-webkit-transition: opacity 0.18s;\ +transition: opacity 0.18s;\ +}\ +.ace_marker-layer .ace_step, .ace_marker-layer .ace_stack {\ +position: absolute;\ +z-index: 3;\ +}\ +.ace_marker-layer .ace_selection {\ +position: absolute;\ +z-index: 5;\ +}\ +.ace_marker-layer .ace_bracket {\ +position: absolute;\ +z-index: 6;\ +}\ +.ace_marker-layer .ace_active-line {\ +position: absolute;\ +z-index: 2;\ +}\ +.ace_marker-layer .ace_selected-word {\ +position: absolute;\ +z-index: 4;\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +}\ +.ace_line .ace_fold {\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +display: inline-block;\ +height: 11px;\ +margin-top: -2px;\ +vertical-align: middle;\ +background-image:\ +url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII=\"),\ +url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACJJREFUeNpi+P//fxgTAwPDBxDxD078RSX+YeEyDFMCIMAAI3INmXiwf2YAAAAASUVORK5CYII=\");\ +background-repeat: no-repeat, repeat-x;\ +background-position: center center, top left;\ +color: transparent;\ +border: 1px solid black;\ +border-radius: 2px;\ +cursor: pointer;\ +pointer-events: auto;\ +}\ +.ace_dark .ace_fold {\ +}\ +.ace_fold:hover{\ +background-image:\ +url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII=\"),\ +url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACBJREFUeNpi+P//fz4TAwPDZxDxD5X4i5fLMEwJgAADAEPVDbjNw87ZAAAAAElFTkSuQmCC\");\ +}\ +.ace_tooltip {\ +background-color: #FFF;\ +background-image: -webkit-linear-gradient(top, transparent, rgba(0, 0, 0, 0.1));\ +background-image: linear-gradient(to bottom, transparent, rgba(0, 0, 0, 0.1));\ +border: 1px solid gray;\ +border-radius: 1px;\ +box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);\ +color: black;\ +max-width: 100%;\ +padding: 3px 4px;\ +position: fixed;\ +z-index: 999999;\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +cursor: default;\ +white-space: pre;\ +word-wrap: break-word;\ +line-height: normal;\ +font-style: normal;\ +font-weight: normal;\ +letter-spacing: normal;\ +pointer-events: none;\ +}\ +.ace_folding-enabled > .ace_gutter-cell {\ +padding-right: 13px;\ +}\ +.ace_fold-widget {\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +margin: 0 -12px 0 1px;\ +display: none;\ +width: 11px;\ +vertical-align: top;\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42mWKsQ0AMAzC8ixLlrzQjzmBiEjp0A6WwBCSPgKAXoLkqSot7nN3yMwR7pZ32NzpKkVoDBUxKAAAAABJRU5ErkJggg==\");\ +background-repeat: no-repeat;\ +background-position: center;\ +border-radius: 3px;\ +border: 1px solid transparent;\ +cursor: pointer;\ +}\ +.ace_folding-enabled .ace_fold-widget {\ +display: inline-block; \ +}\ +.ace_fold-widget.ace_end {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42m3HwQkAMAhD0YzsRchFKI7sAikeWkrxwScEB0nh5e7KTPWimZki4tYfVbX+MNl4pyZXejUO1QAAAABJRU5ErkJggg==\");\ +}\ +.ace_fold-widget.ace_closed {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAGCAYAAAAG5SQMAAAAOUlEQVR42jXKwQkAMAgDwKwqKD4EwQ26sSOkVWjgIIHAzPiCgaqiqnJHZnKICBERHN194O5b9vbLuAVRL+l0YWnZAAAAAElFTkSuQmCCXA==\");\ +}\ +.ace_fold-widget:hover {\ +border: 1px solid rgba(0, 0, 0, 0.3);\ +background-color: rgba(255, 255, 255, 0.2);\ +box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\ +}\ +.ace_fold-widget:active {\ +border: 1px solid rgba(0, 0, 0, 0.4);\ +background-color: rgba(0, 0, 0, 0.05);\ +box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\ +}\ +.ace_dark .ace_fold-widget {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHklEQVQIW2P4//8/AzoGEQ7oGCaLLAhWiSwB146BAQCSTPYocqT0AAAAAElFTkSuQmCC\");\ +}\ +.ace_dark .ace_fold-widget.ace_end {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAH0lEQVQIW2P4//8/AxQ7wNjIAjDMgC4AxjCVKBirIAAF0kz2rlhxpAAAAABJRU5ErkJggg==\");\ +}\ +.ace_dark .ace_fold-widget.ace_closed {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAFCAYAAACAcVaiAAAAHElEQVQIW2P4//+/AxAzgDADlOOAznHAKgPWAwARji8UIDTfQQAAAABJRU5ErkJggg==\");\ +}\ +.ace_dark .ace_fold-widget:hover {\ +box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);\ +background-color: rgba(255, 255, 255, 0.1);\ +}\ +.ace_dark .ace_fold-widget:active {\ +box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);\ +}\ +.ace_fold-widget.ace_invalid {\ +background-color: #FFB4B4;\ +border-color: #DE5555;\ +}\ +.ace_fade-fold-widgets .ace_fold-widget {\ +-webkit-transition: opacity 0.4s ease 0.05s;\ +transition: opacity 0.4s ease 0.05s;\ +opacity: 0;\ +}\ +.ace_fade-fold-widgets:hover .ace_fold-widget {\ +-webkit-transition: opacity 0.05s ease 0.05s;\ +transition: opacity 0.05s ease 0.05s;\ +opacity:1;\ +}\ +.ace_underline {\ +text-decoration: underline;\ +}\ +.ace_bold {\ +font-weight: bold;\ +}\ +.ace_nobold .ace_bold {\ +font-weight: normal;\ +}\ +.ace_italic {\ +font-style: italic;\ +}\ +.ace_error-marker {\ +background-color: rgba(255, 0, 0,0.2);\ +position: absolute;\ +z-index: 9;\ +}\ +.ace_highlight-marker {\ +background-color: rgba(255, 255, 0,0.2);\ +position: absolute;\ +z-index: 8;\ +}\ +.ace_br1 {border-top-left-radius : 3px;}\ +.ace_br2 {border-top-right-radius : 3px;}\ +.ace_br3 {border-top-left-radius : 3px; border-top-right-radius: 3px;}\ +.ace_br4 {border-bottom-right-radius: 3px;}\ +.ace_br5 {border-top-left-radius : 3px; border-bottom-right-radius: 3px;}\ +.ace_br6 {border-top-right-radius : 3px; border-bottom-right-radius: 3px;}\ +.ace_br7 {border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px;}\ +.ace_br8 {border-bottom-left-radius : 3px;}\ +.ace_br9 {border-top-left-radius : 3px; border-bottom-left-radius: 3px;}\ +.ace_br10{border-top-right-radius : 3px; border-bottom-left-radius: 3px;}\ +.ace_br11{border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-left-radius: 3px;}\ +.ace_br12{border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ +.ace_br13{border-top-left-radius : 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ +.ace_br14{border-top-right-radius : 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ +.ace_br15{border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ +.ace_text-input-ios {\ +position: absolute !important;\ +top: -100000px !important;\ +left: -100000px !important;\ +}\ +"; + +dom.importCssString(editorCss, "ace_editor.css"); + +var VirtualRenderer = function(container, theme) { + var _self = this; + + this.container = container || dom.createElement("div"); + this.$keepTextAreaAtCursor = !useragent.isOldIE; + + dom.addCssClass(this.container, "ace_editor"); + + this.setTheme(theme); + + this.$gutter = dom.createElement("div"); + this.$gutter.className = "ace_gutter"; + this.container.appendChild(this.$gutter); + this.$gutter.setAttribute("aria-hidden", true); + + this.scroller = dom.createElement("div"); + this.scroller.className = "ace_scroller"; + this.container.appendChild(this.scroller); + + this.content = dom.createElement("div"); + this.content.className = "ace_content"; + this.scroller.appendChild(this.content); + + this.$gutterLayer = new GutterLayer(this.$gutter); + this.$gutterLayer.on("changeGutterWidth", this.onGutterResize.bind(this)); + + this.$markerBack = new MarkerLayer(this.content); + + var textLayer = this.$textLayer = new TextLayer(this.content); + this.canvas = textLayer.element; + + this.$markerFront = new MarkerLayer(this.content); + + this.$cursorLayer = new CursorLayer(this.content); + this.$horizScroll = false; + this.$vScroll = false; + + this.scrollBar = + this.scrollBarV = new VScrollBar(this.container, this); + this.scrollBarH = new HScrollBar(this.container, this); + this.scrollBarV.addEventListener("scroll", function(e) { + if (!_self.$scrollAnimation) + _self.session.setScrollTop(e.data - _self.scrollMargin.top); + }); + this.scrollBarH.addEventListener("scroll", function(e) { + if (!_self.$scrollAnimation) + _self.session.setScrollLeft(e.data - _self.scrollMargin.left); + }); + + this.scrollTop = 0; + this.scrollLeft = 0; + + this.cursorPos = { + row : 0, + column : 0 + }; + + this.$fontMetrics = new FontMetrics(this.container); + this.$textLayer.$setFontMetrics(this.$fontMetrics); + this.$textLayer.addEventListener("changeCharacterSize", function(e) { + _self.updateCharacterSize(); + _self.onResize(true, _self.gutterWidth, _self.$size.width, _self.$size.height); + _self._signal("changeCharacterSize", e); + }); + + this.$size = { + width: 0, + height: 0, + scrollerHeight: 0, + scrollerWidth: 0, + $dirty: true + }; + + this.layerConfig = { + width : 1, + padding : 0, + firstRow : 0, + firstRowScreen: 0, + lastRow : 0, + lineHeight : 0, + characterWidth : 0, + minHeight : 1, + maxHeight : 1, + offset : 0, + height : 1, + gutterOffset: 1 + }; + + this.scrollMargin = { + left: 0, + right: 0, + top: 0, + bottom: 0, + v: 0, + h: 0 + }; + + this.$loop = new RenderLoop( + this.$renderChanges.bind(this), + this.container.ownerDocument.defaultView + ); + this.$loop.schedule(this.CHANGE_FULL); + + this.updateCharacterSize(); + this.setPadding(4); + config.resetOptions(this); + config._emit("renderer", this); +}; + +(function() { + + this.CHANGE_CURSOR = 1; + this.CHANGE_MARKER = 2; + this.CHANGE_GUTTER = 4; + this.CHANGE_SCROLL = 8; + this.CHANGE_LINES = 16; + this.CHANGE_TEXT = 32; + this.CHANGE_SIZE = 64; + this.CHANGE_MARKER_BACK = 128; + this.CHANGE_MARKER_FRONT = 256; + this.CHANGE_FULL = 512; + this.CHANGE_H_SCROLL = 1024; + + oop.implement(this, EventEmitter); + + this.updateCharacterSize = function() { + if (this.$textLayer.allowBoldFonts != this.$allowBoldFonts) { + this.$allowBoldFonts = this.$textLayer.allowBoldFonts; + this.setStyle("ace_nobold", !this.$allowBoldFonts); + } + + this.layerConfig.characterWidth = + this.characterWidth = this.$textLayer.getCharacterWidth(); + this.layerConfig.lineHeight = + this.lineHeight = this.$textLayer.getLineHeight(); + this.$updatePrintMargin(); + }; + this.setSession = function(session) { + if (this.session) + this.session.doc.off("changeNewLineMode", this.onChangeNewLineMode); + + this.session = session; + if (session && this.scrollMargin.top && session.getScrollTop() <= 0) + session.setScrollTop(-this.scrollMargin.top); + + this.$cursorLayer.setSession(session); + this.$markerBack.setSession(session); + this.$markerFront.setSession(session); + this.$gutterLayer.setSession(session); + this.$textLayer.setSession(session); + if (!session) + return; + + this.$loop.schedule(this.CHANGE_FULL); + this.session.$setFontMetrics(this.$fontMetrics); + this.scrollBarH.scrollLeft = this.scrollBarV.scrollTop = null; + + this.onChangeNewLineMode = this.onChangeNewLineMode.bind(this); + this.onChangeNewLineMode(); + this.session.doc.on("changeNewLineMode", this.onChangeNewLineMode); + }; + this.updateLines = function(firstRow, lastRow, force) { + if (lastRow === undefined) + lastRow = Infinity; + + if (!this.$changedLines) { + this.$changedLines = { + firstRow: firstRow, + lastRow: lastRow + }; + } + else { + if (this.$changedLines.firstRow > firstRow) + this.$changedLines.firstRow = firstRow; + + if (this.$changedLines.lastRow < lastRow) + this.$changedLines.lastRow = lastRow; + } + if (this.$changedLines.lastRow < this.layerConfig.firstRow) { + if (force) + this.$changedLines.lastRow = this.layerConfig.lastRow; + else + return; + } + if (this.$changedLines.firstRow > this.layerConfig.lastRow) + return; + this.$loop.schedule(this.CHANGE_LINES); + }; + + this.onChangeNewLineMode = function() { + this.$loop.schedule(this.CHANGE_TEXT); + this.$textLayer.$updateEolChar(); + this.session.$bidiHandler.setEolChar(this.$textLayer.EOL_CHAR); + }; + + this.onChangeTabSize = function() { + this.$loop.schedule(this.CHANGE_TEXT | this.CHANGE_MARKER); + this.$textLayer.onChangeTabSize(); + }; + this.updateText = function() { + this.$loop.schedule(this.CHANGE_TEXT); + }; + this.updateFull = function(force) { + if (force) + this.$renderChanges(this.CHANGE_FULL, true); + else + this.$loop.schedule(this.CHANGE_FULL); + }; + this.updateFontSize = function() { + this.$textLayer.checkForSizeChanges(); + }; + + this.$changes = 0; + this.$updateSizeAsync = function() { + if (this.$loop.pending) + this.$size.$dirty = true; + else + this.onResize(); + }; + this.onResize = function(force, gutterWidth, width, height) { + if (this.resizing > 2) + return; + else if (this.resizing > 0) + this.resizing++; + else + this.resizing = force ? 1 : 0; + var el = this.container; + if (!height) + height = el.clientHeight || el.scrollHeight; + if (!width) + width = el.clientWidth || el.scrollWidth; + var changes = this.$updateCachedSize(force, gutterWidth, width, height); + + + if (!this.$size.scrollerHeight || (!width && !height)) + return this.resizing = 0; + + if (force) + this.$gutterLayer.$padding = null; + + if (force) + this.$renderChanges(changes | this.$changes, true); + else + this.$loop.schedule(changes | this.$changes); + + if (this.resizing) + this.resizing = 0; + this.scrollBarV.scrollLeft = this.scrollBarV.scrollTop = null; + }; + + this.$updateCachedSize = function(force, gutterWidth, width, height) { + height -= (this.$extraHeight || 0); + var changes = 0; + var size = this.$size; + var oldSize = { + width: size.width, + height: size.height, + scrollerHeight: size.scrollerHeight, + scrollerWidth: size.scrollerWidth + }; + if (height && (force || size.height != height)) { + size.height = height; + changes |= this.CHANGE_SIZE; + + size.scrollerHeight = size.height; + if (this.$horizScroll) + size.scrollerHeight -= this.scrollBarH.getHeight(); + this.scrollBarV.element.style.bottom = this.scrollBarH.getHeight() + "px"; + + changes = changes | this.CHANGE_SCROLL; + } + + if (width && (force || size.width != width)) { + changes |= this.CHANGE_SIZE; + size.width = width; + + if (gutterWidth == null) + gutterWidth = this.$showGutter ? this.$gutter.offsetWidth : 0; + + this.gutterWidth = gutterWidth; + + this.scrollBarH.element.style.left = + this.scroller.style.left = gutterWidth + "px"; + size.scrollerWidth = Math.max(0, width - gutterWidth - this.scrollBarV.getWidth()); + + this.scrollBarH.element.style.right = + this.scroller.style.right = this.scrollBarV.getWidth() + "px"; + this.scroller.style.bottom = this.scrollBarH.getHeight() + "px"; + + if (this.session && this.session.getUseWrapMode() && this.adjustWrapLimit() || force) + changes |= this.CHANGE_FULL; + } + + size.$dirty = !width || !height; + + if (changes) + this._signal("resize", oldSize); + + return changes; + }; + + this.onGutterResize = function() { + var gutterWidth = this.$showGutter ? this.$gutter.offsetWidth : 0; + if (gutterWidth != this.gutterWidth) + this.$changes |= this.$updateCachedSize(true, gutterWidth, this.$size.width, this.$size.height); + + if (this.session.getUseWrapMode() && this.adjustWrapLimit()) { + this.$loop.schedule(this.CHANGE_FULL); + } else if (this.$size.$dirty) { + this.$loop.schedule(this.CHANGE_FULL); + } else { + this.$computeLayerConfig(); + this.$loop.schedule(this.CHANGE_MARKER); + } + }; + this.adjustWrapLimit = function() { + var availableWidth = this.$size.scrollerWidth - this.$padding * 2; + var limit = Math.floor(availableWidth / this.characterWidth); + return this.session.adjustWrapLimit(limit, this.$showPrintMargin && this.$printMarginColumn); + }; + this.setAnimatedScroll = function(shouldAnimate){ + this.setOption("animatedScroll", shouldAnimate); + }; + this.getAnimatedScroll = function() { + return this.$animatedScroll; + }; + this.setShowInvisibles = function(showInvisibles) { + this.setOption("showInvisibles", showInvisibles); + this.session.$bidiHandler.setShowInvisibles(showInvisibles); + }; + this.getShowInvisibles = function() { + return this.getOption("showInvisibles"); + }; + this.getDisplayIndentGuides = function() { + return this.getOption("displayIndentGuides"); + }; + + this.setDisplayIndentGuides = function(display) { + this.setOption("displayIndentGuides", display); + }; + this.setShowPrintMargin = function(showPrintMargin) { + this.setOption("showPrintMargin", showPrintMargin); + }; + this.getShowPrintMargin = function() { + return this.getOption("showPrintMargin"); + }; + this.setPrintMarginColumn = function(showPrintMargin) { + this.setOption("printMarginColumn", showPrintMargin); + }; + this.getPrintMarginColumn = function() { + return this.getOption("printMarginColumn"); + }; + this.getShowGutter = function(){ + return this.getOption("showGutter"); + }; + this.setShowGutter = function(show){ + return this.setOption("showGutter", show); + }; + + this.getFadeFoldWidgets = function(){ + return this.getOption("fadeFoldWidgets"); + }; + + this.setFadeFoldWidgets = function(show) { + this.setOption("fadeFoldWidgets", show); + }; + + this.setHighlightGutterLine = function(shouldHighlight) { + this.setOption("highlightGutterLine", shouldHighlight); + }; + + this.getHighlightGutterLine = function() { + return this.getOption("highlightGutterLine"); + }; + + this.$updateGutterLineHighlight = function() { + var pos = this.$cursorLayer.$pixelPos; + var height = this.layerConfig.lineHeight; + if (this.session.getUseWrapMode()) { + var cursor = this.session.selection.getCursor(); + cursor.column = 0; + pos = this.$cursorLayer.getPixelPosition(cursor, true); + height *= this.session.getRowLength(cursor.row); + } + this.$gutterLineHighlight.style.top = pos.top - this.layerConfig.offset + "px"; + this.$gutterLineHighlight.style.height = height + "px"; + }; + + this.$updatePrintMargin = function() { + if (!this.$showPrintMargin && !this.$printMarginEl) + return; + + if (!this.$printMarginEl) { + var containerEl = dom.createElement("div"); + containerEl.className = "ace_layer ace_print-margin-layer"; + this.$printMarginEl = dom.createElement("div"); + this.$printMarginEl.className = "ace_print-margin"; + containerEl.appendChild(this.$printMarginEl); + this.content.insertBefore(containerEl, this.content.firstChild); + } + + var style = this.$printMarginEl.style; + style.left = ((this.characterWidth * this.$printMarginColumn) + this.$padding) + "px"; + style.visibility = this.$showPrintMargin ? "visible" : "hidden"; + + if (this.session && this.session.$wrap == -1) + this.adjustWrapLimit(); + }; + this.getContainerElement = function() { + return this.container; + }; + this.getMouseEventTarget = function() { + return this.scroller; + }; + this.getTextAreaContainer = function() { + return this.container; + }; + this.$moveTextAreaToCursor = function() { + if (!this.$keepTextAreaAtCursor) + return; + var config = this.layerConfig; + var posTop = this.$cursorLayer.$pixelPos.top; + var posLeft = this.$cursorLayer.$pixelPos.left; + posTop -= config.offset; + + var style = this.textarea.style; + var h = this.lineHeight; + if (posTop < 0 || posTop > config.height - h) { + style.top = style.left = "0"; + return; + } + + var w = this.characterWidth; + if (this.$composition) { + var val = this.textarea.value.replace(/^\x01+/, ""); + w *= (this.session.$getStringScreenWidth(val)[0]+2); + h += 2; + } + posLeft -= this.scrollLeft; + if (posLeft > this.$size.scrollerWidth - w) + posLeft = this.$size.scrollerWidth - w; + + posLeft += this.gutterWidth; + style.height = h + "px"; + style.width = w + "px"; + style.left = Math.min(posLeft, this.$size.scrollerWidth - w) + "px"; + style.top = Math.min(posTop, this.$size.height - h) + "px"; + }; + this.getFirstVisibleRow = function() { + return this.layerConfig.firstRow; + }; + this.getFirstFullyVisibleRow = function() { + return this.layerConfig.firstRow + (this.layerConfig.offset === 0 ? 0 : 1); + }; + this.getLastFullyVisibleRow = function() { + var config = this.layerConfig; + var lastRow = config.lastRow; + var top = this.session.documentToScreenRow(lastRow, 0) * config.lineHeight; + if (top - this.session.getScrollTop() > config.height - config.lineHeight) + return lastRow - 1; + return lastRow; + }; + this.getLastVisibleRow = function() { + return this.layerConfig.lastRow; + }; + + this.$padding = null; + this.setPadding = function(padding) { + this.$padding = padding; + this.$textLayer.setPadding(padding); + this.$cursorLayer.setPadding(padding); + this.$markerFront.setPadding(padding); + this.$markerBack.setPadding(padding); + this.$loop.schedule(this.CHANGE_FULL); + this.$updatePrintMargin(); + }; + + this.setScrollMargin = function(top, bottom, left, right) { + var sm = this.scrollMargin; + sm.top = top|0; + sm.bottom = bottom|0; + sm.right = right|0; + sm.left = left|0; + sm.v = sm.top + sm.bottom; + sm.h = sm.left + sm.right; + if (sm.top && this.scrollTop <= 0 && this.session) + this.session.setScrollTop(-sm.top); + this.updateFull(); + }; + this.getHScrollBarAlwaysVisible = function() { + return this.$hScrollBarAlwaysVisible; + }; + this.setHScrollBarAlwaysVisible = function(alwaysVisible) { + this.setOption("hScrollBarAlwaysVisible", alwaysVisible); + }; + this.getVScrollBarAlwaysVisible = function() { + return this.$vScrollBarAlwaysVisible; + }; + this.setVScrollBarAlwaysVisible = function(alwaysVisible) { + this.setOption("vScrollBarAlwaysVisible", alwaysVisible); + }; + + this.$updateScrollBarV = function() { + var scrollHeight = this.layerConfig.maxHeight; + var scrollerHeight = this.$size.scrollerHeight; + if (!this.$maxLines && this.$scrollPastEnd) { + scrollHeight -= (scrollerHeight - this.lineHeight) * this.$scrollPastEnd; + if (this.scrollTop > scrollHeight - scrollerHeight) { + scrollHeight = this.scrollTop + scrollerHeight; + this.scrollBarV.scrollTop = null; + } + } + this.scrollBarV.setScrollHeight(scrollHeight + this.scrollMargin.v); + this.scrollBarV.setScrollTop(this.scrollTop + this.scrollMargin.top); + }; + this.$updateScrollBarH = function() { + this.scrollBarH.setScrollWidth(this.layerConfig.width + 2 * this.$padding + this.scrollMargin.h); + this.scrollBarH.setScrollLeft(this.scrollLeft + this.scrollMargin.left); + }; + + this.$frozen = false; + this.freeze = function() { + this.$frozen = true; + }; + + this.unfreeze = function() { + this.$frozen = false; + }; + + this.$renderChanges = function(changes, force) { + if (this.$changes) { + changes |= this.$changes; + this.$changes = 0; + } + if ((!this.session || !this.container.offsetWidth || this.$frozen) || (!changes && !force)) { + this.$changes |= changes; + return; + } + if (this.$size.$dirty) { + this.$changes |= changes; + return this.onResize(true); + } + if (!this.lineHeight) { + this.$textLayer.checkForSizeChanges(); + } + + this._signal("beforeRender"); + + if (this.session && this.session.$bidiHandler) + this.session.$bidiHandler.updateCharacterWidths(this.$fontMetrics); + + var config = this.layerConfig; + if (changes & this.CHANGE_FULL || + changes & this.CHANGE_SIZE || + changes & this.CHANGE_TEXT || + changes & this.CHANGE_LINES || + changes & this.CHANGE_SCROLL || + changes & this.CHANGE_H_SCROLL + ) { + changes |= this.$computeLayerConfig(); + if (config.firstRow != this.layerConfig.firstRow && config.firstRowScreen == this.layerConfig.firstRowScreen) { + var st = this.scrollTop + (config.firstRow - this.layerConfig.firstRow) * this.lineHeight; + if (st > 0) { + this.scrollTop = st; + changes = changes | this.CHANGE_SCROLL; + changes |= this.$computeLayerConfig(); + } + } + config = this.layerConfig; + this.$updateScrollBarV(); + if (changes & this.CHANGE_H_SCROLL) + this.$updateScrollBarH(); + this.$gutterLayer.element.style.marginTop = (-config.offset) + "px"; + this.content.style.marginTop = (-config.offset) + "px"; + this.content.style.width = config.width + 2 * this.$padding + "px"; + this.content.style.height = config.minHeight + "px"; + } + if (changes & this.CHANGE_H_SCROLL) { + this.content.style.marginLeft = -this.scrollLeft + "px"; + this.scroller.className = this.scrollLeft <= 0 ? "ace_scroller" : "ace_scroller ace_scroll-left"; + } + if (changes & this.CHANGE_FULL) { + this.$textLayer.update(config); + if (this.$showGutter) + this.$gutterLayer.update(config); + this.$markerBack.update(config); + this.$markerFront.update(config); + this.$cursorLayer.update(config); + this.$moveTextAreaToCursor(); + this.$highlightGutterLine && this.$updateGutterLineHighlight(); + this._signal("afterRender"); + return; + } + if (changes & this.CHANGE_SCROLL) { + if (changes & this.CHANGE_TEXT || changes & this.CHANGE_LINES) + this.$textLayer.update(config); + else + this.$textLayer.scrollLines(config); + + if (this.$showGutter) + this.$gutterLayer.update(config); + this.$markerBack.update(config); + this.$markerFront.update(config); + this.$cursorLayer.update(config); + this.$highlightGutterLine && this.$updateGutterLineHighlight(); + this.$moveTextAreaToCursor(); + this._signal("afterRender"); + return; + } + + if (changes & this.CHANGE_TEXT) { + this.$textLayer.update(config); + if (this.$showGutter) + this.$gutterLayer.update(config); + } + else if (changes & this.CHANGE_LINES) { + if (this.$updateLines() || (changes & this.CHANGE_GUTTER) && this.$showGutter) + this.$gutterLayer.update(config); + } + else if (changes & this.CHANGE_TEXT || changes & this.CHANGE_GUTTER) { + if (this.$showGutter) + this.$gutterLayer.update(config); + } + + if (changes & this.CHANGE_CURSOR) { + this.$cursorLayer.update(config); + this.$moveTextAreaToCursor(); + this.$highlightGutterLine && this.$updateGutterLineHighlight(); + } + + if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_FRONT)) { + this.$markerFront.update(config); + } + + if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_BACK)) { + this.$markerBack.update(config); + } + + this._signal("afterRender"); + }; + + + this.$autosize = function() { + var height = this.session.getScreenLength() * this.lineHeight; + var maxHeight = this.$maxLines * this.lineHeight; + var desiredHeight = Math.min(maxHeight, + Math.max((this.$minLines || 1) * this.lineHeight, height) + ) + this.scrollMargin.v + (this.$extraHeight || 0); + if (this.$horizScroll) + desiredHeight += this.scrollBarH.getHeight(); + if (this.$maxPixelHeight && desiredHeight > this.$maxPixelHeight) + desiredHeight = this.$maxPixelHeight; + var vScroll = height > maxHeight; + + if (desiredHeight != this.desiredHeight || + this.$size.height != this.desiredHeight || vScroll != this.$vScroll) { + if (vScroll != this.$vScroll) { + this.$vScroll = vScroll; + this.scrollBarV.setVisible(vScroll); + } + + var w = this.container.clientWidth; + this.container.style.height = desiredHeight + "px"; + this.$updateCachedSize(true, this.$gutterWidth, w, desiredHeight); + this.desiredHeight = desiredHeight; + + this._signal("autosize"); + } + }; + + this.$computeLayerConfig = function() { + var session = this.session; + var size = this.$size; + + var hideScrollbars = size.height <= 2 * this.lineHeight; + var screenLines = this.session.getScreenLength(); + var maxHeight = screenLines * this.lineHeight; + + var longestLine = this.$getLongestLine(); + + var horizScroll = !hideScrollbars && (this.$hScrollBarAlwaysVisible || + size.scrollerWidth - longestLine - 2 * this.$padding < 0); + + var hScrollChanged = this.$horizScroll !== horizScroll; + if (hScrollChanged) { + this.$horizScroll = horizScroll; + this.scrollBarH.setVisible(horizScroll); + } + var vScrollBefore = this.$vScroll; // autosize can change vscroll value in which case we need to update longestLine + if (this.$maxLines && this.lineHeight > 1) + this.$autosize(); + + var offset = this.scrollTop % this.lineHeight; + var minHeight = size.scrollerHeight + this.lineHeight; + + var scrollPastEnd = !this.$maxLines && this.$scrollPastEnd + ? (size.scrollerHeight - this.lineHeight) * this.$scrollPastEnd + : 0; + maxHeight += scrollPastEnd; + + var sm = this.scrollMargin; + this.session.setScrollTop(Math.max(-sm.top, + Math.min(this.scrollTop, maxHeight - size.scrollerHeight + sm.bottom))); + + this.session.setScrollLeft(Math.max(-sm.left, Math.min(this.scrollLeft, + longestLine + 2 * this.$padding - size.scrollerWidth + sm.right))); + + var vScroll = !hideScrollbars && (this.$vScrollBarAlwaysVisible || + size.scrollerHeight - maxHeight + scrollPastEnd < 0 || this.scrollTop > sm.top); + var vScrollChanged = vScrollBefore !== vScroll; + if (vScrollChanged) { + this.$vScroll = vScroll; + this.scrollBarV.setVisible(vScroll); + } + + var lineCount = Math.ceil(minHeight / this.lineHeight) - 1; + var firstRow = Math.max(0, Math.round((this.scrollTop - offset) / this.lineHeight)); + var lastRow = firstRow + lineCount; + var firstRowScreen, firstRowHeight; + var lineHeight = this.lineHeight; + firstRow = session.screenToDocumentRow(firstRow, 0); + var foldLine = session.getFoldLine(firstRow); + if (foldLine) { + firstRow = foldLine.start.row; + } + + firstRowScreen = session.documentToScreenRow(firstRow, 0); + firstRowHeight = session.getRowLength(firstRow) * lineHeight; + + lastRow = Math.min(session.screenToDocumentRow(lastRow, 0), session.getLength() - 1); + minHeight = size.scrollerHeight + session.getRowLength(lastRow) * lineHeight + + firstRowHeight; + + offset = this.scrollTop - firstRowScreen * lineHeight; + + var changes = 0; + if (this.layerConfig.width != longestLine) + changes = this.CHANGE_H_SCROLL; + if (hScrollChanged || vScrollChanged) { + changes = this.$updateCachedSize(true, this.gutterWidth, size.width, size.height); + this._signal("scrollbarVisibilityChanged"); + if (vScrollChanged) + longestLine = this.$getLongestLine(); + } + + this.layerConfig = { + width : longestLine, + padding : this.$padding, + firstRow : firstRow, + firstRowScreen: firstRowScreen, + lastRow : lastRow, + lineHeight : lineHeight, + characterWidth : this.characterWidth, + minHeight : minHeight, + maxHeight : maxHeight, + offset : offset, + gutterOffset : lineHeight ? Math.max(0, Math.ceil((offset + size.height - size.scrollerHeight) / lineHeight)) : 0, + height : this.$size.scrollerHeight + }; + + return changes; + }; + + this.$updateLines = function() { + if (!this.$changedLines) return; + var firstRow = this.$changedLines.firstRow; + var lastRow = this.$changedLines.lastRow; + this.$changedLines = null; + + var layerConfig = this.layerConfig; + + if (firstRow > layerConfig.lastRow + 1) { return; } + if (lastRow < layerConfig.firstRow) { return; } + if (lastRow === Infinity) { + if (this.$showGutter) + this.$gutterLayer.update(layerConfig); + this.$textLayer.update(layerConfig); + return; + } + this.$textLayer.updateLines(layerConfig, firstRow, lastRow); + return true; + }; + + this.$getLongestLine = function() { + var charCount = this.session.getScreenWidth(); + if (this.showInvisibles && !this.session.$useWrapMode) + charCount += 1; + + return Math.max(this.$size.scrollerWidth - 2 * this.$padding, Math.round(charCount * this.characterWidth)); + }; + this.updateFrontMarkers = function() { + this.$markerFront.setMarkers(this.session.getMarkers(true)); + this.$loop.schedule(this.CHANGE_MARKER_FRONT); + }; + this.updateBackMarkers = function() { + this.$markerBack.setMarkers(this.session.getMarkers()); + this.$loop.schedule(this.CHANGE_MARKER_BACK); + }; + this.addGutterDecoration = function(row, className){ + this.$gutterLayer.addGutterDecoration(row, className); + }; + this.removeGutterDecoration = function(row, className){ + this.$gutterLayer.removeGutterDecoration(row, className); + }; + this.updateBreakpoints = function(rows) { + this.$loop.schedule(this.CHANGE_GUTTER); + }; + this.setAnnotations = function(annotations) { + this.$gutterLayer.setAnnotations(annotations); + this.$loop.schedule(this.CHANGE_GUTTER); + }; + this.updateCursor = function() { + this.$loop.schedule(this.CHANGE_CURSOR); + }; + this.hideCursor = function() { + this.$cursorLayer.hideCursor(); + }; + this.showCursor = function() { + this.$cursorLayer.showCursor(); + }; + + this.scrollSelectionIntoView = function(anchor, lead, offset) { + this.scrollCursorIntoView(anchor, offset); + this.scrollCursorIntoView(lead, offset); + }; + this.scrollCursorIntoView = function(cursor, offset, $viewMargin) { + if (this.$size.scrollerHeight === 0) + return; + + var pos = this.$cursorLayer.getPixelPosition(cursor); + + var left = pos.left; + var top = pos.top; + + var topMargin = $viewMargin && $viewMargin.top || 0; + var bottomMargin = $viewMargin && $viewMargin.bottom || 0; + + var scrollTop = this.$scrollAnimation ? this.session.getScrollTop() : this.scrollTop; + + if (scrollTop + topMargin > top) { + if (offset && scrollTop + topMargin > top + this.lineHeight) + top -= offset * this.$size.scrollerHeight; + if (top === 0) + top = -this.scrollMargin.top; + this.session.setScrollTop(top); + } else if (scrollTop + this.$size.scrollerHeight - bottomMargin < top + this.lineHeight) { + if (offset && scrollTop + this.$size.scrollerHeight - bottomMargin < top - this.lineHeight) + top += offset * this.$size.scrollerHeight; + this.session.setScrollTop(top + this.lineHeight - this.$size.scrollerHeight); + } + + var scrollLeft = this.scrollLeft; + + if (scrollLeft > left) { + if (left < this.$padding + 2 * this.layerConfig.characterWidth) + left = -this.scrollMargin.left; + this.session.setScrollLeft(left); + } else if (scrollLeft + this.$size.scrollerWidth < left + this.characterWidth) { + this.session.setScrollLeft(Math.round(left + this.characterWidth - this.$size.scrollerWidth)); + } else if (scrollLeft <= this.$padding && left - scrollLeft < this.characterWidth) { + this.session.setScrollLeft(0); + } + }; + this.getScrollTop = function() { + return this.session.getScrollTop(); + }; + this.getScrollLeft = function() { + return this.session.getScrollLeft(); + }; + this.getScrollTopRow = function() { + return this.scrollTop / this.lineHeight; + }; + this.getScrollBottomRow = function() { + return Math.max(0, Math.floor((this.scrollTop + this.$size.scrollerHeight) / this.lineHeight) - 1); + }; + this.scrollToRow = function(row) { + this.session.setScrollTop(row * this.lineHeight); + }; + + this.alignCursor = function(cursor, alignment) { + if (typeof cursor == "number") + cursor = {row: cursor, column: 0}; + + var pos = this.$cursorLayer.getPixelPosition(cursor); + var h = this.$size.scrollerHeight - this.lineHeight; + var offset = pos.top - h * (alignment || 0); + + this.session.setScrollTop(offset); + return offset; + }; + + this.STEPS = 8; + this.$calcSteps = function(fromValue, toValue){ + var i = 0; + var l = this.STEPS; + var steps = []; + + var func = function(t, x_min, dx) { + return dx * (Math.pow(t - 1, 3) + 1) + x_min; + }; + + for (i = 0; i < l; ++i) + steps.push(func(i / this.STEPS, fromValue, toValue - fromValue)); + + return steps; + }; + this.scrollToLine = function(line, center, animate, callback) { + var pos = this.$cursorLayer.getPixelPosition({row: line, column: 0}); + var offset = pos.top; + if (center) + offset -= this.$size.scrollerHeight / 2; + + var initialScroll = this.scrollTop; + this.session.setScrollTop(offset); + if (animate !== false) + this.animateScrolling(initialScroll, callback); + }; + + this.animateScrolling = function(fromValue, callback) { + var toValue = this.scrollTop; + if (!this.$animatedScroll) + return; + var _self = this; + + if (fromValue == toValue) + return; + + if (this.$scrollAnimation) { + var oldSteps = this.$scrollAnimation.steps; + if (oldSteps.length) { + fromValue = oldSteps[0]; + if (fromValue == toValue) + return; + } + } + + var steps = _self.$calcSteps(fromValue, toValue); + this.$scrollAnimation = {from: fromValue, to: toValue, steps: steps}; + + clearInterval(this.$timer); + + _self.session.setScrollTop(steps.shift()); + _self.session.$scrollTop = toValue; + this.$timer = setInterval(function() { + if (steps.length) { + _self.session.setScrollTop(steps.shift()); + _self.session.$scrollTop = toValue; + } else if (toValue != null) { + _self.session.$scrollTop = -1; + _self.session.setScrollTop(toValue); + toValue = null; + } else { + _self.$timer = clearInterval(_self.$timer); + _self.$scrollAnimation = null; + callback && callback(); + } + }, 10); + }; + this.scrollToY = function(scrollTop) { + if (this.scrollTop !== scrollTop) { + this.$loop.schedule(this.CHANGE_SCROLL); + this.scrollTop = scrollTop; + } + }; + this.scrollToX = function(scrollLeft) { + if (this.scrollLeft !== scrollLeft) + this.scrollLeft = scrollLeft; + this.$loop.schedule(this.CHANGE_H_SCROLL); + }; + this.scrollTo = function(x, y) { + this.session.setScrollTop(y); + this.session.setScrollLeft(y); + }; + this.scrollBy = function(deltaX, deltaY) { + deltaY && this.session.setScrollTop(this.session.getScrollTop() + deltaY); + deltaX && this.session.setScrollLeft(this.session.getScrollLeft() + deltaX); + }; + this.isScrollableBy = function(deltaX, deltaY) { + if (deltaY < 0 && this.session.getScrollTop() >= 1 - this.scrollMargin.top) + return true; + if (deltaY > 0 && this.session.getScrollTop() + this.$size.scrollerHeight + - this.layerConfig.maxHeight < -1 + this.scrollMargin.bottom) + return true; + if (deltaX < 0 && this.session.getScrollLeft() >= 1 - this.scrollMargin.left) + return true; + if (deltaX > 0 && this.session.getScrollLeft() + this.$size.scrollerWidth + - this.layerConfig.width < -1 + this.scrollMargin.right) + return true; + }; + + this.pixelToScreenCoordinates = function(x, y) { + var canvasPos = this.scroller.getBoundingClientRect(); + + var offsetX = x + this.scrollLeft - canvasPos.left - this.$padding; + var offset = offsetX / this.characterWidth; + var row = Math.floor((y + this.scrollTop - canvasPos.top) / this.lineHeight); + var col = Math.round(offset); + + return {row: row, column: col, side: offset - col > 0 ? 1 : -1, offsetX: offsetX}; + }; + + this.screenToTextCoordinates = function(x, y) { + var canvasPos = this.scroller.getBoundingClientRect(); + var offsetX = x + this.scrollLeft - canvasPos.left - this.$padding; + + var col = Math.round(offsetX / this.characterWidth); + + var row = (y + this.scrollTop - canvasPos.top) / this.lineHeight; + + return this.session.screenToDocumentPosition(row, Math.max(col, 0), offsetX); + }; + this.textToScreenCoordinates = function(row, column) { + var canvasPos = this.scroller.getBoundingClientRect(); + var pos = this.session.documentToScreenPosition(row, column); + + var x = this.$padding + (this.session.$bidiHandler.isBidiRow(pos.row, row) + ? this.session.$bidiHandler.getPosLeft(pos.column) + : Math.round(pos.column * this.characterWidth)); + + var y = pos.row * this.lineHeight; + + return { + pageX: canvasPos.left + x - this.scrollLeft, + pageY: canvasPos.top + y - this.scrollTop + }; + }; + this.visualizeFocus = function() { + dom.addCssClass(this.container, "ace_focus"); + }; + this.visualizeBlur = function() { + dom.removeCssClass(this.container, "ace_focus"); + }; + this.showComposition = function(position) { + if (!this.$composition) + this.$composition = { + keepTextAreaAtCursor: this.$keepTextAreaAtCursor, + cssText: this.textarea.style.cssText + }; + + this.$keepTextAreaAtCursor = true; + dom.addCssClass(this.textarea, "ace_composition"); + this.textarea.style.cssText = ""; + this.$moveTextAreaToCursor(); + }; + this.setCompositionText = function(text) { + this.$moveTextAreaToCursor(); + }; + this.hideComposition = function() { + if (!this.$composition) + return; + + dom.removeCssClass(this.textarea, "ace_composition"); + this.$keepTextAreaAtCursor = this.$composition.keepTextAreaAtCursor; + this.textarea.style.cssText = this.$composition.cssText; + this.$composition = null; + }; + this.setTheme = function(theme, cb) { + var _self = this; + this.$themeId = theme; + _self._dispatchEvent('themeChange',{theme:theme}); + + if (!theme || typeof theme == "string") { + var moduleName = theme || this.$options.theme.initialValue; + config.loadModule(["theme", moduleName], afterLoad); + } else { + afterLoad(theme); + } + + function afterLoad(module) { + if (_self.$themeId != theme) + return cb && cb(); + if (!module || !module.cssClass) + throw new Error("couldn't load module " + theme + " or it didn't call define"); + dom.importCssString( + module.cssText, + module.cssClass, + _self.container.ownerDocument + ); + + if (_self.theme) + dom.removeCssClass(_self.container, _self.theme.cssClass); + + var padding = "padding" in module ? module.padding + : "padding" in (_self.theme || {}) ? 4 : _self.$padding; + if (_self.$padding && padding != _self.$padding) + _self.setPadding(padding); + _self.$theme = module.cssClass; + + _self.theme = module; + dom.addCssClass(_self.container, module.cssClass); + dom.setCssClass(_self.container, "ace_dark", module.isDark); + if (_self.$size) { + _self.$size.width = 0; + _self.$updateSizeAsync(); + } + + _self._dispatchEvent('themeLoaded', {theme:module}); + cb && cb(); + } + }; + this.getTheme = function() { + return this.$themeId; + }; + this.setStyle = function(style, include) { + dom.setCssClass(this.container, style, include !== false); + }; + this.unsetStyle = function(style) { + dom.removeCssClass(this.container, style); + }; + + this.setCursorStyle = function(style) { + if (this.scroller.style.cursor != style) + this.scroller.style.cursor = style; + }; + this.setMouseCursor = function(cursorStyle) { + this.scroller.style.cursor = cursorStyle; + }; + this.destroy = function() { + this.$textLayer.destroy(); + this.$cursorLayer.destroy(); + }; + +}).call(VirtualRenderer.prototype); + + +config.defineOptions(VirtualRenderer.prototype, "renderer", { + animatedScroll: {initialValue: false}, + showInvisibles: { + set: function(value) { + if (this.$textLayer.setShowInvisibles(value)) + this.$loop.schedule(this.CHANGE_TEXT); + }, + initialValue: false + }, + showPrintMargin: { + set: function() { this.$updatePrintMargin(); }, + initialValue: true + }, + printMarginColumn: { + set: function() { this.$updatePrintMargin(); }, + initialValue: 80 + }, + printMargin: { + set: function(val) { + if (typeof val == "number") + this.$printMarginColumn = val; + this.$showPrintMargin = !!val; + this.$updatePrintMargin(); + }, + get: function() { + return this.$showPrintMargin && this.$printMarginColumn; + } + }, + showGutter: { + set: function(show){ + this.$gutter.style.display = show ? "block" : "none"; + this.$loop.schedule(this.CHANGE_FULL); + this.onGutterResize(); + }, + initialValue: true + }, + fadeFoldWidgets: { + set: function(show) { + dom.setCssClass(this.$gutter, "ace_fade-fold-widgets", show); + }, + initialValue: false + }, + showFoldWidgets: { + set: function(show) {this.$gutterLayer.setShowFoldWidgets(show);}, + initialValue: true + }, + showLineNumbers: { + set: function(show) { + this.$gutterLayer.setShowLineNumbers(show); + this.$loop.schedule(this.CHANGE_GUTTER); + }, + initialValue: true + }, + displayIndentGuides: { + set: function(show) { + if (this.$textLayer.setDisplayIndentGuides(show)) + this.$loop.schedule(this.CHANGE_TEXT); + }, + initialValue: true + }, + highlightGutterLine: { + set: function(shouldHighlight) { + if (!this.$gutterLineHighlight) { + this.$gutterLineHighlight = dom.createElement("div"); + this.$gutterLineHighlight.className = "ace_gutter-active-line"; + this.$gutter.appendChild(this.$gutterLineHighlight); + return; + } + + this.$gutterLineHighlight.style.display = shouldHighlight ? "" : "none"; + if (this.$cursorLayer.$pixelPos) + this.$updateGutterLineHighlight(); + }, + initialValue: false, + value: true + }, + hScrollBarAlwaysVisible: { + set: function(val) { + if (!this.$hScrollBarAlwaysVisible || !this.$horizScroll) + this.$loop.schedule(this.CHANGE_SCROLL); + }, + initialValue: false + }, + vScrollBarAlwaysVisible: { + set: function(val) { + if (!this.$vScrollBarAlwaysVisible || !this.$vScroll) + this.$loop.schedule(this.CHANGE_SCROLL); + }, + initialValue: false + }, + fontSize: { + set: function(size) { + if (typeof size == "number") + size = size + "px"; + this.container.style.fontSize = size; + this.updateFontSize(); + }, + initialValue: 12 + }, + fontFamily: { + set: function(name) { + this.container.style.fontFamily = name; + this.updateFontSize(); + } + }, + maxLines: { + set: function(val) { + this.updateFull(); + } + }, + minLines: { + set: function(val) { + this.updateFull(); + } + }, + maxPixelHeight: { + set: function(val) { + this.updateFull(); + }, + initialValue: 0 + }, + scrollPastEnd: { + set: function(val) { + val = +val || 0; + if (this.$scrollPastEnd == val) + return; + this.$scrollPastEnd = val; + this.$loop.schedule(this.CHANGE_SCROLL); + }, + initialValue: 0, + handlesSet: true + }, + fixedWidthGutter: { + set: function(val) { + this.$gutterLayer.$fixedWidth = !!val; + this.$loop.schedule(this.CHANGE_GUTTER); + } + }, + theme: { + set: function(val) { this.setTheme(val); }, + get: function() { return this.$themeId || this.theme; }, + initialValue: "./theme/textmate", + handlesSet: true + } +}); + +exports.VirtualRenderer = VirtualRenderer; +}); + +ace.define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/net","ace/lib/event_emitter","ace/config"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var net = acequire("../lib/net"); +var EventEmitter = acequire("../lib/event_emitter").EventEmitter; +var config = acequire("../config"); + +function $workerBlob(workerUrl, mod) { + var script = mod.src;"importScripts('" + net.qualifyURL(workerUrl) + "');"; + try { + return new Blob([script], {"type": "application/javascript"}); + } catch (e) { // Backwards-compatibility + var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder; + var blobBuilder = new BlobBuilder(); + blobBuilder.append(script); + return blobBuilder.getBlob("application/javascript"); + } +} + +function createWorker(workerUrl, mod) { + var blob = $workerBlob(workerUrl, mod); + var URL = window.URL || window.webkitURL; + var blobURL = URL.createObjectURL(blob); + return new Worker(blobURL); +} + +var WorkerClient = function(topLevelNamespaces, mod, classname, workerUrl, importScripts) { + this.$sendDeltaQueue = this.$sendDeltaQueue.bind(this); + this.changeListener = this.changeListener.bind(this); + this.onMessage = this.onMessage.bind(this); + if (acequire.nameToUrl && !acequire.toUrl) + acequire.toUrl = acequire.nameToUrl; + + if (config.get("packaged") || !acequire.toUrl) { + workerUrl = workerUrl || config.moduleUrl(mod.id, "worker"); + } else { + var normalizePath = this.$normalizePath; + workerUrl = workerUrl || normalizePath(acequire.toUrl("ace/worker/worker.js", null, "_")); + + var tlns = {}; + topLevelNamespaces.forEach(function(ns) { + tlns[ns] = normalizePath(acequire.toUrl(ns, null, "_").replace(/(\.js)?(\?.*)?$/, "")); + }); + } + + this.$worker = createWorker(workerUrl, mod); + if (importScripts) { + this.send("importScripts", importScripts); + } + this.$worker.postMessage({ + init : true, + tlns : tlns, + module : mod.id, + classname : classname + }); + + this.callbackId = 1; + this.callbacks = {}; + + this.$worker.onmessage = this.onMessage; +}; + +(function(){ + + oop.implement(this, EventEmitter); + + this.onMessage = function(e) { + var msg = e.data; + switch (msg.type) { + case "event": + this._signal(msg.name, {data: msg.data}); + break; + case "call": + var callback = this.callbacks[msg.id]; + if (callback) { + callback(msg.data); + delete this.callbacks[msg.id]; + } + break; + case "error": + this.reportError(msg.data); + break; + case "log": + window.console && console.log && console.log.apply(console, msg.data); + break; + } + }; + + this.reportError = function(err) { + window.console && console.error && console.error(err); + }; + + this.$normalizePath = function(path) { + return net.qualifyURL(path); + }; + + this.terminate = function() { + this._signal("terminate", {}); + this.deltaQueue = null; + this.$worker.terminate(); + this.$worker = null; + if (this.$doc) + this.$doc.off("change", this.changeListener); + this.$doc = null; + }; + + this.send = function(cmd, args) { + this.$worker.postMessage({command: cmd, args: args}); + }; + + this.call = function(cmd, args, callback) { + if (callback) { + var id = this.callbackId++; + this.callbacks[id] = callback; + args.push(id); + } + this.send(cmd, args); + }; + + this.emit = function(event, data) { + try { + this.$worker.postMessage({event: event, data: {data: data.data}}); + } + catch(ex) { + console.error(ex.stack); + } + }; + + this.attachToDocument = function(doc) { + if (this.$doc) + this.terminate(); + + this.$doc = doc; + this.call("setValue", [doc.getValue()]); + doc.on("change", this.changeListener); + }; + + this.changeListener = function(delta) { + if (!this.deltaQueue) { + this.deltaQueue = []; + setTimeout(this.$sendDeltaQueue, 0); + } + if (delta.action == "insert") + this.deltaQueue.push(delta.start, delta.lines); + else + this.deltaQueue.push(delta.start, delta.end); + }; + + this.$sendDeltaQueue = function() { + var q = this.deltaQueue; + if (!q) return; + this.deltaQueue = null; + if (q.length > 50 && q.length > this.$doc.getLength() >> 1) { + this.call("setValue", [this.$doc.getValue()]); + } else + this.emit("change", {data: q}); + }; + +}).call(WorkerClient.prototype); + + +var UIWorkerClient = function(topLevelNamespaces, mod, classname) { + this.$sendDeltaQueue = this.$sendDeltaQueue.bind(this); + this.changeListener = this.changeListener.bind(this); + this.callbackId = 1; + this.callbacks = {}; + this.messageBuffer = []; + + var main = null; + var emitSync = false; + var sender = Object.create(EventEmitter); + var _self = this; + + this.$worker = {}; + this.$worker.terminate = function() {}; + this.$worker.postMessage = function(e) { + _self.messageBuffer.push(e); + if (main) { + if (emitSync) + setTimeout(processNext); + else + processNext(); + } + }; + this.setEmitSync = function(val) { emitSync = val; }; + + var processNext = function() { + var msg = _self.messageBuffer.shift(); + if (msg.command) + main[msg.command].apply(main, msg.args); + else if (msg.event) + sender._signal(msg.event, msg.data); + }; + + sender.postMessage = function(msg) { + _self.onMessage({data: msg}); + }; + sender.callback = function(data, callbackId) { + this.postMessage({type: "call", id: callbackId, data: data}); + }; + sender.emit = function(name, data) { + this.postMessage({type: "event", name: name, data: data}); + }; + + config.loadModule(["worker", mod], function(Main) { + main = new Main[classname](sender); + while (_self.messageBuffer.length) + processNext(); + }); +}; + +UIWorkerClient.prototype = WorkerClient.prototype; + +exports.UIWorkerClient = UIWorkerClient; +exports.WorkerClient = WorkerClient; +exports.createWorker = createWorker; + + +}); + +ace.define("ace/placeholder",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/oop"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("./range").Range; +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var oop = acequire("./lib/oop"); + +var PlaceHolder = function(session, length, pos, others, mainClass, othersClass) { + var _self = this; + this.length = length; + this.session = session; + this.doc = session.getDocument(); + this.mainClass = mainClass; + this.othersClass = othersClass; + this.$onUpdate = this.onUpdate.bind(this); + this.doc.on("change", this.$onUpdate); + this.$others = others; + + this.$onCursorChange = function() { + setTimeout(function() { + _self.onCursorChange(); + }); + }; + + this.$pos = pos; + var undoStack = session.getUndoManager().$undoStack || session.getUndoManager().$undostack || {length: -1}; + this.$undoStackDepth = undoStack.length; + this.setup(); + + session.selection.on("changeCursor", this.$onCursorChange); +}; + +(function() { + + oop.implement(this, EventEmitter); + this.setup = function() { + var _self = this; + var doc = this.doc; + var session = this.session; + + this.selectionBefore = session.selection.toJSON(); + if (session.selection.inMultiSelectMode) + session.selection.toSingleRange(); + + this.pos = doc.createAnchor(this.$pos.row, this.$pos.column); + var pos = this.pos; + pos.$insertRight = true; + pos.detach(); + pos.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column + this.length), this.mainClass, null, false); + this.others = []; + this.$others.forEach(function(other) { + var anchor = doc.createAnchor(other.row, other.column); + anchor.$insertRight = true; + anchor.detach(); + _self.others.push(anchor); + }); + session.setUndoSelect(false); + }; + this.showOtherMarkers = function() { + if (this.othersActive) return; + var session = this.session; + var _self = this; + this.othersActive = true; + this.others.forEach(function(anchor) { + anchor.markerId = session.addMarker(new Range(anchor.row, anchor.column, anchor.row, anchor.column+_self.length), _self.othersClass, null, false); + }); + }; + this.hideOtherMarkers = function() { + if (!this.othersActive) return; + this.othersActive = false; + for (var i = 0; i < this.others.length; i++) { + this.session.removeMarker(this.others[i].markerId); + } + }; + this.onUpdate = function(delta) { + if (this.$updating) + return this.updateAnchors(delta); + + var range = delta; + if (range.start.row !== range.end.row) return; + if (range.start.row !== this.pos.row) return; + this.$updating = true; + var lengthDiff = delta.action === "insert" ? range.end.column - range.start.column : range.start.column - range.end.column; + var inMainRange = range.start.column >= this.pos.column && range.start.column <= this.pos.column + this.length + 1; + var distanceFromStart = range.start.column - this.pos.column; + + this.updateAnchors(delta); + + if (inMainRange) + this.length += lengthDiff; + + if (inMainRange && !this.session.$fromUndo) { + if (delta.action === 'insert') { + for (var i = this.others.length - 1; i >= 0; i--) { + var otherPos = this.others[i]; + var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart}; + this.doc.insertMergedLines(newPos, delta.lines); + } + } else if (delta.action === 'remove') { + for (var i = this.others.length - 1; i >= 0; i--) { + var otherPos = this.others[i]; + var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart}; + this.doc.remove(new Range(newPos.row, newPos.column, newPos.row, newPos.column - lengthDiff)); + } + } + } + + this.$updating = false; + this.updateMarkers(); + }; + + this.updateAnchors = function(delta) { + this.pos.onChange(delta); + for (var i = this.others.length; i--;) + this.others[i].onChange(delta); + this.updateMarkers(); + }; + + this.updateMarkers = function() { + if (this.$updating) + return; + var _self = this; + var session = this.session; + var updateMarker = function(pos, className) { + session.removeMarker(pos.markerId); + pos.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column+_self.length), className, null, false); + }; + updateMarker(this.pos, this.mainClass); + for (var i = this.others.length; i--;) + updateMarker(this.others[i], this.othersClass); + }; + + this.onCursorChange = function(event) { + if (this.$updating || !this.session) return; + var pos = this.session.selection.getCursor(); + if (pos.row === this.pos.row && pos.column >= this.pos.column && pos.column <= this.pos.column + this.length) { + this.showOtherMarkers(); + this._emit("cursorEnter", event); + } else { + this.hideOtherMarkers(); + this._emit("cursorLeave", event); + } + }; + this.detach = function() { + this.session.removeMarker(this.pos && this.pos.markerId); + this.hideOtherMarkers(); + this.doc.removeEventListener("change", this.$onUpdate); + this.session.selection.removeEventListener("changeCursor", this.$onCursorChange); + this.session.setUndoSelect(true); + this.session = null; + }; + this.cancel = function() { + if (this.$undoStackDepth === -1) + return; + var undoManager = this.session.getUndoManager(); + var undosRequired = (undoManager.$undoStack || undoManager.$undostack).length - this.$undoStackDepth; + for (var i = 0; i < undosRequired; i++) { + undoManager.undo(true); + } + if (this.selectionBefore) + this.session.selection.fromJSON(this.selectionBefore); + }; +}).call(PlaceHolder.prototype); + + +exports.PlaceHolder = PlaceHolder; +}); + +ace.define("ace/mouse/multi_select_handler",["require","exports","module","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) { + +var event = acequire("../lib/event"); +var useragent = acequire("../lib/useragent"); +function isSamePoint(p1, p2) { + return p1.row == p2.row && p1.column == p2.column; +} + +function onMouseDown(e) { + var ev = e.domEvent; + var alt = ev.altKey; + var shift = ev.shiftKey; + var ctrl = ev.ctrlKey; + var accel = e.getAccelKey(); + var button = e.getButton(); + + if (ctrl && useragent.isMac) + button = ev.button; + + if (e.editor.inMultiSelectMode && button == 2) { + e.editor.textInput.onContextMenu(e.domEvent); + return; + } + + if (!ctrl && !alt && !accel) { + if (button === 0 && e.editor.inMultiSelectMode) + e.editor.exitMultiSelectMode(); + return; + } + + if (button !== 0) + return; + + var editor = e.editor; + var selection = editor.selection; + var isMultiSelect = editor.inMultiSelectMode; + var pos = e.getDocumentPosition(); + var cursor = selection.getCursor(); + var inSelection = e.inSelection() || (selection.isEmpty() && isSamePoint(pos, cursor)); + + var mouseX = e.x, mouseY = e.y; + var onMouseSelection = function(e) { + mouseX = e.clientX; + mouseY = e.clientY; + }; + + var session = editor.session; + var screenAnchor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY); + var screenCursor = screenAnchor; + + var selectionMode; + if (editor.$mouseHandler.$enableJumpToDef) { + if (ctrl && alt || accel && alt) + selectionMode = shift ? "block" : "add"; + else if (alt && editor.$blockSelectEnabled) + selectionMode = "block"; + } else { + if (accel && !alt) { + selectionMode = "add"; + if (!isMultiSelect && shift) + return; + } else if (alt && editor.$blockSelectEnabled) { + selectionMode = "block"; + } + } + + if (selectionMode && useragent.isMac && ev.ctrlKey) { + editor.$mouseHandler.cancelContextMenu(); + } + + if (selectionMode == "add") { + if (!isMultiSelect && inSelection) + return; // dragging + + if (!isMultiSelect) { + var range = selection.toOrientedRange(); + editor.addSelectionMarker(range); + } + + var oldRange = selection.rangeList.rangeAtPoint(pos); + + + editor.$blockScrolling++; + editor.inVirtualSelectionMode = true; + + if (shift) { + oldRange = null; + range = selection.ranges[0] || range; + editor.removeSelectionMarker(range); + } + editor.once("mouseup", function() { + var tmpSel = selection.toOrientedRange(); + + if (oldRange && tmpSel.isEmpty() && isSamePoint(oldRange.cursor, tmpSel.cursor)) + selection.substractPoint(tmpSel.cursor); + else { + if (shift) { + selection.substractPoint(range.cursor); + } else if (range) { + editor.removeSelectionMarker(range); + selection.addRange(range); + } + selection.addRange(tmpSel); + } + editor.$blockScrolling--; + editor.inVirtualSelectionMode = false; + }); + + } else if (selectionMode == "block") { + e.stop(); + editor.inVirtualSelectionMode = true; + var initialRange; + var rectSel = []; + var blockSelect = function() { + var newCursor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY); + var cursor = session.screenToDocumentPosition(newCursor.row, newCursor.column, newCursor.offsetX); + + if (isSamePoint(screenCursor, newCursor) && isSamePoint(cursor, selection.lead)) + return; + screenCursor = newCursor; + + editor.$blockScrolling++; + editor.selection.moveToPosition(cursor); + editor.renderer.scrollCursorIntoView(); + + editor.removeSelectionMarkers(rectSel); + rectSel = selection.rectangularRangeBlock(screenCursor, screenAnchor); + if (editor.$mouseHandler.$clickSelection && rectSel.length == 1 && rectSel[0].isEmpty()) + rectSel[0] = editor.$mouseHandler.$clickSelection.clone(); + rectSel.forEach(editor.addSelectionMarker, editor); + editor.updateSelectionMarkers(); + editor.$blockScrolling--; + }; + editor.$blockScrolling++; + if (isMultiSelect && !accel) { + selection.toSingleRange(); + } else if (!isMultiSelect && accel) { + initialRange = selection.toOrientedRange(); + editor.addSelectionMarker(initialRange); + } + + if (shift) + screenAnchor = session.documentToScreenPosition(selection.lead); + else + selection.moveToPosition(pos); + editor.$blockScrolling--; + + screenCursor = {row: -1, column: -1}; + + var onMouseSelectionEnd = function(e) { + clearInterval(timerId); + editor.removeSelectionMarkers(rectSel); + if (!rectSel.length) + rectSel = [selection.toOrientedRange()]; + editor.$blockScrolling++; + if (initialRange) { + editor.removeSelectionMarker(initialRange); + selection.toSingleRange(initialRange); + } + for (var i = 0; i < rectSel.length; i++) + selection.addRange(rectSel[i]); + editor.inVirtualSelectionMode = false; + editor.$mouseHandler.$clickSelection = null; + editor.$blockScrolling--; + }; + + var onSelectionInterval = blockSelect; + + event.capture(editor.container, onMouseSelection, onMouseSelectionEnd); + var timerId = setInterval(function() {onSelectionInterval();}, 20); + + return e.preventDefault(); + } +} + + +exports.onMouseDown = onMouseDown; + +}); + +ace.define("ace/commands/multi_select_commands",["require","exports","module","ace/keyboard/hash_handler"], function(acequire, exports, module) { +exports.defaultCommands = [{ + name: "addCursorAbove", + exec: function(editor) { editor.selectMoreLines(-1); }, + bindKey: {win: "Ctrl-Alt-Up", mac: "Ctrl-Alt-Up"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "addCursorBelow", + exec: function(editor) { editor.selectMoreLines(1); }, + bindKey: {win: "Ctrl-Alt-Down", mac: "Ctrl-Alt-Down"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "addCursorAboveSkipCurrent", + exec: function(editor) { editor.selectMoreLines(-1, true); }, + bindKey: {win: "Ctrl-Alt-Shift-Up", mac: "Ctrl-Alt-Shift-Up"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "addCursorBelowSkipCurrent", + exec: function(editor) { editor.selectMoreLines(1, true); }, + bindKey: {win: "Ctrl-Alt-Shift-Down", mac: "Ctrl-Alt-Shift-Down"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectMoreBefore", + exec: function(editor) { editor.selectMore(-1); }, + bindKey: {win: "Ctrl-Alt-Left", mac: "Ctrl-Alt-Left"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectMoreAfter", + exec: function(editor) { editor.selectMore(1); }, + bindKey: {win: "Ctrl-Alt-Right", mac: "Ctrl-Alt-Right"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectNextBefore", + exec: function(editor) { editor.selectMore(-1, true); }, + bindKey: {win: "Ctrl-Alt-Shift-Left", mac: "Ctrl-Alt-Shift-Left"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectNextAfter", + exec: function(editor) { editor.selectMore(1, true); }, + bindKey: {win: "Ctrl-Alt-Shift-Right", mac: "Ctrl-Alt-Shift-Right"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "splitIntoLines", + exec: function(editor) { editor.multiSelect.splitIntoLines(); }, + bindKey: {win: "Ctrl-Alt-L", mac: "Ctrl-Alt-L"}, + readOnly: true +}, { + name: "alignCursors", + exec: function(editor) { editor.alignCursors(); }, + bindKey: {win: "Ctrl-Alt-A", mac: "Ctrl-Alt-A"}, + scrollIntoView: "cursor" +}, { + name: "findAll", + exec: function(editor) { editor.findAll(); }, + bindKey: {win: "Ctrl-Alt-K", mac: "Ctrl-Alt-G"}, + scrollIntoView: "cursor", + readOnly: true +}]; +exports.multiSelectCommands = [{ + name: "singleSelection", + bindKey: "esc", + exec: function(editor) { editor.exitMultiSelectMode(); }, + scrollIntoView: "cursor", + readOnly: true, + isAvailable: function(editor) {return editor && editor.inMultiSelectMode;} +}]; + +var HashHandler = acequire("../keyboard/hash_handler").HashHandler; +exports.keyboardHandler = new HashHandler(exports.multiSelectCommands); + +}); + +ace.define("ace/multi_select",["require","exports","module","ace/range_list","ace/range","ace/selection","ace/mouse/multi_select_handler","ace/lib/event","ace/lib/lang","ace/commands/multi_select_commands","ace/search","ace/edit_session","ace/editor","ace/config"], function(acequire, exports, module) { + +var RangeList = acequire("./range_list").RangeList; +var Range = acequire("./range").Range; +var Selection = acequire("./selection").Selection; +var onMouseDown = acequire("./mouse/multi_select_handler").onMouseDown; +var event = acequire("./lib/event"); +var lang = acequire("./lib/lang"); +var commands = acequire("./commands/multi_select_commands"); +exports.commands = commands.defaultCommands.concat(commands.multiSelectCommands); +var Search = acequire("./search").Search; +var search = new Search(); + +function find(session, needle, dir) { + search.$options.wrap = true; + search.$options.needle = needle; + search.$options.backwards = dir == -1; + return search.find(session); +} +var EditSession = acequire("./edit_session").EditSession; +(function() { + this.getSelectionMarkers = function() { + return this.$selectionMarkers; + }; +}).call(EditSession.prototype); +(function() { + this.ranges = null; + this.rangeList = null; + this.addRange = function(range, $blockChangeEvents) { + if (!range) + return; + + if (!this.inMultiSelectMode && this.rangeCount === 0) { + var oldRange = this.toOrientedRange(); + this.rangeList.add(oldRange); + this.rangeList.add(range); + if (this.rangeList.ranges.length != 2) { + this.rangeList.removeAll(); + return $blockChangeEvents || this.fromOrientedRange(range); + } + this.rangeList.removeAll(); + this.rangeList.add(oldRange); + this.$onAddRange(oldRange); + } + + if (!range.cursor) + range.cursor = range.end; + + var removed = this.rangeList.add(range); + + this.$onAddRange(range); + + if (removed.length) + this.$onRemoveRange(removed); + + if (this.rangeCount > 1 && !this.inMultiSelectMode) { + this._signal("multiSelect"); + this.inMultiSelectMode = true; + this.session.$undoSelect = false; + this.rangeList.attach(this.session); + } + + return $blockChangeEvents || this.fromOrientedRange(range); + }; + + this.toSingleRange = function(range) { + range = range || this.ranges[0]; + var removed = this.rangeList.removeAll(); + if (removed.length) + this.$onRemoveRange(removed); + + range && this.fromOrientedRange(range); + }; + this.substractPoint = function(pos) { + var removed = this.rangeList.substractPoint(pos); + if (removed) { + this.$onRemoveRange(removed); + return removed[0]; + } + }; + this.mergeOverlappingRanges = function() { + var removed = this.rangeList.merge(); + if (removed.length) + this.$onRemoveRange(removed); + else if(this.ranges[0]) + this.fromOrientedRange(this.ranges[0]); + }; + + this.$onAddRange = function(range) { + this.rangeCount = this.rangeList.ranges.length; + this.ranges.unshift(range); + this._signal("addRange", {range: range}); + }; + + this.$onRemoveRange = function(removed) { + this.rangeCount = this.rangeList.ranges.length; + if (this.rangeCount == 1 && this.inMultiSelectMode) { + var lastRange = this.rangeList.ranges.pop(); + removed.push(lastRange); + this.rangeCount = 0; + } + + for (var i = removed.length; i--; ) { + var index = this.ranges.indexOf(removed[i]); + this.ranges.splice(index, 1); + } + + this._signal("removeRange", {ranges: removed}); + + if (this.rangeCount === 0 && this.inMultiSelectMode) { + this.inMultiSelectMode = false; + this._signal("singleSelect"); + this.session.$undoSelect = true; + this.rangeList.detach(this.session); + } + + lastRange = lastRange || this.ranges[0]; + if (lastRange && !lastRange.isEqual(this.getRange())) + this.fromOrientedRange(lastRange); + }; + this.$initRangeList = function() { + if (this.rangeList) + return; + + this.rangeList = new RangeList(); + this.ranges = []; + this.rangeCount = 0; + }; + this.getAllRanges = function() { + return this.rangeCount ? this.rangeList.ranges.concat() : [this.getRange()]; + }; + + this.splitIntoLines = function () { + if (this.rangeCount > 1) { + var ranges = this.rangeList.ranges; + var lastRange = ranges[ranges.length - 1]; + var range = Range.fromPoints(ranges[0].start, lastRange.end); + + this.toSingleRange(); + this.setSelectionRange(range, lastRange.cursor == lastRange.start); + } else { + var range = this.getRange(); + var isBackwards = this.isBackwards(); + var startRow = range.start.row; + var endRow = range.end.row; + if (startRow == endRow) { + if (isBackwards) + var start = range.end, end = range.start; + else + var start = range.start, end = range.end; + + this.addRange(Range.fromPoints(end, end)); + this.addRange(Range.fromPoints(start, start)); + return; + } + + var rectSel = []; + var r = this.getLineRange(startRow, true); + r.start.column = range.start.column; + rectSel.push(r); + + for (var i = startRow + 1; i < endRow; i++) + rectSel.push(this.getLineRange(i, true)); + + r = this.getLineRange(endRow, true); + r.end.column = range.end.column; + rectSel.push(r); + + rectSel.forEach(this.addRange, this); + } + }; + this.toggleBlockSelection = function () { + if (this.rangeCount > 1) { + var ranges = this.rangeList.ranges; + var lastRange = ranges[ranges.length - 1]; + var range = Range.fromPoints(ranges[0].start, lastRange.end); + + this.toSingleRange(); + this.setSelectionRange(range, lastRange.cursor == lastRange.start); + } else { + var cursor = this.session.documentToScreenPosition(this.selectionLead); + var anchor = this.session.documentToScreenPosition(this.selectionAnchor); + + var rectSel = this.rectangularRangeBlock(cursor, anchor); + rectSel.forEach(this.addRange, this); + } + }; + this.rectangularRangeBlock = function(screenCursor, screenAnchor, includeEmptyLines) { + var rectSel = []; + + var xBackwards = screenCursor.column < screenAnchor.column; + if (xBackwards) { + var startColumn = screenCursor.column; + var endColumn = screenAnchor.column; + var startOffsetX = screenCursor.offsetX; + var endOffsetX = screenAnchor.offsetX; + } else { + var startColumn = screenAnchor.column; + var endColumn = screenCursor.column; + var startOffsetX = screenAnchor.offsetX; + var endOffsetX = screenCursor.offsetX; + } + + var yBackwards = screenCursor.row < screenAnchor.row; + if (yBackwards) { + var startRow = screenCursor.row; + var endRow = screenAnchor.row; + } else { + var startRow = screenAnchor.row; + var endRow = screenCursor.row; + } + + if (startColumn < 0) + startColumn = 0; + if (startRow < 0) + startRow = 0; + + if (startRow == endRow) + includeEmptyLines = true; + + for (var row = startRow; row <= endRow; row++) { + var range = Range.fromPoints( + this.session.screenToDocumentPosition(row, startColumn, startOffsetX), + this.session.screenToDocumentPosition(row, endColumn, endOffsetX) + ); + if (range.isEmpty()) { + if (docEnd && isSamePoint(range.end, docEnd)) + break; + var docEnd = range.end; + } + range.cursor = xBackwards ? range.start : range.end; + rectSel.push(range); + } + + if (yBackwards) + rectSel.reverse(); + + if (!includeEmptyLines) { + var end = rectSel.length - 1; + while (rectSel[end].isEmpty() && end > 0) + end--; + if (end > 0) { + var start = 0; + while (rectSel[start].isEmpty()) + start++; + } + for (var i = end; i >= start; i--) { + if (rectSel[i].isEmpty()) + rectSel.splice(i, 1); + } + } + + return rectSel; + }; +}).call(Selection.prototype); +var Editor = acequire("./editor").Editor; +(function() { + this.updateSelectionMarkers = function() { + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + }; + this.addSelectionMarker = function(orientedRange) { + if (!orientedRange.cursor) + orientedRange.cursor = orientedRange.end; + + var style = this.getSelectionStyle(); + orientedRange.marker = this.session.addMarker(orientedRange, "ace_selection", style); + + this.session.$selectionMarkers.push(orientedRange); + this.session.selectionMarkerCount = this.session.$selectionMarkers.length; + return orientedRange; + }; + this.removeSelectionMarker = function(range) { + if (!range.marker) + return; + this.session.removeMarker(range.marker); + var index = this.session.$selectionMarkers.indexOf(range); + if (index != -1) + this.session.$selectionMarkers.splice(index, 1); + this.session.selectionMarkerCount = this.session.$selectionMarkers.length; + }; + + this.removeSelectionMarkers = function(ranges) { + var markerList = this.session.$selectionMarkers; + for (var i = ranges.length; i--; ) { + var range = ranges[i]; + if (!range.marker) + continue; + this.session.removeMarker(range.marker); + var index = markerList.indexOf(range); + if (index != -1) + markerList.splice(index, 1); + } + this.session.selectionMarkerCount = markerList.length; + }; + + this.$onAddRange = function(e) { + this.addSelectionMarker(e.range); + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + }; + + this.$onRemoveRange = function(e) { + this.removeSelectionMarkers(e.ranges); + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + }; + + this.$onMultiSelect = function(e) { + if (this.inMultiSelectMode) + return; + this.inMultiSelectMode = true; + + this.setStyle("ace_multiselect"); + this.keyBinding.addKeyboardHandler(commands.keyboardHandler); + this.commands.setDefaultHandler("exec", this.$onMultiSelectExec); + + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + }; + + this.$onSingleSelect = function(e) { + if (this.session.multiSelect.inVirtualMode) + return; + this.inMultiSelectMode = false; + + this.unsetStyle("ace_multiselect"); + this.keyBinding.removeKeyboardHandler(commands.keyboardHandler); + + this.commands.removeDefaultHandler("exec", this.$onMultiSelectExec); + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + this._emit("changeSelection"); + }; + + this.$onMultiSelectExec = function(e) { + var command = e.command; + var editor = e.editor; + if (!editor.multiSelect) + return; + if (!command.multiSelectAction) { + var result = command.exec(editor, e.args || {}); + editor.multiSelect.addRange(editor.multiSelect.toOrientedRange()); + editor.multiSelect.mergeOverlappingRanges(); + } else if (command.multiSelectAction == "forEach") { + result = editor.forEachSelection(command, e.args); + } else if (command.multiSelectAction == "forEachLine") { + result = editor.forEachSelection(command, e.args, true); + } else if (command.multiSelectAction == "single") { + editor.exitMultiSelectMode(); + result = command.exec(editor, e.args || {}); + } else { + result = command.multiSelectAction(editor, e.args || {}); + } + return result; + }; + this.forEachSelection = function(cmd, args, options) { + if (this.inVirtualSelectionMode) + return; + var keepOrder = options && options.keepOrder; + var $byLines = options == true || options && options.$byLines; + var session = this.session; + var selection = this.selection; + var rangeList = selection.rangeList; + var ranges = (keepOrder ? selection : rangeList).ranges; + var result; + + if (!ranges.length) + return cmd.exec ? cmd.exec(this, args || {}) : cmd(this, args || {}); + + var reg = selection._eventRegistry; + selection._eventRegistry = {}; + + var tmpSel = new Selection(session); + this.inVirtualSelectionMode = true; + for (var i = ranges.length; i--;) { + if ($byLines) { + while (i > 0 && ranges[i].start.row == ranges[i - 1].end.row) + i--; + } + tmpSel.fromOrientedRange(ranges[i]); + tmpSel.index = i; + this.selection = session.selection = tmpSel; + var cmdResult = cmd.exec ? cmd.exec(this, args || {}) : cmd(this, args || {}); + if (!result && cmdResult !== undefined) + result = cmdResult; + tmpSel.toOrientedRange(ranges[i]); + } + tmpSel.detach(); + + this.selection = session.selection = selection; + this.inVirtualSelectionMode = false; + selection._eventRegistry = reg; + selection.mergeOverlappingRanges(); + + var anim = this.renderer.$scrollAnimation; + this.onCursorChange(); + this.onSelectionChange(); + if (anim && anim.from == anim.to) + this.renderer.animateScrolling(anim.from); + + return result; + }; + this.exitMultiSelectMode = function() { + if (!this.inMultiSelectMode || this.inVirtualSelectionMode) + return; + this.multiSelect.toSingleRange(); + }; + + this.getSelectedText = function() { + var text = ""; + if (this.inMultiSelectMode && !this.inVirtualSelectionMode) { + var ranges = this.multiSelect.rangeList.ranges; + var buf = []; + for (var i = 0; i < ranges.length; i++) { + buf.push(this.session.getTextRange(ranges[i])); + } + var nl = this.session.getDocument().getNewLineCharacter(); + text = buf.join(nl); + if (text.length == (buf.length - 1) * nl.length) + text = ""; + } else if (!this.selection.isEmpty()) { + text = this.session.getTextRange(this.getSelectionRange()); + } + return text; + }; + + this.$checkMultiselectChange = function(e, anchor) { + if (this.inMultiSelectMode && !this.inVirtualSelectionMode) { + var range = this.multiSelect.ranges[0]; + if (this.multiSelect.isEmpty() && anchor == this.multiSelect.anchor) + return; + var pos = anchor == this.multiSelect.anchor + ? range.cursor == range.start ? range.end : range.start + : range.cursor; + if (pos.row != anchor.row + || this.session.$clipPositionToDocument(pos.row, pos.column).column != anchor.column) + this.multiSelect.toSingleRange(this.multiSelect.toOrientedRange()); + } + }; + this.findAll = function(needle, options, additive) { + options = options || {}; + options.needle = needle || options.needle; + if (options.needle == undefined) { + var range = this.selection.isEmpty() + ? this.selection.getWordRange() + : this.selection.getRange(); + options.needle = this.session.getTextRange(range); + } + this.$search.set(options); + + var ranges = this.$search.findAll(this.session); + if (!ranges.length) + return 0; + + this.$blockScrolling += 1; + var selection = this.multiSelect; + + if (!additive) + selection.toSingleRange(ranges[0]); + + for (var i = ranges.length; i--; ) + selection.addRange(ranges[i], true); + if (range && selection.rangeList.rangeAtPoint(range.start)) + selection.addRange(range, true); + + this.$blockScrolling -= 1; + + return ranges.length; + }; + this.selectMoreLines = function(dir, skip) { + var range = this.selection.toOrientedRange(); + var isBackwards = range.cursor == range.end; + + var screenLead = this.session.documentToScreenPosition(range.cursor); + if (this.selection.$desiredColumn) + screenLead.column = this.selection.$desiredColumn; + + var lead = this.session.screenToDocumentPosition(screenLead.row + dir, screenLead.column); + + if (!range.isEmpty()) { + var screenAnchor = this.session.documentToScreenPosition(isBackwards ? range.end : range.start); + var anchor = this.session.screenToDocumentPosition(screenAnchor.row + dir, screenAnchor.column); + } else { + var anchor = lead; + } + + if (isBackwards) { + var newRange = Range.fromPoints(lead, anchor); + newRange.cursor = newRange.start; + } else { + var newRange = Range.fromPoints(anchor, lead); + newRange.cursor = newRange.end; + } + + newRange.desiredColumn = screenLead.column; + if (!this.selection.inMultiSelectMode) { + this.selection.addRange(range); + } else { + if (skip) + var toRemove = range.cursor; + } + + this.selection.addRange(newRange); + if (toRemove) + this.selection.substractPoint(toRemove); + }; + this.transposeSelections = function(dir) { + var session = this.session; + var sel = session.multiSelect; + var all = sel.ranges; + + for (var i = all.length; i--; ) { + var range = all[i]; + if (range.isEmpty()) { + var tmp = session.getWordRange(range.start.row, range.start.column); + range.start.row = tmp.start.row; + range.start.column = tmp.start.column; + range.end.row = tmp.end.row; + range.end.column = tmp.end.column; + } + } + sel.mergeOverlappingRanges(); + + var words = []; + for (var i = all.length; i--; ) { + var range = all[i]; + words.unshift(session.getTextRange(range)); + } + + if (dir < 0) + words.unshift(words.pop()); + else + words.push(words.shift()); + + for (var i = all.length; i--; ) { + var range = all[i]; + var tmp = range.clone(); + session.replace(range, words[i]); + range.start.row = tmp.start.row; + range.start.column = tmp.start.column; + } + }; + this.selectMore = function(dir, skip, stopAtFirst) { + var session = this.session; + var sel = session.multiSelect; + + var range = sel.toOrientedRange(); + if (range.isEmpty()) { + range = session.getWordRange(range.start.row, range.start.column); + range.cursor = dir == -1 ? range.start : range.end; + this.multiSelect.addRange(range); + if (stopAtFirst) + return; + } + var needle = session.getTextRange(range); + + var newRange = find(session, needle, dir); + if (newRange) { + newRange.cursor = dir == -1 ? newRange.start : newRange.end; + this.$blockScrolling += 1; + this.session.unfold(newRange); + this.multiSelect.addRange(newRange); + this.$blockScrolling -= 1; + this.renderer.scrollCursorIntoView(null, 0.5); + } + if (skip) + this.multiSelect.substractPoint(range.cursor); + }; + this.alignCursors = function() { + var session = this.session; + var sel = session.multiSelect; + var ranges = sel.ranges; + var row = -1; + var sameRowRanges = ranges.filter(function(r) { + if (r.cursor.row == row) + return true; + row = r.cursor.row; + }); + + if (!ranges.length || sameRowRanges.length == ranges.length - 1) { + var range = this.selection.getRange(); + var fr = range.start.row, lr = range.end.row; + var guessRange = fr == lr; + if (guessRange) { + var max = this.session.getLength(); + var line; + do { + line = this.session.getLine(lr); + } while (/[=:]/.test(line) && ++lr < max); + do { + line = this.session.getLine(fr); + } while (/[=:]/.test(line) && --fr > 0); + + if (fr < 0) fr = 0; + if (lr >= max) lr = max - 1; + } + var lines = this.session.removeFullLines(fr, lr); + lines = this.$reAlignText(lines, guessRange); + this.session.insert({row: fr, column: 0}, lines.join("\n") + "\n"); + if (!guessRange) { + range.start.column = 0; + range.end.column = lines[lines.length - 1].length; + } + this.selection.setRange(range); + } else { + sameRowRanges.forEach(function(r) { + sel.substractPoint(r.cursor); + }); + + var maxCol = 0; + var minSpace = Infinity; + var spaceOffsets = ranges.map(function(r) { + var p = r.cursor; + var line = session.getLine(p.row); + var spaceOffset = line.substr(p.column).search(/\S/g); + if (spaceOffset == -1) + spaceOffset = 0; + + if (p.column > maxCol) + maxCol = p.column; + if (spaceOffset < minSpace) + minSpace = spaceOffset; + return spaceOffset; + }); + ranges.forEach(function(r, i) { + var p = r.cursor; + var l = maxCol - p.column; + var d = spaceOffsets[i] - minSpace; + if (l > d) + session.insert(p, lang.stringRepeat(" ", l - d)); + else + session.remove(new Range(p.row, p.column, p.row, p.column - l + d)); + + r.start.column = r.end.column = maxCol; + r.start.row = r.end.row = p.row; + r.cursor = r.end; + }); + sel.fromOrientedRange(ranges[0]); + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + } + }; + + this.$reAlignText = function(lines, forceLeft) { + var isLeftAligned = true, isRightAligned = true; + var startW, textW, endW; + + return lines.map(function(line) { + var m = line.match(/(\s*)(.*?)(\s*)([=:].*)/); + if (!m) + return [line]; + + if (startW == null) { + startW = m[1].length; + textW = m[2].length; + endW = m[3].length; + return m; + } + + if (startW + textW + endW != m[1].length + m[2].length + m[3].length) + isRightAligned = false; + if (startW != m[1].length) + isLeftAligned = false; + + if (startW > m[1].length) + startW = m[1].length; + if (textW < m[2].length) + textW = m[2].length; + if (endW > m[3].length) + endW = m[3].length; + + return m; + }).map(forceLeft ? alignLeft : + isLeftAligned ? isRightAligned ? alignRight : alignLeft : unAlign); + + function spaces(n) { + return lang.stringRepeat(" ", n); + } + + function alignLeft(m) { + return !m[2] ? m[0] : spaces(startW) + m[2] + + spaces(textW - m[2].length + endW) + + m[4].replace(/^([=:])\s+/, "$1 "); + } + function alignRight(m) { + return !m[2] ? m[0] : spaces(startW + textW - m[2].length) + m[2] + + spaces(endW, " ") + + m[4].replace(/^([=:])\s+/, "$1 "); + } + function unAlign(m) { + return !m[2] ? m[0] : spaces(startW) + m[2] + + spaces(endW) + + m[4].replace(/^([=:])\s+/, "$1 "); + } + }; +}).call(Editor.prototype); + + +function isSamePoint(p1, p2) { + return p1.row == p2.row && p1.column == p2.column; +} +exports.onSessionChange = function(e) { + var session = e.session; + if (session && !session.multiSelect) { + session.$selectionMarkers = []; + session.selection.$initRangeList(); + session.multiSelect = session.selection; + } + this.multiSelect = session && session.multiSelect; + + var oldSession = e.oldSession; + if (oldSession) { + oldSession.multiSelect.off("addRange", this.$onAddRange); + oldSession.multiSelect.off("removeRange", this.$onRemoveRange); + oldSession.multiSelect.off("multiSelect", this.$onMultiSelect); + oldSession.multiSelect.off("singleSelect", this.$onSingleSelect); + oldSession.multiSelect.lead.off("change", this.$checkMultiselectChange); + oldSession.multiSelect.anchor.off("change", this.$checkMultiselectChange); + } + + if (session) { + session.multiSelect.on("addRange", this.$onAddRange); + session.multiSelect.on("removeRange", this.$onRemoveRange); + session.multiSelect.on("multiSelect", this.$onMultiSelect); + session.multiSelect.on("singleSelect", this.$onSingleSelect); + session.multiSelect.lead.on("change", this.$checkMultiselectChange); + session.multiSelect.anchor.on("change", this.$checkMultiselectChange); + } + + if (session && this.inMultiSelectMode != session.selection.inMultiSelectMode) { + if (session.selection.inMultiSelectMode) + this.$onMultiSelect(); + else + this.$onSingleSelect(); + } +}; +function MultiSelect(editor) { + if (editor.$multiselectOnSessionChange) + return; + editor.$onAddRange = editor.$onAddRange.bind(editor); + editor.$onRemoveRange = editor.$onRemoveRange.bind(editor); + editor.$onMultiSelect = editor.$onMultiSelect.bind(editor); + editor.$onSingleSelect = editor.$onSingleSelect.bind(editor); + editor.$multiselectOnSessionChange = exports.onSessionChange.bind(editor); + editor.$checkMultiselectChange = editor.$checkMultiselectChange.bind(editor); + + editor.$multiselectOnSessionChange(editor); + editor.on("changeSession", editor.$multiselectOnSessionChange); + + editor.on("mousedown", onMouseDown); + editor.commands.addCommands(commands.defaultCommands); + + addAltCursorListeners(editor); +} + +function addAltCursorListeners(editor){ + var el = editor.textInput.getElement(); + var altCursor = false; + event.addListener(el, "keydown", function(e) { + var altDown = e.keyCode == 18 && !(e.ctrlKey || e.shiftKey || e.metaKey); + if (editor.$blockSelectEnabled && altDown) { + if (!altCursor) { + editor.renderer.setMouseCursor("crosshair"); + altCursor = true; + } + } else if (altCursor) { + reset(); + } + }); + + event.addListener(el, "keyup", reset); + event.addListener(el, "blur", reset); + function reset(e) { + if (altCursor) { + editor.renderer.setMouseCursor(""); + altCursor = false; + } + } +} + +exports.MultiSelect = MultiSelect; + + +acequire("./config").defineOptions(Editor.prototype, "editor", { + enableMultiselect: { + set: function(val) { + MultiSelect(this); + if (val) { + this.on("changeSession", this.$multiselectOnSessionChange); + this.on("mousedown", onMouseDown); + } else { + this.off("changeSession", this.$multiselectOnSessionChange); + this.off("mousedown", onMouseDown); + } + }, + value: true + }, + enableBlockSelect: { + set: function(val) { + this.$blockSelectEnabled = val; + }, + value: true + } +}); + + + +}); + +ace.define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../../range").Range; + +var FoldMode = exports.FoldMode = function() {}; + +(function() { + + this.foldingStartMarker = null; + this.foldingStopMarker = null; + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + if (this.foldingStartMarker.test(line)) + return "start"; + if (foldStyle == "markbeginend" + && this.foldingStopMarker + && this.foldingStopMarker.test(line)) + return "end"; + return ""; + }; + + this.getFoldWidgetRange = function(session, foldStyle, row) { + return null; + }; + + this.indentationBlock = function(session, row, column) { + var re = /\S/; + var line = session.getLine(row); + var startLevel = line.search(re); + if (startLevel == -1) + return; + + var startColumn = column || line.length; + var maxRow = session.getLength(); + var startRow = row; + var endRow = row; + + while (++row < maxRow) { + var level = session.getLine(row).search(re); + + if (level == -1) + continue; + + if (level <= startLevel) + break; + + endRow = row; + } + + if (endRow > startRow) { + var endColumn = session.getLine(endRow).length; + return new Range(startRow, startColumn, endRow, endColumn); + } + }; + + this.openingBracketBlock = function(session, bracket, row, column, typeRe) { + var start = {row: row, column: column + 1}; + var end = session.$findClosingBracket(bracket, start, typeRe); + if (!end) + return; + + var fw = session.foldWidgets[end.row]; + if (fw == null) + fw = session.getFoldWidget(end.row); + + if (fw == "start" && end.row > start.row) { + end.row --; + end.column = session.getLine(end.row).length; + } + return Range.fromPoints(start, end); + }; + + this.closingBracketBlock = function(session, bracket, row, column, typeRe) { + var end = {row: row, column: column}; + var start = session.$findOpeningBracket(bracket, end); + + if (!start) + return; + + start.column++; + end.column--; + + return Range.fromPoints(start, end); + }; +}).call(FoldMode.prototype); + +}); + +ace.define("ace/theme/textmate",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; + +exports.isDark = false; +exports.cssClass = "ace-tm"; +exports.cssText = ".ace-tm .ace_gutter {\ +background: #f0f0f0;\ +color: #333;\ +}\ +.ace-tm .ace_print-margin {\ +width: 1px;\ +background: #e8e8e8;\ +}\ +.ace-tm .ace_fold {\ +background-color: #6B72E6;\ +}\ +.ace-tm {\ +background-color: #FFFFFF;\ +color: black;\ +}\ +.ace-tm .ace_cursor {\ +color: black;\ +}\ +.ace-tm .ace_invisible {\ +color: rgb(191, 191, 191);\ +}\ +.ace-tm .ace_storage,\ +.ace-tm .ace_keyword {\ +color: blue;\ +}\ +.ace-tm .ace_constant {\ +color: rgb(197, 6, 11);\ +}\ +.ace-tm .ace_constant.ace_buildin {\ +color: rgb(88, 72, 246);\ +}\ +.ace-tm .ace_constant.ace_language {\ +color: rgb(88, 92, 246);\ +}\ +.ace-tm .ace_constant.ace_library {\ +color: rgb(6, 150, 14);\ +}\ +.ace-tm .ace_invalid {\ +background-color: rgba(255, 0, 0, 0.1);\ +color: red;\ +}\ +.ace-tm .ace_support.ace_function {\ +color: rgb(60, 76, 114);\ +}\ +.ace-tm .ace_support.ace_constant {\ +color: rgb(6, 150, 14);\ +}\ +.ace-tm .ace_support.ace_type,\ +.ace-tm .ace_support.ace_class {\ +color: rgb(109, 121, 222);\ +}\ +.ace-tm .ace_keyword.ace_operator {\ +color: rgb(104, 118, 135);\ +}\ +.ace-tm .ace_string {\ +color: rgb(3, 106, 7);\ +}\ +.ace-tm .ace_comment {\ +color: rgb(76, 136, 107);\ +}\ +.ace-tm .ace_comment.ace_doc {\ +color: rgb(0, 102, 255);\ +}\ +.ace-tm .ace_comment.ace_doc.ace_tag {\ +color: rgb(128, 159, 191);\ +}\ +.ace-tm .ace_constant.ace_numeric {\ +color: rgb(0, 0, 205);\ +}\ +.ace-tm .ace_variable {\ +color: rgb(49, 132, 149);\ +}\ +.ace-tm .ace_xml-pe {\ +color: rgb(104, 104, 91);\ +}\ +.ace-tm .ace_entity.ace_name.ace_function {\ +color: #0000A2;\ +}\ +.ace-tm .ace_heading {\ +color: rgb(12, 7, 255);\ +}\ +.ace-tm .ace_list {\ +color:rgb(185, 6, 144);\ +}\ +.ace-tm .ace_meta.ace_tag {\ +color:rgb(0, 22, 142);\ +}\ +.ace-tm .ace_string.ace_regex {\ +color: rgb(255, 0, 0)\ +}\ +.ace-tm .ace_marker-layer .ace_selection {\ +background: rgb(181, 213, 255);\ +}\ +.ace-tm.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px white;\ +}\ +.ace-tm .ace_marker-layer .ace_step {\ +background: rgb(252, 255, 0);\ +}\ +.ace-tm .ace_marker-layer .ace_stack {\ +background: rgb(164, 229, 101);\ +}\ +.ace-tm .ace_marker-layer .ace_bracket {\ +margin: -1px 0 0 -1px;\ +border: 1px solid rgb(192, 192, 192);\ +}\ +.ace-tm .ace_marker-layer .ace_active-line {\ +background: rgba(0, 0, 0, 0.07);\ +}\ +.ace-tm .ace_gutter-active-line {\ +background-color : #dcdcdc;\ +}\ +.ace-tm .ace_marker-layer .ace_selected-word {\ +background: rgb(250, 250, 255);\ +border: 1px solid rgb(200, 200, 250);\ +}\ +.ace-tm .ace_indent-guide {\ +background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\ +}\ +"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); + +ace.define("ace/line_widgets",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/range"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var dom = acequire("./lib/dom"); +var Range = acequire("./range").Range; + + +function LineWidgets(session) { + this.session = session; + this.session.widgetManager = this; + this.session.getRowLength = this.getRowLength; + this.session.$getWidgetScreenLength = this.$getWidgetScreenLength; + this.updateOnChange = this.updateOnChange.bind(this); + this.renderWidgets = this.renderWidgets.bind(this); + this.measureWidgets = this.measureWidgets.bind(this); + this.session._changedWidgets = []; + this.$onChangeEditor = this.$onChangeEditor.bind(this); + + this.session.on("change", this.updateOnChange); + this.session.on("changeFold", this.updateOnFold); + this.session.on("changeEditor", this.$onChangeEditor); +} + +(function() { + this.getRowLength = function(row) { + var h; + if (this.lineWidgets) + h = this.lineWidgets[row] && this.lineWidgets[row].rowCount || 0; + else + h = 0; + if (!this.$useWrapMode || !this.$wrapData[row]) { + return 1 + h; + } else { + return this.$wrapData[row].length + 1 + h; + } + }; + + this.$getWidgetScreenLength = function() { + var screenRows = 0; + this.lineWidgets.forEach(function(w){ + if (w && w.rowCount && !w.hidden) + screenRows += w.rowCount; + }); + return screenRows; + }; + + this.$onChangeEditor = function(e) { + this.attach(e.editor); + }; + + this.attach = function(editor) { + if (editor && editor.widgetManager && editor.widgetManager != this) + editor.widgetManager.detach(); + + if (this.editor == editor) + return; + + this.detach(); + this.editor = editor; + + if (editor) { + editor.widgetManager = this; + editor.renderer.on("beforeRender", this.measureWidgets); + editor.renderer.on("afterRender", this.renderWidgets); + } + }; + this.detach = function(e) { + var editor = this.editor; + if (!editor) + return; + + this.editor = null; + editor.widgetManager = null; + + editor.renderer.off("beforeRender", this.measureWidgets); + editor.renderer.off("afterRender", this.renderWidgets); + var lineWidgets = this.session.lineWidgets; + lineWidgets && lineWidgets.forEach(function(w) { + if (w && w.el && w.el.parentNode) { + w._inDocument = false; + w.el.parentNode.removeChild(w.el); + } + }); + }; + + this.updateOnFold = function(e, session) { + var lineWidgets = session.lineWidgets; + if (!lineWidgets || !e.action) + return; + var fold = e.data; + var start = fold.start.row; + var end = fold.end.row; + var hide = e.action == "add"; + for (var i = start + 1; i < end; i++) { + if (lineWidgets[i]) + lineWidgets[i].hidden = hide; + } + if (lineWidgets[end]) { + if (hide) { + if (!lineWidgets[start]) + lineWidgets[start] = lineWidgets[end]; + else + lineWidgets[end].hidden = hide; + } else { + if (lineWidgets[start] == lineWidgets[end]) + lineWidgets[start] = undefined; + lineWidgets[end].hidden = hide; + } + } + }; + + this.updateOnChange = function(delta) { + var lineWidgets = this.session.lineWidgets; + if (!lineWidgets) return; + + var startRow = delta.start.row; + var len = delta.end.row - startRow; + + if (len === 0) { + } else if (delta.action == 'remove') { + var removed = lineWidgets.splice(startRow + 1, len); + removed.forEach(function(w) { + w && this.removeLineWidget(w); + }, this); + this.$updateRows(); + } else { + var args = new Array(len); + args.unshift(startRow, 0); + lineWidgets.splice.apply(lineWidgets, args); + this.$updateRows(); + } + }; + + this.$updateRows = function() { + var lineWidgets = this.session.lineWidgets; + if (!lineWidgets) return; + var noWidgets = true; + lineWidgets.forEach(function(w, i) { + if (w) { + noWidgets = false; + w.row = i; + while (w.$oldWidget) { + w.$oldWidget.row = i; + w = w.$oldWidget; + } + } + }); + if (noWidgets) + this.session.lineWidgets = null; + }; + + this.addLineWidget = function(w) { + if (!this.session.lineWidgets) + this.session.lineWidgets = new Array(this.session.getLength()); + + var old = this.session.lineWidgets[w.row]; + if (old) { + w.$oldWidget = old; + if (old.el && old.el.parentNode) { + old.el.parentNode.removeChild(old.el); + old._inDocument = false; + } + } + + this.session.lineWidgets[w.row] = w; + + w.session = this.session; + + var renderer = this.editor.renderer; + if (w.html && !w.el) { + w.el = dom.createElement("div"); + w.el.innerHTML = w.html; + } + if (w.el) { + dom.addCssClass(w.el, "ace_lineWidgetContainer"); + w.el.style.position = "absolute"; + w.el.style.zIndex = 5; + renderer.container.appendChild(w.el); + w._inDocument = true; + } + + if (!w.coverGutter) { + w.el.style.zIndex = 3; + } + if (w.pixelHeight == null) { + w.pixelHeight = w.el.offsetHeight; + } + if (w.rowCount == null) { + w.rowCount = w.pixelHeight / renderer.layerConfig.lineHeight; + } + + var fold = this.session.getFoldAt(w.row, 0); + w.$fold = fold; + if (fold) { + var lineWidgets = this.session.lineWidgets; + if (w.row == fold.end.row && !lineWidgets[fold.start.row]) + lineWidgets[fold.start.row] = w; + else + w.hidden = true; + } + + this.session._emit("changeFold", {data:{start:{row: w.row}}}); + + this.$updateRows(); + this.renderWidgets(null, renderer); + this.onWidgetChanged(w); + return w; + }; + + this.removeLineWidget = function(w) { + w._inDocument = false; + w.session = null; + if (w.el && w.el.parentNode) + w.el.parentNode.removeChild(w.el); + if (w.editor && w.editor.destroy) try { + w.editor.destroy(); + } catch(e){} + if (this.session.lineWidgets) { + var w1 = this.session.lineWidgets[w.row]; + if (w1 == w) { + this.session.lineWidgets[w.row] = w.$oldWidget; + if (w.$oldWidget) + this.onWidgetChanged(w.$oldWidget); + } else { + while (w1) { + if (w1.$oldWidget == w) { + w1.$oldWidget = w.$oldWidget; + break; + } + w1 = w1.$oldWidget; + } + } + } + this.session._emit("changeFold", {data:{start:{row: w.row}}}); + this.$updateRows(); + }; + + this.getWidgetsAtRow = function(row) { + var lineWidgets = this.session.lineWidgets; + var w = lineWidgets && lineWidgets[row]; + var list = []; + while (w) { + list.push(w); + w = w.$oldWidget; + } + return list; + }; + + this.onWidgetChanged = function(w) { + this.session._changedWidgets.push(w); + this.editor && this.editor.renderer.updateFull(); + }; + + this.measureWidgets = function(e, renderer) { + var changedWidgets = this.session._changedWidgets; + var config = renderer.layerConfig; + + if (!changedWidgets || !changedWidgets.length) return; + var min = Infinity; + for (var i = 0; i < changedWidgets.length; i++) { + var w = changedWidgets[i]; + if (!w || !w.el) continue; + if (w.session != this.session) continue; + if (!w._inDocument) { + if (this.session.lineWidgets[w.row] != w) + continue; + w._inDocument = true; + renderer.container.appendChild(w.el); + } + + w.h = w.el.offsetHeight; + + if (!w.fixedWidth) { + w.w = w.el.offsetWidth; + w.screenWidth = Math.ceil(w.w / config.characterWidth); + } + + var rowCount = w.h / config.lineHeight; + if (w.coverLine) { + rowCount -= this.session.getRowLineCount(w.row); + if (rowCount < 0) + rowCount = 0; + } + if (w.rowCount != rowCount) { + w.rowCount = rowCount; + if (w.row < min) + min = w.row; + } + } + if (min != Infinity) { + this.session._emit("changeFold", {data:{start:{row: min}}}); + this.session.lineWidgetWidth = null; + } + this.session._changedWidgets = []; + }; + + this.renderWidgets = function(e, renderer) { + var config = renderer.layerConfig; + var lineWidgets = this.session.lineWidgets; + if (!lineWidgets) + return; + var first = Math.min(this.firstRow, config.firstRow); + var last = Math.max(this.lastRow, config.lastRow, lineWidgets.length); + + while (first > 0 && !lineWidgets[first]) + first--; + + this.firstRow = config.firstRow; + this.lastRow = config.lastRow; + + renderer.$cursorLayer.config = config; + for (var i = first; i <= last; i++) { + var w = lineWidgets[i]; + if (!w || !w.el) continue; + if (w.hidden) { + w.el.style.top = -100 - (w.pixelHeight || 0) + "px"; + continue; + } + if (!w._inDocument) { + w._inDocument = true; + renderer.container.appendChild(w.el); + } + var top = renderer.$cursorLayer.getPixelPosition({row: i, column:0}, true).top; + if (!w.coverLine) + top += config.lineHeight * this.session.getRowLineCount(w.row); + w.el.style.top = top - config.offset + "px"; + + var left = w.coverGutter ? 0 : renderer.gutterWidth; + if (!w.fixedWidth) + left -= renderer.scrollLeft; + w.el.style.left = left + "px"; + + if (w.fullWidth && w.screenWidth) { + w.el.style.minWidth = config.width + 2 * config.padding + "px"; + } + + if (w.fixedWidth) { + w.el.style.right = renderer.scrollBar.getWidth() + "px"; + } else { + w.el.style.right = ""; + } + } + }; + +}).call(LineWidgets.prototype); + + +exports.LineWidgets = LineWidgets; + +}); + +ace.define("ace/ext/error_marker",["require","exports","module","ace/line_widgets","ace/lib/dom","ace/range"], function(acequire, exports, module) { +"use strict"; +var LineWidgets = acequire("../line_widgets").LineWidgets; +var dom = acequire("../lib/dom"); +var Range = acequire("../range").Range; + +function binarySearch(array, needle, comparator) { + var first = 0; + var last = array.length - 1; + + while (first <= last) { + var mid = (first + last) >> 1; + var c = comparator(needle, array[mid]); + if (c > 0) + first = mid + 1; + else if (c < 0) + last = mid - 1; + else + return mid; + } + return -(first + 1); +} + +function findAnnotations(session, row, dir) { + var annotations = session.getAnnotations().sort(Range.comparePoints); + if (!annotations.length) + return; + + var i = binarySearch(annotations, {row: row, column: -1}, Range.comparePoints); + if (i < 0) + i = -i - 1; + + if (i >= annotations.length) + i = dir > 0 ? 0 : annotations.length - 1; + else if (i === 0 && dir < 0) + i = annotations.length - 1; + + var annotation = annotations[i]; + if (!annotation || !dir) + return; + + if (annotation.row === row) { + do { + annotation = annotations[i += dir]; + } while (annotation && annotation.row === row); + if (!annotation) + return annotations.slice(); + } + + + var matched = []; + row = annotation.row; + do { + matched[dir < 0 ? "unshift" : "push"](annotation); + annotation = annotations[i += dir]; + } while (annotation && annotation.row == row); + return matched.length && matched; +} + +exports.showErrorMarker = function(editor, dir) { + var session = editor.session; + if (!session.widgetManager) { + session.widgetManager = new LineWidgets(session); + session.widgetManager.attach(editor); + } + + var pos = editor.getCursorPosition(); + var row = pos.row; + var oldWidget = session.widgetManager.getWidgetsAtRow(row).filter(function(w) { + return w.type == "errorMarker"; + })[0]; + if (oldWidget) { + oldWidget.destroy(); + } else { + row -= dir; + } + var annotations = findAnnotations(session, row, dir); + var gutterAnno; + if (annotations) { + var annotation = annotations[0]; + pos.column = (annotation.pos && typeof annotation.column != "number" + ? annotation.pos.sc + : annotation.column) || 0; + pos.row = annotation.row; + gutterAnno = editor.renderer.$gutterLayer.$annotations[pos.row]; + } else if (oldWidget) { + return; + } else { + gutterAnno = { + text: ["Looks good!"], + className: "ace_ok" + }; + } + editor.session.unfold(pos.row); + editor.selection.moveToPosition(pos); + + var w = { + row: pos.row, + fixedWidth: true, + coverGutter: true, + el: dom.createElement("div"), + type: "errorMarker" + }; + var el = w.el.appendChild(dom.createElement("div")); + var arrow = w.el.appendChild(dom.createElement("div")); + arrow.className = "error_widget_arrow " + gutterAnno.className; + + var left = editor.renderer.$cursorLayer + .getPixelPosition(pos).left; + arrow.style.left = left + editor.renderer.gutterWidth - 5 + "px"; + + w.el.className = "error_widget_wrapper"; + el.className = "error_widget " + gutterAnno.className; + el.innerHTML = gutterAnno.text.join("
"); + + el.appendChild(dom.createElement("div")); + + var kb = function(_, hashId, keyString) { + if (hashId === 0 && (keyString === "esc" || keyString === "return")) { + w.destroy(); + return {command: "null"}; + } + }; + + w.destroy = function() { + if (editor.$mouseHandler.isMousePressed) + return; + editor.keyBinding.removeKeyboardHandler(kb); + session.widgetManager.removeLineWidget(w); + editor.off("changeSelection", w.destroy); + editor.off("changeSession", w.destroy); + editor.off("mouseup", w.destroy); + editor.off("change", w.destroy); + }; + + editor.keyBinding.addKeyboardHandler(kb); + editor.on("changeSelection", w.destroy); + editor.on("changeSession", w.destroy); + editor.on("mouseup", w.destroy); + editor.on("change", w.destroy); + + editor.session.widgetManager.addLineWidget(w); + + w.el.onmousedown = editor.focus.bind(editor); + + editor.renderer.scrollCursorIntoView(null, 0.5, {bottom: w.el.offsetHeight}); +}; + + +dom.importCssString("\ + .error_widget_wrapper {\ + background: inherit;\ + color: inherit;\ + border:none\ + }\ + .error_widget {\ + border-top: solid 2px;\ + border-bottom: solid 2px;\ + margin: 5px 0;\ + padding: 10px 40px;\ + white-space: pre-wrap;\ + }\ + .error_widget.ace_error, .error_widget_arrow.ace_error{\ + border-color: #ff5a5a\ + }\ + .error_widget.ace_warning, .error_widget_arrow.ace_warning{\ + border-color: #F1D817\ + }\ + .error_widget.ace_info, .error_widget_arrow.ace_info{\ + border-color: #5a5a5a\ + }\ + .error_widget.ace_ok, .error_widget_arrow.ace_ok{\ + border-color: #5aaa5a\ + }\ + .error_widget_arrow {\ + position: absolute;\ + border: solid 5px;\ + border-top-color: transparent!important;\ + border-right-color: transparent!important;\ + border-left-color: transparent!important;\ + top: -5px;\ + }\ +", ""); + +}); + +ace.define("ace/ace",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/dom","ace/lib/event","ace/editor","ace/edit_session","ace/undomanager","ace/virtual_renderer","ace/worker/worker_client","ace/keyboard/hash_handler","ace/placeholder","ace/multi_select","ace/mode/folding/fold_mode","ace/theme/textmate","ace/ext/error_marker","ace/config"], function(acequire, exports, module) { +"use strict"; + +acequire("./lib/fixoldbrowsers"); + +var dom = acequire("./lib/dom"); +var event = acequire("./lib/event"); + +var Editor = acequire("./editor").Editor; +var EditSession = acequire("./edit_session").EditSession; +var UndoManager = acequire("./undomanager").UndoManager; +var Renderer = acequire("./virtual_renderer").VirtualRenderer; +acequire("./worker/worker_client"); +acequire("./keyboard/hash_handler"); +acequire("./placeholder"); +acequire("./multi_select"); +acequire("./mode/folding/fold_mode"); +acequire("./theme/textmate"); +acequire("./ext/error_marker"); + +exports.config = acequire("./config"); +exports.acequire = acequire; + +if (typeof define === "function") + exports.define = define; +exports.edit = function(el) { + if (typeof el == "string") { + var _id = el; + el = document.getElementById(_id); + if (!el) + throw new Error("ace.edit can't find div #" + _id); + } + + if (el && el.env && el.env.editor instanceof Editor) + return el.env.editor; + + var value = ""; + if (el && /input|textarea/i.test(el.tagName)) { + var oldNode = el; + value = oldNode.value; + el = dom.createElement("pre"); + oldNode.parentNode.replaceChild(el, oldNode); + } else if (el) { + value = dom.getInnerText(el); + el.innerHTML = ""; + } + + var doc = exports.createEditSession(value); + + var editor = new Editor(new Renderer(el)); + editor.setSession(doc); + + var env = { + document: doc, + editor: editor, + onResize: editor.resize.bind(editor, null) + }; + if (oldNode) env.textarea = oldNode; + event.addListener(window, "resize", env.onResize); + editor.on("destroy", function() { + event.removeListener(window, "resize", env.onResize); + env.editor.container.env = null; // prevent memory leak on old ie + }); + editor.container.env = editor.env = env; + return editor; +}; +exports.createEditSession = function(text, mode) { + var doc = new EditSession(text, mode); + doc.setUndoManager(new UndoManager()); + return doc; +}; +exports.EditSession = EditSession; +exports.UndoManager = UndoManager; +exports.version = "1.2.9"; +}); + (function() { + ace.acequire(["ace/ace"], function(a) { + if (a) { + a.config.init(true); + a.define = ace.define; + } + if (!window.ace) + window.ace = a; + for (var key in a) if (a.hasOwnProperty(key)) + window.ace[key] = a[key]; + }); + })(); + +module.exports = window.ace.acequire("ace/ace"); \ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/node_modules/brace/mode/javascript.js b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/node_modules/brace/mode/javascript.js new file mode 100644 index 0000000..cef278a --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/node_modules/brace/mode/javascript.js @@ -0,0 +1,789 @@ +ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var DocCommentHighlightRules = function() { + this.$rules = { + "start" : [ { + token : "comment.doc.tag", + regex : "@[\\w\\d_]+" // TODO: fix email addresses + }, + DocCommentHighlightRules.getTagRule(), + { + defaultToken : "comment.doc", + caseInsensitive: true + }] + }; +}; + +oop.inherits(DocCommentHighlightRules, TextHighlightRules); + +DocCommentHighlightRules.getTagRule = function(start) { + return { + token : "comment.doc.tag.storage.type", + regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" + }; +}; + +DocCommentHighlightRules.getStartRule = function(start) { + return { + token : "comment.doc", // doc comment + regex : "\\/\\*(?=\\*)", + next : start + }; +}; + +DocCommentHighlightRules.getEndRule = function (start) { + return { + token : "comment.doc", // closing comment + regex : "\\*\\/", + next : start + }; +}; + + +exports.DocCommentHighlightRules = DocCommentHighlightRules; + +}); + +ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var DocCommentHighlightRules = acequire("./doc_comment_highlight_rules").DocCommentHighlightRules; +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; +var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*"; + +var JavaScriptHighlightRules = function(options) { + var keywordMapper = this.createKeywordMapper({ + "variable.language": + "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors + "Namespace|QName|XML|XMLList|" + // E4X + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors + "SyntaxError|TypeError|URIError|" + + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions + "isNaN|parseFloat|parseInt|" + + "JSON|Math|" + // Other + "this|arguments|prototype|window|document" , // Pseudo + "keyword": + "const|yield|import|get|set|async|await|" + + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + + "if|in|of|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + + "__parent__|__count__|escape|unescape|with|__proto__|" + + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", + "storage.type": + "const|let|var|function", + "constant.language": + "null|Infinity|NaN|undefined", + "support.function": + "alert", + "constant.language.boolean": "true|false" + }, "identifier"); + var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; + + var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex + "u[0-9a-fA-F]{4}|" + // unicode + "u{[0-9a-fA-F]{1,6}}|" + // es6 unicode + "[0-2][0-7]{0,2}|" + // oct + "3[0-7][0-7]?|" + // oct + "[4-7][0-7]?|" + //oct + ".)"; + + this.$rules = { + "no_regex" : [ + DocCommentHighlightRules.getStartRule("doc-start"), + comments("no_regex"), + { + token : "string", + regex : "'(?=.)", + next : "qstring" + }, { + token : "string", + regex : '"(?=.)', + next : "qqstring" + }, { + token : "constant.numeric", // hexadecimal, octal and binary + regex : /0(?:[xX][0-9a-fA-F]+|[oO][0-7]+|[bB][01]+)\b/ + }, { + token : "constant.numeric", // decimal integers and floats + regex : /(?:\d\d*(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+\b)?/ + }, { + token : [ + "storage.type", "punctuation.operator", "support.function", + "punctuation.operator", "entity.name.function", "text","keyword.operator" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", + next: "function_arguments" + }, { + token : [ + "storage.type", "punctuation.operator", "entity.name.function", "text", + "keyword.operator", "text", "storage.type", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "entity.name.function", "text", "keyword.operator", "text", "storage.type", + "text", "paren.lparen" + ], + regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "storage.type", "punctuation.operator", "entity.name.function", "text", + "keyword.operator", "text", + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "entity.name.function", "text", "punctuation.operator", + "text", "storage.type", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "text", "text", "storage.type", "text", "paren.lparen" + ], + regex : "(:)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : "keyword", + regex : "from(?=\\s*('|\"))" + }, { + token : "keyword", + regex : "(?:" + kwBeforeRe + ")\\b", + next : "start" + }, { + token : ["support.constant"], + regex : /that\b/ + }, { + token : ["storage.type", "punctuation.operator", "support.function.firebug"], + regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ + }, { + token : keywordMapper, + regex : identifierRe + }, { + token : "punctuation.operator", + regex : /[.](?![.])/, + next : "property" + }, { + token : "storage.type", + regex : /=>/ + }, { + token : "keyword.operator", + regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/, + next : "start" + }, { + token : "punctuation.operator", + regex : /[?:,;.]/, + next : "start" + }, { + token : "paren.lparen", + regex : /[\[({]/, + next : "start" + }, { + token : "paren.rparen", + regex : /[\])}]/ + }, { + token: "comment", + regex: /^#!.*$/ + } + ], + property: [{ + token : "text", + regex : "\\s+" + }, { + token : [ + "storage.type", "punctuation.operator", "entity.name.function", "text", + "keyword.operator", "text", + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()", + next: "function_arguments" + }, { + token : "punctuation.operator", + regex : /[.](?![.])/ + }, { + token : "support.function", + regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ + }, { + token : "support.function.dom", + regex : /(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ + }, { + token : "support.constant", + regex : /(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ + }, { + token : "identifier", + regex : identifierRe + }, { + regex: "", + token: "empty", + next: "no_regex" + } + ], + "start": [ + DocCommentHighlightRules.getStartRule("doc-start"), + comments("start"), + { + token: "string.regexp", + regex: "\\/", + next: "regex" + }, { + token : "text", + regex : "\\s+|^$", + next : "start" + }, { + token: "empty", + regex: "", + next: "no_regex" + } + ], + "regex": [ + { + token: "regexp.keyword.operator", + regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" + }, { + token: "string.regexp", + regex: "/[sxngimy]*", + next: "no_regex" + }, { + token : "invalid", + regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ + }, { + token : "constant.language.escape", + regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ + }, { + token : "constant.language.delimiter", + regex: /\|/ + }, { + token: "constant.language.escape", + regex: /\[\^?/, + next: "regex_character_class" + }, { + token: "empty", + regex: "$", + next: "no_regex" + }, { + defaultToken: "string.regexp" + } + ], + "regex_character_class": [ + { + token: "regexp.charclass.keyword.operator", + regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" + }, { + token: "constant.language.escape", + regex: "]", + next: "regex" + }, { + token: "constant.language.escape", + regex: "-" + }, { + token: "empty", + regex: "$", + next: "no_regex" + }, { + defaultToken: "string.regexp.charachterclass" + } + ], + "function_arguments": [ + { + token: "variable.parameter", + regex: identifierRe + }, { + token: "punctuation.operator", + regex: "[, ]+" + }, { + token: "punctuation.operator", + regex: "$" + }, { + token: "empty", + regex: "", + next: "no_regex" + } + ], + "qqstring" : [ + { + token : "constant.language.escape", + regex : escapedRe + }, { + token : "string", + regex : "\\\\$", + consumeLineEnd : true + }, { + token : "string", + regex : '"|$', + next : "no_regex" + }, { + defaultToken: "string" + } + ], + "qstring" : [ + { + token : "constant.language.escape", + regex : escapedRe + }, { + token : "string", + regex : "\\\\$", + consumeLineEnd : true + }, { + token : "string", + regex : "'|$", + next : "no_regex" + }, { + defaultToken: "string" + } + ] + }; + + + if (!options || !options.noES6) { + this.$rules.no_regex.unshift({ + regex: "[{}]", onMatch: function(val, state, stack) { + this.next = val == "{" ? this.nextState : ""; + if (val == "{" && stack.length) { + stack.unshift("start", state); + } + else if (val == "}" && stack.length) { + stack.shift(); + this.next = stack.shift(); + if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1) + return "paren.quasi.end"; + } + return val == "{" ? "paren.lparen" : "paren.rparen"; + }, + nextState: "start" + }, { + token : "string.quasi.start", + regex : /`/, + push : [{ + token : "constant.language.escape", + regex : escapedRe + }, { + token : "paren.quasi.start", + regex : /\${/, + push : "start" + }, { + token : "string.quasi.end", + regex : /`/, + next : "pop" + }, { + defaultToken: "string.quasi" + }] + }); + + if (!options || options.jsx != false) + JSX.call(this); + } + + this.embedRules(DocCommentHighlightRules, "doc-", + [ DocCommentHighlightRules.getEndRule("no_regex") ]); + + this.normalizeRules(); +}; + +oop.inherits(JavaScriptHighlightRules, TextHighlightRules); + +function JSX() { + var tagRegex = identifierRe.replace("\\d", "\\d\\-"); + var jsxTag = { + onMatch : function(val, state, stack) { + var offset = val.charAt(1) == "/" ? 2 : 1; + if (offset == 1) { + if (state != this.nextState) + stack.unshift(this.next, this.nextState, 0); + else + stack.unshift(this.next); + stack[2]++; + } else if (offset == 2) { + if (state == this.nextState) { + stack[1]--; + if (!stack[1] || stack[1] < 0) { + stack.shift(); + stack.shift(); + } + } + } + return [{ + type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml", + value: val.slice(0, offset) + }, { + type: "meta.tag.tag-name.xml", + value: val.substr(offset) + }]; + }, + regex : "", + onMatch : function(value, currentState, stack) { + if (currentState == stack[0]) + stack.shift(); + if (value.length == 2) { + if (stack[0] == this.nextState) + stack[1]--; + if (!stack[1] || stack[1] < 0) { + stack.splice(0, 2); + } + } + this.next = stack[0] || "start"; + return [{type: this.token, value: value}]; + }, + nextState: "jsx" + }, + jsxJsRule, + comments("jsxAttributes"), + { + token : "entity.other.attribute-name.xml", + regex : tagRegex + }, { + token : "keyword.operator.attribute-equals.xml", + regex : "=" + }, { + token : "text.tag-whitespace.xml", + regex : "\\s+" + }, { + token : "string.attribute-value.xml", + regex : "'", + stateName : "jsx_attr_q", + push : [ + {token : "string.attribute-value.xml", regex: "'", next: "pop"}, + {include : "reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }, { + token : "string.attribute-value.xml", + regex : '"', + stateName : "jsx_attr_qq", + push : [ + {token : "string.attribute-value.xml", regex: '"', next: "pop"}, + {include : "reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }, + jsxTag + ]; + this.$rules.reference = [{ + token : "constant.language.escape.reference.xml", + regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" + }]; +} + +function comments(next) { + return [ + { + token : "comment", // multi line comment + regex : /\/\*/, + next: [ + DocCommentHighlightRules.getTagRule(), + {token : "comment", regex : "\\*\\/", next : next || "pop"}, + {defaultToken : "comment", caseInsensitive: true} + ] + }, { + token : "comment", + regex : "\\/\\/", + next: [ + DocCommentHighlightRules.getTagRule(), + {token : "comment", regex : "$|^", next : next || "pop"}, + {defaultToken : "comment", caseInsensitive: true} + ] + } + ]; +} +exports.JavaScriptHighlightRules = JavaScriptHighlightRules; +}); + +ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; + +var MatchingBraceOutdent = function() {}; + +(function() { + + this.checkOutdent = function(line, input) { + if (! /^\s+$/.test(line)) + return false; + + return /^\s*\}/.test(input); + }; + + this.autoOutdent = function(doc, row) { + var line = doc.getLine(row); + var match = line.match(/^(\s*\})/); + + if (!match) return 0; + + var column = match[1].length; + var openBracePos = doc.findMatchingBracket({row: row, column: column}); + + if (!openBracePos || openBracePos.row == row) return 0; + + var indent = this.$getIndent(doc.getLine(openBracePos.row)); + doc.replace(new Range(row, 0, row, column-1), indent); + }; + + this.$getIndent = function(line) { + return line.match(/^\s*/)[0]; + }; + +}).call(MatchingBraceOutdent.prototype); + +exports.MatchingBraceOutdent = MatchingBraceOutdent; +}); + +ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Range = acequire("../../range").Range; +var BaseFoldMode = acequire("./fold_mode").FoldMode; + +var FoldMode = exports.FoldMode = function(commentRegex) { + if (commentRegex) { + this.foldingStartMarker = new RegExp( + this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) + ); + this.foldingStopMarker = new RegExp( + this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) + ); + } +}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + this.foldingStartMarker = /([\{\[\(])[^\}\]\)]*$|^\s*(\/\*)/; + this.foldingStopMarker = /^[^\[\{\(]*([\}\]\)])|^[\s\*]*(\*\/)/; + this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; + this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; + this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; + this._getFoldWidgetBase = this.getFoldWidget; + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + + if (this.singleLineBlockCommentRe.test(line)) { + if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) + return ""; + } + + var fw = this._getFoldWidgetBase(session, foldStyle, row); + + if (!fw && this.startRegionRe.test(line)) + return "start"; // lineCommentRegionStart + + return fw; + }; + + this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { + var line = session.getLine(row); + + if (this.startRegionRe.test(line)) + return this.getCommentRegionBlock(session, line, row); + + var match = line.match(this.foldingStartMarker); + if (match) { + var i = match.index; + + if (match[1]) + return this.openingBracketBlock(session, match[1], row, i); + + var range = session.getCommentFoldRange(row, i + match[0].length, 1); + + if (range && !range.isMultiLine()) { + if (forceMultiline) { + range = this.getSectionRange(session, row); + } else if (foldStyle != "all") + range = null; + } + + return range; + } + + if (foldStyle === "markbegin") + return; + + var match = line.match(this.foldingStopMarker); + if (match) { + var i = match.index + match[0].length; + + if (match[1]) + return this.closingBracketBlock(session, match[1], row, i); + + return session.getCommentFoldRange(row, i, -1); + } + }; + + this.getSectionRange = function(session, row) { + var line = session.getLine(row); + var startIndent = line.search(/\S/); + var startRow = row; + var startColumn = line.length; + row = row + 1; + var endRow = row; + var maxRow = session.getLength(); + while (++row < maxRow) { + line = session.getLine(row); + var indent = line.search(/\S/); + if (indent === -1) + continue; + if (startIndent > indent) + break; + var subRange = this.getFoldWidgetRange(session, "all", row); + + if (subRange) { + if (subRange.start.row <= startRow) { + break; + } else if (subRange.isMultiLine()) { + row = subRange.end.row; + } else if (startIndent == indent) { + break; + } + } + endRow = row; + } + + return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); + }; + this.getCommentRegionBlock = function(session, line, row) { + var startColumn = line.search(/\s*$/); + var maxRow = session.getLength(); + var startRow = row; + + var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; + var depth = 1; + while (++row < maxRow) { + line = session.getLine(row); + var m = re.exec(line); + if (!m) continue; + if (m[1]) depth--; + else depth++; + + if (!depth) break; + } + + var endRow = row; + if (endRow > startRow) { + return new Range(startRow, startColumn, endRow, line.length); + } + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var JavaScriptHighlightRules = acequire("./javascript_highlight_rules").JavaScriptHighlightRules; +var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; +var WorkerClient = acequire("../worker/worker_client").WorkerClient; +var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; +var CStyleFoldMode = acequire("./folding/cstyle").FoldMode; + +var Mode = function() { + this.HighlightRules = JavaScriptHighlightRules; + + this.$outdent = new MatchingBraceOutdent(); + this.$behaviour = new CstyleBehaviour(); + this.foldingRules = new CStyleFoldMode(); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.lineCommentStart = "//"; + this.blockComment = {start: "/*", end: "*/"}; + this.$quotes = {'"': '"', "'": "'", "`": "`"}; + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + var tokenizedLine = this.getTokenizer().getLineTokens(line, state); + var tokens = tokenizedLine.tokens; + var endState = tokenizedLine.state; + + if (tokens.length && tokens[tokens.length-1].type == "comment") { + return indent; + } + + if (state == "start" || state == "no_regex") { + var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/); + if (match) { + indent += tab; + } + } else if (state == "doc-start") { + if (endState == "start" || endState == "no_regex") { + return ""; + } + var match = line.match(/^\s*(\/?)\*/); + if (match) { + if (match[1]) { + indent += " "; + } + indent += "* "; + } + } + + return indent; + }; + + this.checkOutdent = function(state, line, input) { + return this.$outdent.checkOutdent(line, input); + }; + + this.autoOutdent = function(state, doc, row) { + this.$outdent.autoOutdent(doc, row); + }; + + this.createWorker = function(session) { + var worker = new WorkerClient(["ace"], require("../worker/javascript"), "JavaScriptWorker"); + worker.attachToDocument(session.getDocument()); + + worker.on("annotate", function(results) { + session.setAnnotations(results.data); + }); + + worker.on("terminate", function() { + session.clearAnnotations(); + }); + + return worker; + }; + + this.$id = "ace/mode/javascript"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/node_modules/brace/theme/tomorrow_night_bright.js b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/node_modules/brace/theme/tomorrow_night_bright.js new file mode 100644 index 0000000..6bbc92d --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/node_modules/brace/theme/tomorrow_night_bright.js @@ -0,0 +1,121 @@ +ace.define("ace/theme/tomorrow_night_bright",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { + +exports.isDark = true; +exports.cssClass = "ace-tomorrow-night-bright"; +exports.cssText = ".ace-tomorrow-night-bright .ace_gutter {\ +background: #1a1a1a;\ +color: #DEDEDE\ +}\ +.ace-tomorrow-night-bright .ace_print-margin {\ +width: 1px;\ +background: #1a1a1a\ +}\ +.ace-tomorrow-night-bright {\ +background-color: #000000;\ +color: #DEDEDE\ +}\ +.ace-tomorrow-night-bright .ace_cursor {\ +color: #9F9F9F\ +}\ +.ace-tomorrow-night-bright .ace_marker-layer .ace_selection {\ +background: #424242\ +}\ +.ace-tomorrow-night-bright.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px #000000;\ +}\ +.ace-tomorrow-night-bright .ace_marker-layer .ace_step {\ +background: rgb(102, 82, 0)\ +}\ +.ace-tomorrow-night-bright .ace_marker-layer .ace_bracket {\ +margin: -1px 0 0 -1px;\ +border: 1px solid #888888\ +}\ +.ace-tomorrow-night-bright .ace_marker-layer .ace_highlight {\ +border: 1px solid rgb(110, 119, 0);\ +border-bottom: 0;\ +box-shadow: inset 0 -1px rgb(110, 119, 0);\ +margin: -1px 0 0 -1px;\ +background: rgba(255, 235, 0, 0.1)\ +}\ +.ace-tomorrow-night-bright .ace_marker-layer .ace_active-line {\ +background: #2A2A2A\ +}\ +.ace-tomorrow-night-bright .ace_gutter-active-line {\ +background-color: #2A2A2A\ +}\ +.ace-tomorrow-night-bright .ace_stack {\ +background-color: rgb(66, 90, 44)\ +}\ +.ace-tomorrow-night-bright .ace_marker-layer .ace_selected-word {\ +border: 1px solid #888888\ +}\ +.ace-tomorrow-night-bright .ace_invisible {\ +color: #343434\ +}\ +.ace-tomorrow-night-bright .ace_keyword,\ +.ace-tomorrow-night-bright .ace_meta,\ +.ace-tomorrow-night-bright .ace_storage,\ +.ace-tomorrow-night-bright .ace_storage.ace_type,\ +.ace-tomorrow-night-bright .ace_support.ace_type {\ +color: #C397D8\ +}\ +.ace-tomorrow-night-bright .ace_keyword.ace_operator {\ +color: #70C0B1\ +}\ +.ace-tomorrow-night-bright .ace_constant.ace_character,\ +.ace-tomorrow-night-bright .ace_constant.ace_language,\ +.ace-tomorrow-night-bright .ace_constant.ace_numeric,\ +.ace-tomorrow-night-bright .ace_keyword.ace_other.ace_unit,\ +.ace-tomorrow-night-bright .ace_support.ace_constant,\ +.ace-tomorrow-night-bright .ace_variable.ace_parameter {\ +color: #E78C45\ +}\ +.ace-tomorrow-night-bright .ace_constant.ace_other {\ +color: #EEEEEE\ +}\ +.ace-tomorrow-night-bright .ace_invalid {\ +color: #CED2CF;\ +background-color: #DF5F5F\ +}\ +.ace-tomorrow-night-bright .ace_invalid.ace_deprecated {\ +color: #CED2CF;\ +background-color: #B798BF\ +}\ +.ace-tomorrow-night-bright .ace_fold {\ +background-color: #7AA6DA;\ +border-color: #DEDEDE\ +}\ +.ace-tomorrow-night-bright .ace_entity.ace_name.ace_function,\ +.ace-tomorrow-night-bright .ace_support.ace_function,\ +.ace-tomorrow-night-bright .ace_variable {\ +color: #7AA6DA\ +}\ +.ace-tomorrow-night-bright .ace_support.ace_class,\ +.ace-tomorrow-night-bright .ace_support.ace_type {\ +color: #E7C547\ +}\ +.ace-tomorrow-night-bright .ace_heading,\ +.ace-tomorrow-night-bright .ace_markup.ace_heading,\ +.ace-tomorrow-night-bright .ace_string {\ +color: #B9CA4A\ +}\ +.ace-tomorrow-night-bright .ace_entity.ace_name.ace_tag,\ +.ace-tomorrow-night-bright .ace_entity.ace_other.ace_attribute-name,\ +.ace-tomorrow-night-bright .ace_meta.ace_tag,\ +.ace-tomorrow-night-bright .ace_string.ace_regexp,\ +.ace-tomorrow-night-bright .ace_variable {\ +color: #D54E53\ +}\ +.ace-tomorrow-night-bright .ace_comment {\ +color: #969896\ +}\ +.ace-tomorrow-night-bright .ace_c9searchresults.ace_keyword {\ +color: #C2C280\ +}\ +.ace-tomorrow-night-bright .ace_indent-guide {\ +background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNgYGBgYFBXV/8PAAJoAXX4kT2EAAAAAElFTkSuQmCC) right repeat-y\ +}"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/node_modules/brace/worker/javascript.js b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/node_modules/brace/worker/javascript.js new file mode 100644 index 0000000..2be1a0b --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/node_modules/brace/worker/javascript.js @@ -0,0 +1,2 @@ +module.exports.id = 'ace/mode/javascript_worker'; +module.exports.src = "\"no use strict\";!function(window){function resolveModuleId(id,paths){for(var testPath=id,tail=\"\";testPath;){var alias=paths[testPath];if(\"string\"==typeof alias)return alias+tail;if(alias)return alias.location.replace(/\\/*$/,\"/\")+(tail||alias.main||alias.name);if(alias===!1)return\"\";var i=testPath.lastIndexOf(\"/\");if(-1===i)break;tail=testPath.substr(i)+tail,testPath=testPath.slice(0,i)}return id}if(!(void 0!==window.window&&window.document||window.acequire&&window.define)){window.console||(window.console=function(){var msgs=Array.prototype.slice.call(arguments,0);postMessage({type:\"log\",data:msgs})},window.console.error=window.console.warn=window.console.log=window.console.trace=window.console),window.window=window,window.ace=window,window.onerror=function(message,file,line,col,err){postMessage({type:\"error\",data:{message:message,data:err.data,file:file,line:line,col:col,stack:err.stack}})},window.normalizeModule=function(parentId,moduleName){if(-1!==moduleName.indexOf(\"!\")){var chunks=moduleName.split(\"!\");return window.normalizeModule(parentId,chunks[0])+\"!\"+window.normalizeModule(parentId,chunks[1])}if(\".\"==moduleName.charAt(0)){var base=parentId.split(\"/\").slice(0,-1).join(\"/\");for(moduleName=(base?base+\"/\":\"\")+moduleName;-1!==moduleName.indexOf(\".\")&&previous!=moduleName;){var previous=moduleName;moduleName=moduleName.replace(/^\\.\\//,\"\").replace(/\\/\\.\\//,\"/\").replace(/[^\\/]+\\/\\.\\.\\//,\"\")}}return moduleName},window.acequire=function acequire(parentId,id){if(id||(id=parentId,parentId=null),!id.charAt)throw Error(\"worker.js acequire() accepts only (parentId, id) as arguments\");id=window.normalizeModule(parentId,id);var module=window.acequire.modules[id];if(module)return module.initialized||(module.initialized=!0,module.exports=module.factory().exports),module.exports;if(!window.acequire.tlns)return console.log(\"unable to load \"+id);var path=resolveModuleId(id,window.acequire.tlns);return\".js\"!=path.slice(-3)&&(path+=\".js\"),window.acequire.id=id,window.acequire.modules[id]={},importScripts(path),window.acequire(parentId,id)},window.acequire.modules={},window.acequire.tlns={},window.define=function(id,deps,factory){if(2==arguments.length?(factory=deps,\"string\"!=typeof id&&(deps=id,id=window.acequire.id)):1==arguments.length&&(factory=id,deps=[],id=window.acequire.id),\"function\"!=typeof factory)return window.acequire.modules[id]={exports:factory,initialized:!0},void 0;deps.length||(deps=[\"require\",\"exports\",\"module\"]);var req=function(childId){return window.acequire(id,childId)};window.acequire.modules[id]={exports:{},factory:function(){var module=this,returnExports=factory.apply(this,deps.map(function(dep){switch(dep){case\"require\":return req;case\"exports\":return module.exports;case\"module\":return module;default:return req(dep)}}));return returnExports&&(module.exports=returnExports),module}}},window.define.amd={},acequire.tlns={},window.initBaseUrls=function(topLevelNamespaces){for(var i in topLevelNamespaces)acequire.tlns[i]=topLevelNamespaces[i]},window.initSender=function(){var EventEmitter=window.acequire(\"ace/lib/event_emitter\").EventEmitter,oop=window.acequire(\"ace/lib/oop\"),Sender=function(){};return function(){oop.implement(this,EventEmitter),this.callback=function(data,callbackId){postMessage({type:\"call\",id:callbackId,data:data})},this.emit=function(name,data){postMessage({type:\"event\",name:name,data:data})}}.call(Sender.prototype),new Sender};var main=window.main=null,sender=window.sender=null;window.onmessage=function(e){var msg=e.data;if(msg.event&&sender)sender._signal(msg.event,msg.data);else if(msg.command)if(main[msg.command])main[msg.command].apply(main,msg.args);else{if(!window[msg.command])throw Error(\"Unknown command:\"+msg.command);window[msg.command].apply(window,msg.args)}else if(msg.init){window.initBaseUrls(msg.tlns),acequire(\"ace/lib/es5-shim\"),sender=window.sender=window.initSender();var clazz=acequire(msg.module)[msg.classname];main=window.main=new clazz(sender)}}}}(this),ace.define(\"ace/lib/oop\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},exports.mixin=function(obj,mixin){for(var key in mixin)obj[key]=mixin[key];return obj},exports.implement=function(proto,mixin){exports.mixin(proto,mixin)}}),ace.define(\"ace/range\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";var comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},Range=function(startRow,startColumn,endRow,endColumn){this.start={row:startRow,column:startColumn},this.end={row:endRow,column:endColumn}};(function(){this.isEqual=function(range){return this.start.row===range.start.row&&this.end.row===range.end.row&&this.start.column===range.start.column&&this.end.column===range.end.column},this.toString=function(){return\"Range: [\"+this.start.row+\"/\"+this.start.column+\"] -> [\"+this.end.row+\"/\"+this.end.column+\"]\"},this.contains=function(row,column){return 0==this.compare(row,column)},this.compareRange=function(range){var cmp,end=range.end,start=range.start;return cmp=this.compare(end.row,end.column),1==cmp?(cmp=this.compare(start.row,start.column),1==cmp?2:0==cmp?1:0):-1==cmp?-2:(cmp=this.compare(start.row,start.column),-1==cmp?-1:1==cmp?42:0)},this.comparePoint=function(p){return this.compare(p.row,p.column)},this.containsRange=function(range){return 0==this.comparePoint(range.start)&&0==this.comparePoint(range.end)},this.intersects=function(range){var cmp=this.compareRange(range);return-1==cmp||0==cmp||1==cmp},this.isEnd=function(row,column){return this.end.row==row&&this.end.column==column},this.isStart=function(row,column){return this.start.row==row&&this.start.column==column},this.setStart=function(row,column){\"object\"==typeof row?(this.start.column=row.column,this.start.row=row.row):(this.start.row=row,this.start.column=column)},this.setEnd=function(row,column){\"object\"==typeof row?(this.end.column=row.column,this.end.row=row.row):(this.end.row=row,this.end.column=column)},this.inside=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)||this.isStart(row,column)?!1:!0:!1},this.insideStart=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)?!1:!0:!1},this.insideEnd=function(row,column){return 0==this.compare(row,column)?this.isStart(row,column)?!1:!0:!1},this.compare=function(row,column){return this.isMultiLine()||row!==this.start.row?this.start.row>row?-1:row>this.end.row?1:this.start.row===row?column>=this.start.column?0:-1:this.end.row===row?this.end.column>=column?0:1:0:this.start.column>column?-1:column>this.end.column?1:0},this.compareStart=function(row,column){return this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.compareEnd=function(row,column){return this.end.row==row&&this.end.column==column?1:this.compare(row,column)},this.compareInside=function(row,column){return this.end.row==row&&this.end.column==column?1:this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.clipRows=function(firstRow,lastRow){if(this.end.row>lastRow)var end={row:lastRow+1,column:0};else if(firstRow>this.end.row)var end={row:firstRow,column:0};if(this.start.row>lastRow)var start={row:lastRow+1,column:0};else if(firstRow>this.start.row)var start={row:firstRow,column:0};return Range.fromPoints(start||this.start,end||this.end)},this.extend=function(row,column){var cmp=this.compare(row,column);if(0==cmp)return this;if(-1==cmp)var start={row:row,column:column};else var end={row:row,column:column};return Range.fromPoints(start||this.start,end||this.end)},this.isEmpty=function(){return this.start.row===this.end.row&&this.start.column===this.end.column},this.isMultiLine=function(){return this.start.row!==this.end.row},this.clone=function(){return Range.fromPoints(this.start,this.end)},this.collapseRows=function(){return 0==this.end.column?new Range(this.start.row,0,Math.max(this.start.row,this.end.row-1),0):new Range(this.start.row,0,this.end.row,0)},this.toScreenRange=function(session){var screenPosStart=session.documentToScreenPosition(this.start),screenPosEnd=session.documentToScreenPosition(this.end);return new Range(screenPosStart.row,screenPosStart.column,screenPosEnd.row,screenPosEnd.column)},this.moveBy=function(row,column){this.start.row+=row,this.start.column+=column,this.end.row+=row,this.end.column+=column}}).call(Range.prototype),Range.fromPoints=function(start,end){return new Range(start.row,start.column,end.row,end.column)},Range.comparePoints=comparePoints,Range.comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},exports.Range=Range}),ace.define(\"ace/apply_delta\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.applyDelta=function(docLines,delta){var row=delta.start.row,startColumn=delta.start.column,line=docLines[row]||\"\";switch(delta.action){case\"insert\":var lines=delta.lines;if(1===lines.length)docLines[row]=line.substring(0,startColumn)+delta.lines[0]+line.substring(startColumn);else{var args=[row,1].concat(delta.lines);docLines.splice.apply(docLines,args),docLines[row]=line.substring(0,startColumn)+docLines[row],docLines[row+delta.lines.length-1]+=line.substring(startColumn)}break;case\"remove\":var endColumn=delta.end.column,endRow=delta.end.row;row===endRow?docLines[row]=line.substring(0,startColumn)+line.substring(endColumn):docLines.splice(row,endRow-row+1,line.substring(0,startColumn)+docLines[endRow].substring(endColumn))}}}),ace.define(\"ace/lib/event_emitter\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";var EventEmitter={},stopPropagation=function(){this.propagationStopped=!0},preventDefault=function(){this.defaultPrevented=!0};EventEmitter._emit=EventEmitter._dispatchEvent=function(eventName,e){this._eventRegistry||(this._eventRegistry={}),this._defaultHandlers||(this._defaultHandlers={});var listeners=this._eventRegistry[eventName]||[],defaultHandler=this._defaultHandlers[eventName];if(listeners.length||defaultHandler){\"object\"==typeof e&&e||(e={}),e.type||(e.type=eventName),e.stopPropagation||(e.stopPropagation=stopPropagation),e.preventDefault||(e.preventDefault=preventDefault),listeners=listeners.slice();for(var i=0;listeners.length>i&&(listeners[i](e,this),!e.propagationStopped);i++);return defaultHandler&&!e.defaultPrevented?defaultHandler(e,this):void 0}},EventEmitter._signal=function(eventName,e){var listeners=(this._eventRegistry||{})[eventName];if(listeners){listeners=listeners.slice();for(var i=0;listeners.length>i;i++)listeners[i](e,this)}},EventEmitter.once=function(eventName,callback){var _self=this;callback&&this.addEventListener(eventName,function newCallback(){_self.removeEventListener(eventName,newCallback),callback.apply(null,arguments)})},EventEmitter.setDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers||(handlers=this._defaultHandlers={_disabled_:{}}),handlers[eventName]){var old=handlers[eventName],disabled=handlers._disabled_[eventName];disabled||(handlers._disabled_[eventName]=disabled=[]),disabled.push(old);var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}handlers[eventName]=callback},EventEmitter.removeDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers){var disabled=handlers._disabled_[eventName];if(handlers[eventName]==callback)handlers[eventName],disabled&&this.setDefaultHandler(eventName,disabled.pop());else if(disabled){var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}}},EventEmitter.on=EventEmitter.addEventListener=function(eventName,callback,capturing){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];return listeners||(listeners=this._eventRegistry[eventName]=[]),-1==listeners.indexOf(callback)&&listeners[capturing?\"unshift\":\"push\"](callback),callback},EventEmitter.off=EventEmitter.removeListener=EventEmitter.removeEventListener=function(eventName,callback){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];if(listeners){var index=listeners.indexOf(callback);-1!==index&&listeners.splice(index,1)}},EventEmitter.removeAllListeners=function(eventName){this._eventRegistry&&(this._eventRegistry[eventName]=[])},exports.EventEmitter=EventEmitter}),ace.define(\"ace/anchor\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/lib/event_emitter\"],function(acequire,exports){\"use strict\";var oop=acequire(\"./lib/oop\"),EventEmitter=acequire(\"./lib/event_emitter\").EventEmitter,Anchor=exports.Anchor=function(doc,row,column){this.$onChange=this.onChange.bind(this),this.attach(doc),column===void 0?this.setPosition(row.row,row.column):this.setPosition(row,column)};(function(){function $pointsInOrder(point1,point2,equalPointsInOrder){var bColIsAfter=equalPointsInOrder?point1.column<=point2.column:point1.columnthis.row)){var point=$getTransformedPoint(delta,{row:this.row,column:this.column},this.$insertRight);this.setPosition(point.row,point.column,!0)}},this.setPosition=function(row,column,noClip){var pos;if(pos=noClip?{row:row,column:column}:this.$clipPositionToDocument(row,column),this.row!=pos.row||this.column!=pos.column){var old={row:this.row,column:this.column};this.row=pos.row,this.column=pos.column,this._signal(\"change\",{old:old,value:pos})}},this.detach=function(){this.document.removeEventListener(\"change\",this.$onChange)},this.attach=function(doc){this.document=doc||this.document,this.document.on(\"change\",this.$onChange)},this.$clipPositionToDocument=function(row,column){var pos={};return row>=this.document.getLength()?(pos.row=Math.max(0,this.document.getLength()-1),pos.column=this.document.getLine(pos.row).length):0>row?(pos.row=0,pos.column=0):(pos.row=row,pos.column=Math.min(this.document.getLine(pos.row).length,Math.max(0,column))),0>column&&(pos.column=0),pos}}).call(Anchor.prototype)}),ace.define(\"ace/document\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/apply_delta\",\"ace/lib/event_emitter\",\"ace/range\",\"ace/anchor\"],function(acequire,exports){\"use strict\";var oop=acequire(\"./lib/oop\"),applyDelta=acequire(\"./apply_delta\").applyDelta,EventEmitter=acequire(\"./lib/event_emitter\").EventEmitter,Range=acequire(\"./range\").Range,Anchor=acequire(\"./anchor\").Anchor,Document=function(textOrLines){this.$lines=[\"\"],0===textOrLines.length?this.$lines=[\"\"]:Array.isArray(textOrLines)?this.insertMergedLines({row:0,column:0},textOrLines):this.insert({row:0,column:0},textOrLines)};(function(){oop.implement(this,EventEmitter),this.setValue=function(text){var len=this.getLength()-1;this.remove(new Range(0,0,len,this.getLine(len).length)),this.insert({row:0,column:0},text)},this.getValue=function(){return this.getAllLines().join(this.getNewLineCharacter())},this.createAnchor=function(row,column){return new Anchor(this,row,column)},this.$split=0===\"aaa\".split(/a/).length?function(text){return text.replace(/\\r\\n|\\r/g,\"\\n\").split(\"\\n\")}:function(text){return text.split(/\\r\\n|\\r|\\n/)},this.$detectNewLine=function(text){var match=text.match(/^.*?(\\r\\n|\\r|\\n)/m);this.$autoNewLine=match?match[1]:\"\\n\",this._signal(\"changeNewLineMode\")},this.getNewLineCharacter=function(){switch(this.$newLineMode){case\"windows\":return\"\\r\\n\";case\"unix\":return\"\\n\";default:return this.$autoNewLine||\"\\n\"}},this.$autoNewLine=\"\",this.$newLineMode=\"auto\",this.setNewLineMode=function(newLineMode){this.$newLineMode!==newLineMode&&(this.$newLineMode=newLineMode,this._signal(\"changeNewLineMode\"))},this.getNewLineMode=function(){return this.$newLineMode},this.isNewLine=function(text){return\"\\r\\n\"==text||\"\\r\"==text||\"\\n\"==text},this.getLine=function(row){return this.$lines[row]||\"\"},this.getLines=function(firstRow,lastRow){return this.$lines.slice(firstRow,lastRow+1)},this.getAllLines=function(){return this.getLines(0,this.getLength())},this.getLength=function(){return this.$lines.length},this.getTextRange=function(range){return this.getLinesForRange(range).join(this.getNewLineCharacter())},this.getLinesForRange=function(range){var lines;if(range.start.row===range.end.row)lines=[this.getLine(range.start.row).substring(range.start.column,range.end.column)];else{lines=this.getLines(range.start.row,range.end.row),lines[0]=(lines[0]||\"\").substring(range.start.column);var l=lines.length-1;range.end.row-range.start.row==l&&(lines[l]=lines[l].substring(0,range.end.column))}return lines},this.insertLines=function(row,lines){return console.warn(\"Use of document.insertLines is deprecated. Use the insertFullLines method instead.\"),this.insertFullLines(row,lines)},this.removeLines=function(firstRow,lastRow){return console.warn(\"Use of document.removeLines is deprecated. Use the removeFullLines method instead.\"),this.removeFullLines(firstRow,lastRow)},this.insertNewLine=function(position){return console.warn(\"Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead.\"),this.insertMergedLines(position,[\"\",\"\"])},this.insert=function(position,text){return 1>=this.getLength()&&this.$detectNewLine(text),this.insertMergedLines(position,this.$split(text))},this.insertInLine=function(position,text){var start=this.clippedPos(position.row,position.column),end=this.pos(position.row,position.column+text.length);return this.applyDelta({start:start,end:end,action:\"insert\",lines:[text]},!0),this.clonePos(end)},this.clippedPos=function(row,column){var length=this.getLength();void 0===row?row=length:0>row?row=0:row>=length&&(row=length-1,column=void 0);var line=this.getLine(row);return void 0==column&&(column=line.length),column=Math.min(Math.max(column,0),line.length),{row:row,column:column}},this.clonePos=function(pos){return{row:pos.row,column:pos.column}},this.pos=function(row,column){return{row:row,column:column}},this.$clipPosition=function(position){var length=this.getLength();return position.row>=length?(position.row=Math.max(0,length-1),position.column=this.getLine(length-1).length):(position.row=Math.max(0,position.row),position.column=Math.min(Math.max(position.column,0),this.getLine(position.row).length)),position},this.insertFullLines=function(row,lines){row=Math.min(Math.max(row,0),this.getLength());var column=0;this.getLength()>row?(lines=lines.concat([\"\"]),column=0):(lines=[\"\"].concat(lines),row--,column=this.$lines[row].length),this.insertMergedLines({row:row,column:column},lines)},this.insertMergedLines=function(position,lines){var start=this.clippedPos(position.row,position.column),end={row:start.row+lines.length-1,column:(1==lines.length?start.column:0)+lines[lines.length-1].length};return this.applyDelta({start:start,end:end,action:\"insert\",lines:lines}),this.clonePos(end)},this.remove=function(range){var start=this.clippedPos(range.start.row,range.start.column),end=this.clippedPos(range.end.row,range.end.column);return this.applyDelta({start:start,end:end,action:\"remove\",lines:this.getLinesForRange({start:start,end:end})}),this.clonePos(start)},this.removeInLine=function(row,startColumn,endColumn){var start=this.clippedPos(row,startColumn),end=this.clippedPos(row,endColumn);return this.applyDelta({start:start,end:end,action:\"remove\",lines:this.getLinesForRange({start:start,end:end})},!0),this.clonePos(start)},this.removeFullLines=function(firstRow,lastRow){firstRow=Math.min(Math.max(0,firstRow),this.getLength()-1),lastRow=Math.min(Math.max(0,lastRow),this.getLength()-1);var deleteFirstNewLine=lastRow==this.getLength()-1&&firstRow>0,deleteLastNewLine=this.getLength()-1>lastRow,startRow=deleteFirstNewLine?firstRow-1:firstRow,startCol=deleteFirstNewLine?this.getLine(startRow).length:0,endRow=deleteLastNewLine?lastRow+1:lastRow,endCol=deleteLastNewLine?0:this.getLine(endRow).length,range=new Range(startRow,startCol,endRow,endCol),deletedLines=this.$lines.slice(firstRow,lastRow+1);return this.applyDelta({start:range.start,end:range.end,action:\"remove\",lines:this.getLinesForRange(range)}),deletedLines},this.removeNewLine=function(row){this.getLength()-1>row&&row>=0&&this.applyDelta({start:this.pos(row,this.getLine(row).length),end:this.pos(row+1,0),action:\"remove\",lines:[\"\",\"\"]})},this.replace=function(range,text){if(range instanceof Range||(range=Range.fromPoints(range.start,range.end)),0===text.length&&range.isEmpty())return range.start;if(text==this.getTextRange(range))return range.end;this.remove(range);var end;return end=text?this.insert(range.start,text):range.start},this.applyDeltas=function(deltas){for(var i=0;deltas.length>i;i++)this.applyDelta(deltas[i])},this.revertDeltas=function(deltas){for(var i=deltas.length-1;i>=0;i--)this.revertDelta(deltas[i])},this.applyDelta=function(delta,doNotValidate){var isInsert=\"insert\"==delta.action;(isInsert?1>=delta.lines.length&&!delta.lines[0]:!Range.comparePoints(delta.start,delta.end))||(isInsert&&delta.lines.length>2e4&&this.$splitAndapplyLargeDelta(delta,2e4),applyDelta(this.$lines,delta,doNotValidate),this._signal(\"change\",delta))},this.$splitAndapplyLargeDelta=function(delta,MAX){for(var lines=delta.lines,l=lines.length,row=delta.start.row,column=delta.start.column,from=0,to=0;;){from=to,to+=MAX-1;var chunk=lines.slice(from,to);if(to>l){delta.lines=chunk,delta.start.row=row+from,delta.start.column=column;break}chunk.push(\"\"),this.applyDelta({start:this.pos(row+from,column),end:this.pos(row+to,column=0),action:delta.action,lines:chunk},!0)}},this.revertDelta=function(delta){this.applyDelta({start:this.clonePos(delta.start),end:this.clonePos(delta.end),action:\"insert\"==delta.action?\"remove\":\"insert\",lines:delta.lines.slice()})},this.indexToPosition=function(index,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,i=startRow||0,l=lines.length;l>i;i++)if(index-=lines[i].length+newlineLength,0>index)return{row:i,column:index+lines[i].length+newlineLength};return{row:l-1,column:lines[l-1].length}},this.positionToIndex=function(pos,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,index=0,row=Math.min(pos.row,lines.length),i=startRow||0;row>i;++i)index+=lines[i].length+newlineLength;return index+pos.column}}).call(Document.prototype),exports.Document=Document}),ace.define(\"ace/lib/lang\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.last=function(a){return a[a.length-1]},exports.stringReverse=function(string){return string.split(\"\").reverse().join(\"\")},exports.stringRepeat=function(string,count){for(var result=\"\";count>0;)1&count&&(result+=string),(count>>=1)&&(string+=string);return result};var trimBeginRegexp=/^\\s\\s*/,trimEndRegexp=/\\s\\s*$/;exports.stringTrimLeft=function(string){return string.replace(trimBeginRegexp,\"\")},exports.stringTrimRight=function(string){return string.replace(trimEndRegexp,\"\")},exports.copyObject=function(obj){var copy={};for(var key in obj)copy[key]=obj[key];return copy},exports.copyArray=function(array){for(var copy=[],i=0,l=array.length;l>i;i++)copy[i]=array[i]&&\"object\"==typeof array[i]?this.copyObject(array[i]):array[i];return copy},exports.deepCopy=function deepCopy(obj){if(\"object\"!=typeof obj||!obj)return obj;var copy;if(Array.isArray(obj)){copy=[];for(var key=0;obj.length>key;key++)copy[key]=deepCopy(obj[key]);return copy}if(\"[object Object]\"!==Object.prototype.toString.call(obj))return obj;copy={};for(var key in obj)copy[key]=deepCopy(obj[key]);return copy},exports.arrayToMap=function(arr){for(var map={},i=0;arr.length>i;i++)map[arr[i]]=1;return map},exports.createMap=function(props){var map=Object.create(null);for(var i in props)map[i]=props[i];return map},exports.arrayRemove=function(array,value){for(var i=0;array.length>=i;i++)value===array[i]&&array.splice(i,1)},exports.escapeRegExp=function(str){return str.replace(/([.*+?^${}()|[\\]\\/\\\\])/g,\"\\\\$1\")},exports.escapeHTML=function(str){return str.replace(/&/g,\"&\").replace(/\"/g,\""\").replace(/'/g,\"'\").replace(/i;i+=2){if(Array.isArray(data[i+1]))var d={action:\"insert\",start:data[i],lines:data[i+1]};else var d={action:\"remove\",start:data[i],end:data[i+1]};doc.applyDelta(d,!0)}return _self.$timeout?deferredUpdate.schedule(_self.$timeout):(_self.onUpdate(),void 0)})};(function(){this.$timeout=500,this.setTimeout=function(timeout){this.$timeout=timeout},this.setValue=function(value){this.doc.setValue(value),this.deferredUpdate.schedule(this.$timeout)},this.getValue=function(callbackId){this.sender.callback(this.doc.getValue(),callbackId)},this.onUpdate=function(){},this.isPending=function(){return this.deferredUpdate.isPending()}}).call(Mirror.prototype)}),ace.define(\"ace/mode/javascript/jshint\",[\"require\",\"exports\",\"module\"],function(acequire,exports,module){module.exports=function outer(modules,cache,entry){function newRequire(name,jumped){if(!cache[name]){if(!modules[name]){var currentRequire=\"function\"==typeof acequire&&acequire;if(!jumped&¤tRequire)return currentRequire(name,!0);if(previousRequire)return previousRequire(name,!0);var err=Error(\"Cannot find module '\"+name+\"'\");throw err.code=\"MODULE_NOT_FOUND\",err}var m=cache[name]={exports:{}};modules[name][0].call(m.exports,function(x){var id=modules[name][1][x];return newRequire(id?id:x)},m,m.exports,outer,modules,cache,entry)}return cache[name].exports}for(var previousRequire=\"function\"==typeof acequire&&acequire,i=0;entry.length>i;i++)newRequire(entry[i]);return newRequire(entry[0])}({\"/node_modules/browserify/node_modules/events/events.js\":[function(_dereq_,module){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return\"function\"==typeof arg}function isNumber(arg){return\"number\"==typeof arg}function isObject(arg){return\"object\"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError(\"n must be a positive number\");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),\"error\"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if(er=arguments[1],er instanceof Error)throw er;throw TypeError('Uncaught, unspecified \"error\" event.')}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:for(len=arguments.length,args=Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];handler.apply(this,args)}else if(isObject(handler)){for(len=arguments.length,args=Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];for(listeners=handler.slice(),len=listeners.length,i=0;len>i;i++)listeners[i].apply(this,args)}return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError(\"listener must be a function\");if(this._events||(this._events={}),this._events.newListener&&this.emit(\"newListener\",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned){var m;m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error(\"(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.\",this._events[type].length),\"function\"==typeof console.trace&&console.trace())}return this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError(\"listener must be a function\");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError(\"listener must be a function\");if(!this._events||!this._events[type])return this;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit(\"removeListener\",type,listener);else if(isObject(list)){for(i=length;i-->0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit(\"removeListener\",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)\"removeListener\"!==key&&this.removeAllListeners(key);return this.removeAllListeners(\"removeListener\"),this._events={},this\n}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.listenerCount=function(emitter,type){var ret;return ret=emitter._events&&emitter._events[type]?isFunction(emitter._events[type])?1:emitter._events[type].length:0}},{}],\"/node_modules/jshint/data/ascii-identifier-data.js\":[function(_dereq_,module){for(var identifierStartTable=[],i=0;128>i;i++)identifierStartTable[i]=36===i||i>=65&&90>=i||95===i||i>=97&&122>=i;for(var identifierPartTable=[],i=0;128>i;i++)identifierPartTable[i]=identifierStartTable[i]||i>=48&&57>=i;module.exports={asciiIdentifierStartTable:identifierStartTable,asciiIdentifierPartTable:identifierPartTable}},{}],\"/node_modules/jshint/lodash.js\":[function(_dereq_,module,exports){(function(global){(function(){function baseFindIndex(array,predicate,fromRight){for(var length=array.length,index=fromRight?length:-1;fromRight?index--:length>++index;)if(predicate(array[index],index,array))return index;return-1}function baseIndexOf(array,value,fromIndex){if(value!==value)return indexOfNaN(array,fromIndex);for(var index=fromIndex-1,length=array.length;length>++index;)if(array[index]===value)return index;return-1}function baseIsFunction(value){return\"function\"==typeof value||!1}function baseToString(value){return\"string\"==typeof value?value:null==value?\"\":value+\"\"}function indexOfNaN(array,fromIndex,fromRight){for(var length=array.length,index=fromIndex+(fromRight?0:-1);fromRight?index--:length>++index;){var other=array[index];if(other!==other)return index}return-1}function isObjectLike(value){return!!value&&\"object\"==typeof value}function lodash(){}function arrayCopy(source,array){var index=-1,length=source.length;for(array||(array=Array(length));length>++index;)array[index]=source[index];return array}function arrayEach(array,iteratee){for(var index=-1,length=array.length;length>++index&&iteratee(array[index],index,array)!==!1;);return array}function arrayFilter(array,predicate){for(var index=-1,length=array.length,resIndex=-1,result=[];length>++index;){var value=array[index];predicate(value,index,array)&&(result[++resIndex]=value)}return result}function arrayMap(array,iteratee){for(var index=-1,length=array.length,result=Array(length);length>++index;)result[index]=iteratee(array[index],index,array);return result}function arrayMax(array){for(var index=-1,length=array.length,result=NEGATIVE_INFINITY;length>++index;){var value=array[index];value>result&&(result=value)}return result}function arraySome(array,predicate){for(var index=-1,length=array.length;length>++index;)if(predicate(array[index],index,array))return!0;return!1}function assignWith(object,source,customizer){var props=keys(source);push.apply(props,getSymbols(source));for(var index=-1,length=props.length;length>++index;){var key=props[index],value=object[key],result=customizer(value,source[key],key,object,source);(result===result?result===value:value!==value)&&(value!==undefined||key in object)||(object[key]=result)}return object}function baseCopy(source,props,object){object||(object={});for(var index=-1,length=props.length;length>++index;){var key=props[index];object[key]=source[key]}return object}function baseCallback(func,thisArg,argCount){var type=typeof func;return\"function\"==type?thisArg===undefined?func:bindCallback(func,thisArg,argCount):null==func?identity:\"object\"==type?baseMatches(func):thisArg===undefined?property(func):baseMatchesProperty(func,thisArg)}function baseClone(value,isDeep,customizer,key,object,stackA,stackB){var result;if(customizer&&(result=object?customizer(value,key,object):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return arrayCopy(value,result)}else{var tag=objToString.call(value),isFunc=tag==funcTag;if(tag!=objectTag&&tag!=argsTag&&(!isFunc||object))return cloneableTags[tag]?initCloneByTag(value,tag,isDeep):object?value:{};if(result=initCloneObject(isFunc?{}:value),!isDeep)return baseAssign(result,value)}stackA||(stackA=[]),stackB||(stackB=[]);for(var length=stackA.length;length--;)if(stackA[length]==value)return stackB[length];return stackA.push(value),stackB.push(result),(isArr?arrayEach:baseForOwn)(value,function(subValue,key){result[key]=baseClone(subValue,isDeep,customizer,key,value,stackA,stackB)}),result}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseForIn(object,iteratee){return baseFor(object,iteratee,keysIn)}function baseForOwn(object,iteratee){return baseFor(object,iteratee,keys)}function baseGet(object,path,pathKey){if(null!=object){pathKey!==undefined&&pathKey in toObject(object)&&(path=[pathKey]);for(var index=-1,length=path.length;null!=object&&length>++index;)var result=object=object[path[index]];return result}}function baseIsEqual(value,other,customizer,isLoose,stackA,stackB){if(value===other)return 0!==value||1/value==1/other;var valType=typeof value,othType=typeof other;return\"function\"!=valType&&\"object\"!=valType&&\"function\"!=othType&&\"object\"!=othType||null==value||null==other?value!==value&&other!==other:baseIsEqualDeep(value,other,baseIsEqual,customizer,isLoose,stackA,stackB)}function baseIsEqualDeep(object,other,equalFunc,customizer,isLoose,stackA,stackB){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=arrayTag,othTag=arrayTag;objIsArr||(objTag=objToString.call(object),objTag==argsTag?objTag=objectTag:objTag!=objectTag&&(objIsArr=isTypedArray(object))),othIsArr||(othTag=objToString.call(other),othTag==argsTag?othTag=objectTag:othTag!=objectTag&&(othIsArr=isTypedArray(other)));var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&!objIsArr&&!objIsObj)return equalByTag(object,other,objTag);if(!isLoose){var valWrapped=objIsObj&&hasOwnProperty.call(object,\"__wrapped__\"),othWrapped=othIsObj&&hasOwnProperty.call(other,\"__wrapped__\");if(valWrapped||othWrapped)return equalFunc(valWrapped?object.value():object,othWrapped?other.value():other,customizer,isLoose,stackA,stackB)}if(!isSameTag)return!1;stackA||(stackA=[]),stackB||(stackB=[]);for(var length=stackA.length;length--;)if(stackA[length]==object)return stackB[length]==other;stackA.push(object),stackB.push(other);var result=(objIsArr?equalArrays:equalObjects)(object,other,equalFunc,customizer,isLoose,stackA,stackB);return stackA.pop(),stackB.pop(),result}function baseIsMatch(object,props,values,strictCompareFlags,customizer){for(var index=-1,length=props.length,noCustomizer=!customizer;length>++index;)if(noCustomizer&&strictCompareFlags[index]?values[index]!==object[props[index]]:!(props[index]in object))return!1;for(index=-1;length>++index;){var key=props[index],objValue=object[key],srcValue=values[index];if(noCustomizer&&strictCompareFlags[index])var result=objValue!==undefined||key in object;else result=customizer?customizer(objValue,srcValue,key):undefined,result===undefined&&(result=baseIsEqual(srcValue,objValue,customizer,!0));if(!result)return!1}return!0}function baseMatches(source){var props=keys(source),length=props.length;if(!length)return constant(!0);if(1==length){var key=props[0],value=source[key];if(isStrictComparable(value))return function(object){return null==object?!1:object[key]===value&&(value!==undefined||key in toObject(object))}}for(var values=Array(length),strictCompareFlags=Array(length);length--;)value=source[props[length]],values[length]=value,strictCompareFlags[length]=isStrictComparable(value);return function(object){return null!=object&&baseIsMatch(toObject(object),props,values,strictCompareFlags)}}function baseMatchesProperty(path,value){var isArr=isArray(path),isCommon=isKey(path)&&isStrictComparable(value),pathKey=path+\"\";return path=toPath(path),function(object){if(null==object)return!1;var key=pathKey;if(object=toObject(object),!(!isArr&&isCommon||key in object)){if(object=1==path.length?object:baseGet(object,baseSlice(path,0,-1)),null==object)return!1;key=last(path),object=toObject(object)}return object[key]===value?value!==undefined||key in object:baseIsEqual(value,object[key],null,!0)}}function baseMerge(object,source,customizer,stackA,stackB){if(!isObject(object))return object;var isSrcArr=isLength(source.length)&&(isArray(source)||isTypedArray(source));if(!isSrcArr){var props=keys(source);push.apply(props,getSymbols(source))}return arrayEach(props||source,function(srcValue,key){if(props&&(key=srcValue,srcValue=source[key]),isObjectLike(srcValue))stackA||(stackA=[]),stackB||(stackB=[]),baseMergeDeep(object,source,key,baseMerge,customizer,stackA,stackB);else{var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=result===undefined;isCommon&&(result=srcValue),!isSrcArr&&result===undefined||!isCommon&&(result===result?result===value:value!==value)||(object[key]=result)}}),object}function baseMergeDeep(object,source,key,mergeFunc,customizer,stackA,stackB){for(var length=stackA.length,srcValue=source[key];length--;)if(stackA[length]==srcValue)return object[key]=stackB[length],undefined;var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=result===undefined;isCommon&&(result=srcValue,isLength(srcValue.length)&&(isArray(srcValue)||isTypedArray(srcValue))?result=isArray(value)?value:getLength(value)?arrayCopy(value):[]:isPlainObject(srcValue)||isArguments(srcValue)?result=isArguments(value)?toPlainObject(value):isPlainObject(value)?value:{}:isCommon=!1),stackA.push(srcValue),stackB.push(result),isCommon?object[key]=mergeFunc(result,srcValue,customizer,stackA,stackB):(result===result?result!==value:value===value)&&(object[key]=result)}function baseProperty(key){return function(object){return null==object?undefined:object[key]}}function basePropertyDeep(path){var pathKey=path+\"\";return path=toPath(path),function(object){return baseGet(object,path,pathKey)}}function baseSlice(array,start,end){var index=-1,length=array.length;start=null==start?0:+start||0,0>start&&(start=-start>length?0:length+start),end=end===undefined||end>length?length:+end||0,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);length>++index;)result[index]=array[index+start];return result}function baseSome(collection,predicate){var result;return baseEach(collection,function(value,index,collection){return result=predicate(value,index,collection),!result}),!!result}function baseValues(object,props){for(var index=-1,length=props.length,result=Array(length);length>++index;)result[index]=object[props[index]];return result}function binaryIndex(array,value,retHighest){var low=0,high=array?array.length:low;if(\"number\"==typeof value&&value===value&&HALF_MAX_ARRAY_LENGTH>=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return binaryIndexBy(array,value,identity,retHighest)}function binaryIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsUndef=value===undefined;high>low;){var mid=floor((low+high)/2),computed=iteratee(array[mid]),isReflexive=computed===computed;if(valIsNaN)var setLow=isReflexive||retHighest;else setLow=valIsUndef?isReflexive&&(retHighest||computed!==undefined):retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function bindCallback(func,thisArg,argCount){if(\"function\"!=typeof func)return identity;if(thisArg===undefined)return func;switch(argCount){case 1:return function(value){return func.call(thisArg,value)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)};case 4:return function(accumulator,value,index,collection){return func.call(thisArg,accumulator,value,index,collection)};case 5:return function(value,other,key,object,source){return func.call(thisArg,value,other,key,object,source)}}return function(){return func.apply(thisArg,arguments)}}function bufferClone(buffer){return bufferSlice.call(buffer,0)}function createAssigner(assigner){return restParam(function(object,sources){var index=-1,length=null==object?0:sources.length,customizer=length>2&&sources[length-2],guard=length>2&&sources[2],thisArg=length>1&&sources[length-1];for(\"function\"==typeof customizer?(customizer=bindCallback(customizer,thisArg,5),length-=2):(customizer=\"function\"==typeof thisArg?thisArg:null,length-=customizer?1:0),guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?null:customizer,length=1);length>++index;){var source=sources[index];source&&assigner(object,source,customizer)}return object})}function createBaseEach(eachFunc,fromRight){return function(collection,iteratee){var length=collection?getLength(collection):0;if(!isLength(length))return eachFunc(collection,iteratee);for(var index=fromRight?length:-1,iterable=toObject(collection);(fromRight?index--:length>++index)&&iteratee(iterable[index],index,iterable)!==!1;);return collection}}function createBaseFor(fromRight){return function(object,iteratee,keysFunc){for(var iterable=toObject(object),props=keysFunc(object),length=props.length,index=fromRight?length:-1;fromRight?index--:length>++index;){var key=props[index];if(iteratee(iterable[key],key,iterable)===!1)break}return object}}function createFindIndex(fromRight){return function(array,predicate,thisArg){return array&&array.length?(predicate=getCallback(predicate,thisArg,3),baseFindIndex(array,predicate,fromRight)):-1}}function createForEach(arrayFunc,eachFunc){return function(collection,iteratee,thisArg){return\"function\"==typeof iteratee&&thisArg===undefined&&isArray(collection)?arrayFunc(collection,iteratee):eachFunc(collection,bindCallback(iteratee,thisArg,3))}}function equalArrays(array,other,equalFunc,customizer,isLoose,stackA,stackB){var index=-1,arrLength=array.length,othLength=other.length,result=!0;if(arrLength!=othLength&&!(isLoose&&othLength>arrLength))return!1;for(;result&&arrLength>++index;){var arrValue=array[index],othValue=other[index];if(result=undefined,customizer&&(result=isLoose?customizer(othValue,arrValue,index):customizer(arrValue,othValue,index)),result===undefined)if(isLoose)for(var othIndex=othLength;othIndex--&&(othValue=other[othIndex],!(result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isLoose,stackA,stackB))););else result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isLoose,stackA,stackB)}return!!result}function equalByTag(object,other,tag){switch(tag){case boolTag:case dateTag:return+object==+other;case errorTag:return object.name==other.name&&object.message==other.message;case numberTag:return object!=+object?other!=+other:0==object?1/object==1/other:object==+other;case regexpTag:case stringTag:return object==other+\"\"}return!1}function equalObjects(object,other,equalFunc,customizer,isLoose,stackA,stackB){var objProps=keys(object),objLength=objProps.length,othProps=keys(other),othLength=othProps.length;if(objLength!=othLength&&!isLoose)return!1;for(var skipCtor=isLoose,index=-1;objLength>++index;){var key=objProps[index],result=isLoose?key in other:hasOwnProperty.call(other,key);if(result){var objValue=object[key],othValue=other[key];result=undefined,customizer&&(result=isLoose?customizer(othValue,objValue,key):customizer(objValue,othValue,key)),result===undefined&&(result=objValue&&objValue===othValue||equalFunc(objValue,othValue,customizer,isLoose,stackA,stackB))}if(!result)return!1;skipCtor||(skipCtor=\"constructor\"==key)}if(!skipCtor){var objCtor=object.constructor,othCtor=other.constructor;if(objCtor!=othCtor&&\"constructor\"in object&&\"constructor\"in other&&!(\"function\"==typeof objCtor&&objCtor instanceof objCtor&&\"function\"==typeof othCtor&&othCtor instanceof othCtor))return!1}return!0}function getCallback(func,thisArg,argCount){var result=lodash.callback||callback;return result=result===callback?baseCallback:result,argCount?result(func,thisArg,argCount):result}function getIndexOf(collection,target,fromIndex){var result=lodash.indexOf||indexOf;return result=result===indexOf?baseIndexOf:result,collection?result(collection,target,fromIndex):result}function initCloneArray(array){var length=array.length,result=new array.constructor(length);return length&&\"string\"==typeof array[0]&&hasOwnProperty.call(array,\"index\")&&(result.index=array.index,result.input=array.input),result}function initCloneObject(object){var Ctor=object.constructor;return\"function\"==typeof Ctor&&Ctor instanceof Ctor||(Ctor=Object),new Ctor}function initCloneByTag(object,tag,isDeep){var Ctor=object.constructor;switch(tag){case arrayBufferTag:return bufferClone(object);case boolTag:case dateTag:return new Ctor(+object);case float32Tag:case float64Tag:case int8Tag:case int16Tag:case int32Tag:case uint8Tag:case uint8ClampedTag:case uint16Tag:case uint32Tag:var buffer=object.buffer;return new Ctor(isDeep?bufferClone(buffer):buffer,object.byteOffset,object.length);case numberTag:case stringTag:return new Ctor(object);case regexpTag:var result=new Ctor(object.source,reFlags.exec(object));result.lastIndex=object.lastIndex}return result}function isIndex(value,length){return value=+value,length=null==length?MAX_SAFE_INTEGER:length,value>-1&&0==value%1&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;if(\"number\"==type)var length=getLength(object),prereq=isLength(length)&&isIndex(index,length);else prereq=\"string\"==type&&index in object;if(prereq){var other=object[index];return value===value?value===other:other!==other}return!1}function isKey(value,object){var type=typeof value;if(\"string\"==type&&reIsPlainProp.test(value)||\"number\"==type)return!0;if(isArray(value))return!1;var result=!reIsDeepProp.test(value);return result||null!=object&&value in toObject(object)}function isLength(value){return\"number\"==typeof value&&value>-1&&0==value%1&&MAX_SAFE_INTEGER>=value}function isStrictComparable(value){return value===value&&(0===value?1/value>0:!isObject(value))}function shimIsPlainObject(value){var Ctor;if(lodash.support,!isObjectLike(value)||objToString.call(value)!=objectTag||!hasOwnProperty.call(value,\"constructor\")&&(Ctor=value.constructor,\"function\"==typeof Ctor&&!(Ctor instanceof Ctor)))return!1;var result;return baseForIn(value,function(subValue,key){result=key}),result===undefined||hasOwnProperty.call(value,result)}function shimKeys(object){for(var props=keysIn(object),propsLength=props.length,length=propsLength&&object.length,support=lodash.support,allowIndexes=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object)),index=-1,result=[];propsLength>++index;){var key=props[index];(allowIndexes&&isIndex(key,length)||hasOwnProperty.call(object,key))&&result.push(key)}return result}function toObject(value){return isObject(value)?value:Object(value)}function toPath(value){if(isArray(value))return value;var result=[];return baseToString(value).replace(rePropName,function(match,number,quote,string){result.push(quote?string.replace(reEscapeChar,\"$1\"):number||match)}),result}function indexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;if(\"number\"==typeof fromIndex)fromIndex=0>fromIndex?nativeMax(length+fromIndex,0):fromIndex;else if(fromIndex){var index=binaryIndex(array,value),other=array[index];return(value===value?value===other:other!==other)?index:-1}return baseIndexOf(array,value,fromIndex||0)}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function slice(array,start,end){var length=array?array.length:0;return length?(end&&\"number\"!=typeof end&&isIterateeCall(array,start,end)&&(start=0,end=length),baseSlice(array,start,end)):[]}function unzip(array){for(var index=-1,length=(array&&array.length&&arrayMax(arrayMap(array,getLength)))>>>0,result=Array(length);length>++index;)result[index]=arrayMap(array,baseProperty(index));return result}function includes(collection,target,fromIndex,guard){var length=collection?getLength(collection):0;return isLength(length)||(collection=values(collection),length=collection.length),length?(fromIndex=\"number\"!=typeof fromIndex||guard&&isIterateeCall(target,fromIndex,guard)?0:0>fromIndex?nativeMax(length+fromIndex,0):fromIndex||0,\"string\"==typeof collection||!isArray(collection)&&isString(collection)?length>fromIndex&&collection.indexOf(target,fromIndex)>-1:getIndexOf(collection,target,fromIndex)>-1):!1}function reject(collection,predicate,thisArg){var func=isArray(collection)?arrayFilter:baseFilter;return predicate=getCallback(predicate,thisArg,3),func(collection,function(value,index,collection){return!predicate(value,index,collection)})}function some(collection,predicate,thisArg){var func=isArray(collection)?arraySome:baseSome;return thisArg&&isIterateeCall(collection,predicate,thisArg)&&(predicate=null),(\"function\"!=typeof predicate||thisArg!==undefined)&&(predicate=getCallback(predicate,thisArg,3)),func(collection,predicate)}function restParam(func,start){if(\"function\"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=nativeMax(start===undefined?func.length-1:+start||0,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),rest=Array(length);length>++index;)rest[index]=args[start+index];switch(start){case 0:return func.call(this,rest);case 1:return func.call(this,args[0],rest);case 2:return func.call(this,args[0],args[1],rest)}var otherArgs=Array(start+1);for(index=-1;start>++index;)otherArgs[index]=args[index];return otherArgs[start]=rest,func.apply(this,otherArgs)}}function clone(value,isDeep,customizer,thisArg){return isDeep&&\"boolean\"!=typeof isDeep&&isIterateeCall(value,isDeep,customizer)?isDeep=!1:\"function\"==typeof isDeep&&(thisArg=customizer,customizer=isDeep,isDeep=!1),customizer=\"function\"==typeof customizer&&bindCallback(customizer,thisArg,1),baseClone(value,isDeep,customizer)}function isArguments(value){var length=isObjectLike(value)?value.length:undefined;return isLength(length)&&objToString.call(value)==argsTag}function isEmpty(value){if(null==value)return!0;var length=getLength(value);return isLength(length)&&(isArray(value)||isString(value)||isArguments(value)||isObjectLike(value)&&isFunction(value.splice))?!length:!keys(value).length}function isObject(value){var type=typeof value;return\"function\"==type||!!value&&\"object\"==type}function isNative(value){return null==value?!1:objToString.call(value)==funcTag?reIsNative.test(fnToString.call(value)):isObjectLike(value)&&reIsHostCtor.test(value)}function isNumber(value){return\"number\"==typeof value||isObjectLike(value)&&objToString.call(value)==numberTag}function isString(value){return\"string\"==typeof value||isObjectLike(value)&&objToString.call(value)==stringTag}function isTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[objToString.call(value)]}function toPlainObject(value){return baseCopy(value,keysIn(value))}function has(object,path){if(null==object)return!1;var result=hasOwnProperty.call(object,path);return result||isKey(path)||(path=toPath(path),object=1==path.length?object:baseGet(object,baseSlice(path,0,-1)),path=last(path),result=null!=object&&hasOwnProperty.call(object,path)),result}function keysIn(object){if(null==object)return[];isObject(object)||(object=Object(object));var length=object.length;length=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object))&&length||0;for(var Ctor=object.constructor,index=-1,isProto=\"function\"==typeof Ctor&&Ctor.prototype===object,result=Array(length),skipIndexes=length>0;length>++index;)result[index]=index+\"\";for(var key in object)skipIndexes&&isIndex(key,length)||\"constructor\"==key&&(isProto||!hasOwnProperty.call(object,key))||result.push(key);return result}function values(object){return baseValues(object,keys(object))}function escapeRegExp(string){return string=baseToString(string),string&&reHasRegExpChars.test(string)?string.replace(reRegExpChars,\"\\\\$&\"):string}function callback(func,thisArg,guard){return guard&&isIterateeCall(func,thisArg,guard)&&(thisArg=null),baseCallback(func,thisArg)}function constant(value){return function(){return value}}function identity(value){return value}function property(path){return isKey(path)?baseProperty(path):basePropertyDeep(path)}var undefined,VERSION=\"3.7.0\",FUNC_ERROR_TEXT=\"Expected a function\",argsTag=\"[object Arguments]\",arrayTag=\"[object Array]\",boolTag=\"[object Boolean]\",dateTag=\"[object Date]\",errorTag=\"[object Error]\",funcTag=\"[object Function]\",mapTag=\"[object Map]\",numberTag=\"[object Number]\",objectTag=\"[object Object]\",regexpTag=\"[object RegExp]\",setTag=\"[object Set]\",stringTag=\"[object String]\",weakMapTag=\"[object WeakMap]\",arrayBufferTag=\"[object ArrayBuffer]\",float32Tag=\"[object Float32Array]\",float64Tag=\"[object Float64Array]\",int8Tag=\"[object Int8Array]\",int16Tag=\"[object Int16Array]\",int32Tag=\"[object Int32Array]\",uint8Tag=\"[object Uint8Array]\",uint8ClampedTag=\"[object Uint8ClampedArray]\",uint16Tag=\"[object Uint16Array]\",uint32Tag=\"[object Uint32Array]\",reIsDeepProp=/\\.|\\[(?:[^[\\]]+|([\"'])(?:(?!\\1)[^\\n\\\\]|\\\\.)*?)\\1\\]/,reIsPlainProp=/^\\w*$/,rePropName=/[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\n\\\\]|\\\\.)*?)\\2)\\]/g,reRegExpChars=/[.*+?^${}()|[\\]\\/\\\\]/g,reHasRegExpChars=RegExp(reRegExpChars.source),reEscapeChar=/\\\\(\\\\)?/g,reFlags=/\\w*$/,reIsHostCtor=/^\\[object .+?Constructor\\]$/,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[stringTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[mapTag]=cloneableTags[setTag]=cloneableTags[weakMapTag]=!1;var objectTypes={\"function\":!0,object:!0},freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports,freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module,freeGlobal=freeExports&&freeModule&&\"object\"==typeof global&&global&&global.Object&&global,freeSelf=objectTypes[typeof self]&&self&&self.Object&&self,freeWindow=objectTypes[typeof window]&&window&&window.Object&&window,moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports,root=freeGlobal||freeWindow!==(this&&this.window)&&freeWindow||freeSelf||this,arrayProto=Array.prototype,objectProto=Object.prototype,fnToString=Function.prototype.toString,hasOwnProperty=objectProto.hasOwnProperty,objToString=objectProto.toString,reIsNative=RegExp(\"^\"+escapeRegExp(objToString).replace(/toString|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g,\"$1.*?\")+\"$\"),ArrayBuffer=isNative(ArrayBuffer=root.ArrayBuffer)&&ArrayBuffer,bufferSlice=isNative(bufferSlice=ArrayBuffer&&new ArrayBuffer(0).slice)&&bufferSlice,floor=Math.floor,getOwnPropertySymbols=isNative(getOwnPropertySymbols=Object.getOwnPropertySymbols)&&getOwnPropertySymbols,getPrototypeOf=isNative(getPrototypeOf=Object.getPrototypeOf)&&getPrototypeOf,push=arrayProto.push,preventExtensions=isNative(Object.preventExtensions=Object.preventExtensions)&&preventExtensions,propertyIsEnumerable=objectProto.propertyIsEnumerable,Uint8Array=isNative(Uint8Array=root.Uint8Array)&&Uint8Array,Float64Array=function(){try{var func=isNative(func=root.Float64Array)&&func,result=new func(new ArrayBuffer(10),0,1)&&func}catch(e){}return result}(),nativeAssign=function(){var object={1:0},func=preventExtensions&&isNative(func=Object.assign)&&func;try{func(preventExtensions(object),\"xo\")}catch(e){}return!object[1]&&func}(),nativeIsArray=isNative(nativeIsArray=Array.isArray)&&nativeIsArray,nativeKeys=isNative(nativeKeys=Object.keys)&&nativeKeys,nativeMax=Math.max,nativeMin=Math.min,NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,MAX_ARRAY_LENGTH=Math.pow(2,32)-1,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,FLOAT64_BYTES_PER_ELEMENT=Float64Array?Float64Array.BYTES_PER_ELEMENT:0,MAX_SAFE_INTEGER=Math.pow(2,53)-1,support=lodash.support={};(function(x){var Ctor=function(){this.x=x},props=[];Ctor.prototype={valueOf:x,y:x};for(var key in new Ctor)props.push(key);support.funcDecomp=/\\bthis\\b/.test(function(){return this}),support.funcNames=\"string\"==typeof Function.name;try{support.nonEnumArgs=!propertyIsEnumerable.call(arguments,1)}catch(e){support.nonEnumArgs=!0}})(1,0);var baseAssign=nativeAssign||function(object,source){return null==source?object:baseCopy(source,getSymbols(source),baseCopy(source,keys(source),object))},baseEach=createBaseEach(baseForOwn),baseFor=createBaseFor();bufferSlice||(bufferClone=ArrayBuffer&&Uint8Array?function(buffer){var byteLength=buffer.byteLength,floatLength=Float64Array?floor(byteLength/FLOAT64_BYTES_PER_ELEMENT):0,offset=floatLength*FLOAT64_BYTES_PER_ELEMENT,result=new ArrayBuffer(byteLength);if(floatLength){var view=new Float64Array(result,0,floatLength);view.set(new Float64Array(buffer,0,floatLength))}return byteLength!=offset&&(view=new Uint8Array(result,offset),view.set(new Uint8Array(buffer,offset))),result}:constant(null));var getLength=baseProperty(\"length\"),getSymbols=getOwnPropertySymbols?function(object){return getOwnPropertySymbols(toObject(object))}:constant([]),findLastIndex=createFindIndex(!0),zip=restParam(unzip),forEach=createForEach(arrayEach,baseEach),isArray=nativeIsArray||function(value){return isObjectLike(value)&&isLength(value.length)&&objToString.call(value)==arrayTag},isFunction=baseIsFunction(/x/)||Uint8Array&&!baseIsFunction(Uint8Array)?function(value){return objToString.call(value)==funcTag}:baseIsFunction,isPlainObject=getPrototypeOf?function(value){if(!value||objToString.call(value)!=objectTag)return!1;var valueOf=value.valueOf,objProto=isNative(valueOf)&&(objProto=getPrototypeOf(valueOf))&&getPrototypeOf(objProto);return objProto?value==objProto||getPrototypeOf(value)==objProto:shimIsPlainObject(value)}:shimIsPlainObject,assign=createAssigner(function(object,source,customizer){return customizer?assignWith(object,source,customizer):baseAssign(object,source)}),keys=nativeKeys?function(object){if(object)var Ctor=object.constructor,length=object.length;return\"function\"==typeof Ctor&&Ctor.prototype===object||\"function\"!=typeof object&&isLength(length)?shimKeys(object):isObject(object)?nativeKeys(object):[]}:shimKeys,merge=createAssigner(baseMerge);lodash.assign=assign,lodash.callback=callback,lodash.constant=constant,lodash.forEach=forEach,lodash.keys=keys,lodash.keysIn=keysIn,lodash.merge=merge,lodash.property=property,lodash.reject=reject,lodash.restParam=restParam,lodash.slice=slice,lodash.toPlainObject=toPlainObject,lodash.unzip=unzip,lodash.values=values,lodash.zip=zip,lodash.each=forEach,lodash.extend=assign,lodash.iteratee=callback,lodash.clone=clone,lodash.escapeRegExp=escapeRegExp,lodash.findLastIndex=findLastIndex,lodash.has=has,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isEmpty=isEmpty,lodash.isFunction=isFunction,lodash.isNative=isNative,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isPlainObject=isPlainObject,lodash.isString=isString,lodash.isTypedArray=isTypedArray,lodash.last=last,lodash.some=some,lodash.any=some,lodash.contains=includes,lodash.include=includes,lodash.VERSION=VERSION,freeExports&&freeModule?moduleExports?(freeModule.exports=lodash)._=lodash:freeExports._=lodash:root._=lodash\n}).call(this)}).call(this,\"undefined\"!=typeof global?global:\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{})},{}],\"/node_modules/jshint/src/jshint.js\":[function(_dereq_,module,exports){var _=_dereq_(\"../lodash\"),events=_dereq_(\"events\"),vars=_dereq_(\"./vars.js\"),messages=_dereq_(\"./messages.js\"),Lexer=_dereq_(\"./lex.js\").Lexer,reg=_dereq_(\"./reg.js\"),state=_dereq_(\"./state.js\").state,style=_dereq_(\"./style.js\"),options=_dereq_(\"./options.js\"),scopeManager=_dereq_(\"./scope-manager.js\"),JSHINT=function(){\"use strict\";function checkOption(name,t){return name=name.trim(),/^[+-]W\\d{3}$/g.test(name)?!0:-1!==options.validNames.indexOf(name)||\"jslint\"===t.type||_.has(options.removed,name)?!0:(error(\"E001\",t,name),!1)}function isString(obj){return\"[object String]\"===Object.prototype.toString.call(obj)}function isIdentifier(tkn,value){return tkn?tkn.identifier&&tkn.value===value?!0:!1:!1}function isReserved(token){if(!token.reserved)return!1;var meta=token.meta;if(meta&&meta.isFutureReservedWord&&state.inES5()){if(!meta.es5)return!1;if(meta.strictOnly&&!state.option.strict&&!state.isStrict())return!1;if(token.isProperty)return!1}return!0}function supplant(str,data){return str.replace(/\\{([^{}]*)\\}/g,function(a,b){var r=data[b];return\"string\"==typeof r||\"number\"==typeof r?r:a})}function combine(dest,src){Object.keys(src).forEach(function(name){_.has(JSHINT.blacklist,name)||(dest[name]=src[name])})}function processenforceall(){if(state.option.enforceall){for(var enforceopt in options.bool.enforcing)void 0!==state.option[enforceopt]||options.noenforceall[enforceopt]||(state.option[enforceopt]=!0);for(var relaxopt in options.bool.relaxing)void 0===state.option[relaxopt]&&(state.option[relaxopt]=!1)}}function assume(){processenforceall(),state.option.esversion||state.option.moz||(state.option.esversion=state.option.es3?3:state.option.esnext?6:5),state.inES5()&&combine(predefined,vars.ecmaIdentifiers[5]),state.inES6()&&combine(predefined,vars.ecmaIdentifiers[6]),state.option.module&&(state.option.strict===!0&&(state.option.strict=\"global\"),state.inES6()||warning(\"W134\",state.tokens.next,\"module\",6)),state.option.couch&&combine(predefined,vars.couch),state.option.qunit&&combine(predefined,vars.qunit),state.option.rhino&&combine(predefined,vars.rhino),state.option.shelljs&&(combine(predefined,vars.shelljs),combine(predefined,vars.node)),state.option.typed&&combine(predefined,vars.typed),state.option.phantom&&(combine(predefined,vars.phantom),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.prototypejs&&combine(predefined,vars.prototypejs),state.option.node&&(combine(predefined,vars.node),combine(predefined,vars.typed),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.devel&&combine(predefined,vars.devel),state.option.dojo&&combine(predefined,vars.dojo),state.option.browser&&(combine(predefined,vars.browser),combine(predefined,vars.typed)),state.option.browserify&&(combine(predefined,vars.browser),combine(predefined,vars.typed),combine(predefined,vars.browserify),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.nonstandard&&combine(predefined,vars.nonstandard),state.option.jasmine&&combine(predefined,vars.jasmine),state.option.jquery&&combine(predefined,vars.jquery),state.option.mootools&&combine(predefined,vars.mootools),state.option.worker&&combine(predefined,vars.worker),state.option.wsh&&combine(predefined,vars.wsh),state.option.globalstrict&&state.option.strict!==!1&&(state.option.strict=\"global\"),state.option.yui&&combine(predefined,vars.yui),state.option.mocha&&combine(predefined,vars.mocha)}function quit(code,line,chr){var percentage=Math.floor(100*(line/state.lines.length)),message=messages.errors[code].desc;throw{name:\"JSHintError\",line:line,character:chr,message:message+\" (\"+percentage+\"% scanned).\",raw:message,code:code}}function removeIgnoredMessages(){var ignored=state.ignoredLines;_.isEmpty(ignored)||(JSHINT.errors=_.reject(JSHINT.errors,function(err){return ignored[err.line]}))}function warning(code,t,a,b,c,d){var ch,l,w,msg;if(/^W\\d{3}$/.test(code)){if(state.ignored[code])return;msg=messages.warnings[code]}else/E\\d{3}/.test(code)?msg=messages.errors[code]:/I\\d{3}/.test(code)&&(msg=messages.info[code]);return t=t||state.tokens.next||{},\"(end)\"===t.id&&(t=state.tokens.curr),l=t.line||0,ch=t.from||0,w={id:\"(error)\",raw:msg.desc,code:msg.code,evidence:state.lines[l-1]||\"\",line:l,character:ch,scope:JSHINT.scope,a:a,b:b,c:c,d:d},w.reason=supplant(msg.desc,w),JSHINT.errors.push(w),removeIgnoredMessages(),JSHINT.errors.length>=state.option.maxerr&&quit(\"E043\",l,ch),w}function warningAt(m,l,ch,a,b,c,d){return warning(m,{line:l,from:ch},a,b,c,d)}function error(m,t,a,b,c,d){warning(m,t,a,b,c,d)}function errorAt(m,l,ch,a,b,c,d){return error(m,{line:l,from:ch},a,b,c,d)}function addInternalSrc(elem,src){var i;return i={id:\"(internal)\",elem:elem,value:src},JSHINT.internals.push(i),i}function doOption(){var nt=state.tokens.next,body=nt.body.match(/(-\\s+)?[^\\s,:]+(?:\\s*:\\s*(-\\s+)?[^\\s,]+)?/g)||[],predef={};if(\"globals\"===nt.type){body.forEach(function(g,idx){g=g.split(\":\");var key=(g[0]||\"\").trim(),val=(g[1]||\"\").trim();if(\"-\"===key||!key.length){if(idx>0&&idx===body.length-1)return;return error(\"E002\",nt),void 0}\"-\"===key.charAt(0)?(key=key.slice(1),val=!1,JSHINT.blacklist[key]=key,delete predefined[key]):predef[key]=\"true\"===val}),combine(predefined,predef);for(var key in predef)_.has(predef,key)&&(declared[key]=nt)}\"exported\"===nt.type&&body.forEach(function(e,idx){if(!e.length){if(idx>0&&idx===body.length-1)return;return error(\"E002\",nt),void 0}state.funct[\"(scope)\"].addExported(e)}),\"members\"===nt.type&&(membersOnly=membersOnly||{},body.forEach(function(m){var ch1=m.charAt(0),ch2=m.charAt(m.length-1);ch1!==ch2||'\"'!==ch1&&\"'\"!==ch1||(m=m.substr(1,m.length-2).replace('\\\\\"','\"')),membersOnly[m]=!1}));var numvals=[\"maxstatements\",\"maxparams\",\"maxdepth\",\"maxcomplexity\",\"maxerr\",\"maxlen\",\"indent\"];(\"jshint\"===nt.type||\"jslint\"===nt.type)&&(body.forEach(function(g){g=g.split(\":\");var key=(g[0]||\"\").trim(),val=(g[1]||\"\").trim();if(checkOption(key,nt))if(numvals.indexOf(key)>=0)if(\"false\"!==val){if(val=+val,\"number\"!=typeof val||!isFinite(val)||0>=val||Math.floor(val)!==val)return error(\"E032\",nt,g[1].trim()),void 0;state.option[key]=val}else state.option[key]=\"indent\"===key?4:!1;else{if(\"validthis\"===key)return state.funct[\"(global)\"]?void error(\"E009\"):\"true\"!==val&&\"false\"!==val?void error(\"E002\",nt):(state.option.validthis=\"true\"===val,void 0);if(\"quotmark\"!==key)if(\"shadow\"!==key)if(\"unused\"!==key)if(\"latedef\"!==key)if(\"ignore\"!==key)if(\"strict\"!==key){\"module\"===key&&(hasParsedCode(state.funct)||error(\"E055\",state.tokens.next,\"module\"));var esversions={es3:3,es5:5,esnext:6};if(!_.has(esversions,key)){if(\"esversion\"===key){switch(val){case\"5\":state.inES5(!0)&&warning(\"I003\");case\"3\":case\"6\":state.option.moz=!1,state.option.esversion=+val;break;case\"2015\":state.option.moz=!1,state.option.esversion=6;break;default:error(\"E002\",nt)}return hasParsedCode(state.funct)||error(\"E055\",state.tokens.next,\"esversion\"),void 0}var match=/^([+-])(W\\d{3})$/g.exec(key);if(match)return state.ignored[match[2]]=\"-\"===match[1],void 0;var tn;return\"true\"===val||\"false\"===val?(\"jslint\"===nt.type?(tn=options.renamed[key]||key,state.option[tn]=\"true\"===val,void 0!==options.inverted[tn]&&(state.option[tn]=!state.option[tn])):state.option[key]=\"true\"===val,\"newcap\"===key&&(state.option[\"(explicitNewcap)\"]=!0),void 0):(error(\"E002\",nt),void 0)}switch(val){case\"true\":state.option.moz=!1,state.option.esversion=esversions[key];break;case\"false\":state.option.moz||(state.option.esversion=5);break;default:error(\"E002\",nt)}}else switch(val){case\"true\":state.option.strict=!0;break;case\"false\":state.option.strict=!1;break;case\"func\":case\"global\":case\"implied\":state.option.strict=val;break;default:error(\"E002\",nt)}else switch(val){case\"line\":state.ignoredLines[nt.line]=!0,removeIgnoredMessages();break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.latedef=!0;break;case\"false\":state.option.latedef=!1;break;case\"nofunc\":state.option.latedef=\"nofunc\";break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.unused=!0;break;case\"false\":state.option.unused=!1;break;case\"vars\":case\"strict\":state.option.unused=val;break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.shadow=!0;break;case\"outer\":state.option.shadow=\"outer\";break;case\"false\":case\"inner\":state.option.shadow=\"inner\";break;default:error(\"E002\",nt)}else switch(val){case\"true\":case\"false\":state.option.quotmark=\"true\"===val;break;case\"double\":case\"single\":state.option.quotmark=val;break;default:error(\"E002\",nt)}}}),assume())}function peek(p){var t,i=p||0,j=lookahead.length;if(j>i)return lookahead[i];for(;i>=j;)t=lookahead[j],t||(t=lookahead[j]=lex.token()),j+=1;return t||\"(end)\"!==state.tokens.next.id?t:state.tokens.next}function peekIgnoreEOL(){var t,i=0;do t=peek(i++);while(\"(endline)\"===t.id);return t}function advance(id,t){switch(state.tokens.curr.id){case\"(number)\":\".\"===state.tokens.next.id&&warning(\"W005\",state.tokens.curr);break;case\"-\":(\"-\"===state.tokens.next.id||\"--\"===state.tokens.next.id)&&warning(\"W006\");break;case\"+\":(\"+\"===state.tokens.next.id||\"++\"===state.tokens.next.id)&&warning(\"W007\")}for(id&&state.tokens.next.id!==id&&(t?\"(end)\"===state.tokens.next.id?error(\"E019\",t,t.id):error(\"E020\",state.tokens.next,id,t.id,t.line,state.tokens.next.value):(\"(identifier)\"!==state.tokens.next.type||state.tokens.next.value!==id)&&warning(\"W116\",state.tokens.next,id,state.tokens.next.value)),state.tokens.prev=state.tokens.curr,state.tokens.curr=state.tokens.next;;){if(state.tokens.next=lookahead.shift()||lex.token(),state.tokens.next||quit(\"E041\",state.tokens.curr.line),\"(end)\"===state.tokens.next.id||\"(error)\"===state.tokens.next.id)return;if(state.tokens.next.check&&state.tokens.next.check(),state.tokens.next.isSpecial)\"falls through\"===state.tokens.next.type?state.tokens.curr.caseFallsThrough=!0:doOption();else if(\"(endline)\"!==state.tokens.next.id)break}}function isInfix(token){return token.infix||!token.identifier&&!token.template&&!!token.led}function isEndOfExpr(){var curr=state.tokens.curr,next=state.tokens.next;return\";\"===next.id||\"}\"===next.id||\":\"===next.id?!0:isInfix(next)===isInfix(curr)||\"yield\"===curr.id&&state.inMoz()?curr.line!==startLine(next):!1}function isBeginOfExpr(prev){return!prev.left&&\"unary\"!==prev.arity}function expression(rbp,initial){var left,isArray=!1,isObject=!1,isLetExpr=!1;state.nameStack.push(),initial||\"let\"!==state.tokens.next.value||\"(\"!==peek(0).value||(state.inMoz()||warning(\"W118\",state.tokens.next,\"let expressions\"),isLetExpr=!0,state.funct[\"(scope)\"].stack(),advance(\"let\"),advance(\"(\"),state.tokens.prev.fud(),advance(\")\")),\"(end)\"===state.tokens.next.id&&error(\"E006\",state.tokens.curr);var isDangerous=state.option.asi&&state.tokens.prev.line!==startLine(state.tokens.curr)&&_.contains([\"]\",\")\"],state.tokens.prev.id)&&_.contains([\"[\",\"(\"],state.tokens.curr.id);if(isDangerous&&warning(\"W014\",state.tokens.curr,state.tokens.curr.id),advance(),initial&&(state.funct[\"(verb)\"]=state.tokens.curr.value,state.tokens.curr.beginsStmt=!0),initial===!0&&state.tokens.curr.fud)left=state.tokens.curr.fud();else for(state.tokens.curr.nud?left=state.tokens.curr.nud():error(\"E030\",state.tokens.curr,state.tokens.curr.id);(state.tokens.next.lbp>rbp||\"(template)\"===state.tokens.next.type)&&!isEndOfExpr();)isArray=\"Array\"===state.tokens.curr.value,isObject=\"Object\"===state.tokens.curr.value,left&&(left.value||left.first&&left.first.value)&&(\"new\"!==left.value||left.first&&left.first.value&&\".\"===left.first.value)&&(isArray=!1,left.value!==state.tokens.curr.value&&(isObject=!1)),advance(),isArray&&\"(\"===state.tokens.curr.id&&\")\"===state.tokens.next.id&&warning(\"W009\",state.tokens.curr),isObject&&\"(\"===state.tokens.curr.id&&\")\"===state.tokens.next.id&&warning(\"W010\",state.tokens.curr),left&&state.tokens.curr.led?left=state.tokens.curr.led(left):error(\"E033\",state.tokens.curr,state.tokens.curr.id);return isLetExpr&&state.funct[\"(scope)\"].unstack(),state.nameStack.pop(),left}function startLine(token){return token.startLine||token.line}function nobreaknonadjacent(left,right){left=left||state.tokens.curr,right=right||state.tokens.next,state.option.laxbreak||left.line===startLine(right)||warning(\"W014\",right,right.value)}function nolinebreak(t){t=t||state.tokens.curr,t.line!==startLine(state.tokens.next)&&warning(\"E022\",t,t.value)}function nobreakcomma(left,right){left.line!==startLine(right)&&(state.option.laxcomma||(comma.first&&(warning(\"I001\"),comma.first=!1),warning(\"W014\",left,right.value)))}function comma(opts){if(opts=opts||{},opts.peek?nobreakcomma(state.tokens.prev,state.tokens.curr):(nobreakcomma(state.tokens.curr,state.tokens.next),advance(\",\")),state.tokens.next.identifier&&(!opts.property||!state.inES5()))switch(state.tokens.next.value){case\"break\":case\"case\":case\"catch\":case\"continue\":case\"default\":case\"do\":case\"else\":case\"finally\":case\"for\":case\"if\":case\"in\":case\"instanceof\":case\"return\":case\"switch\":case\"throw\":case\"try\":case\"var\":case\"let\":case\"while\":case\"with\":return error(\"E024\",state.tokens.next,state.tokens.next.value),!1}if(\"(punctuator)\"===state.tokens.next.type)switch(state.tokens.next.value){case\"}\":case\"]\":case\",\":if(opts.allowTrailing)return!0;case\")\":return error(\"E024\",state.tokens.next,state.tokens.next.value),!1}return!0}function symbol(s,p){var x=state.syntax[s];return x&&\"object\"==typeof x||(state.syntax[s]=x={id:s,lbp:p,value:s}),x}function delim(s){var x=symbol(s,0);return x.delim=!0,x}function stmt(s,f){var x=delim(s);return x.identifier=x.reserved=!0,x.fud=f,x}function blockstmt(s,f){var x=stmt(s,f);return x.block=!0,x}function reserveName(x){var c=x.id.charAt(0);return(c>=\"a\"&&\"z\">=c||c>=\"A\"&&\"Z\">=c)&&(x.identifier=x.reserved=!0),x}function prefix(s,f){var x=symbol(s,150);return reserveName(x),x.nud=\"function\"==typeof f?f:function(){return this.arity=\"unary\",this.right=expression(150),(\"++\"===this.id||\"--\"===this.id)&&(state.option.plusplus?warning(\"W016\",this,this.id):!this.right||this.right.identifier&&!isReserved(this.right)||\".\"===this.right.id||\"[\"===this.right.id||warning(\"W017\",this),this.right&&this.right.isMetaProperty?error(\"E031\",this):this.right&&this.right.identifier&&state.funct[\"(scope)\"].block.modify(this.right.value,this)),this},x}function type(s,f){var x=delim(s);return x.type=s,x.nud=f,x}function reserve(name,func){var x=type(name,func);return x.identifier=!0,x.reserved=!0,x}function FutureReservedWord(name,meta){var x=type(name,meta&&meta.nud||function(){return this});return meta=meta||{},meta.isFutureReservedWord=!0,x.value=name,x.identifier=!0,x.reserved=!0,x.meta=meta,x}function reservevar(s,v){return reserve(s,function(){return\"function\"==typeof v&&v(this),this})}function infix(s,f,p,w){var x=symbol(s,p);return reserveName(x),x.infix=!0,x.led=function(left){return w||nobreaknonadjacent(state.tokens.prev,state.tokens.curr),\"in\"!==s&&\"instanceof\"!==s||\"!\"!==left.id||warning(\"W018\",left,\"!\"),\"function\"==typeof f?f(left,this):(this.left=left,this.right=expression(p),this)},x}function application(s){var x=symbol(s,42);return x.led=function(left){return nobreaknonadjacent(state.tokens.prev,state.tokens.curr),this.left=left,this.right=doFunction({type:\"arrow\",loneArg:left}),this},x}function relation(s,f){var x=symbol(s,100);return x.led=function(left){nobreaknonadjacent(state.tokens.prev,state.tokens.curr),this.left=left;var right=this.right=expression(100);return isIdentifier(left,\"NaN\")||isIdentifier(right,\"NaN\")?warning(\"W019\",this):f&&f.apply(this,[left,right]),left&&right||quit(\"E041\",state.tokens.curr.line),\"!\"===left.id&&warning(\"W018\",left,\"!\"),\"!\"===right.id&&warning(\"W018\",right,\"!\"),this},x}function isPoorRelation(node){return node&&(\"(number)\"===node.type&&0===+node.value||\"(string)\"===node.type&&\"\"===node.value||\"null\"===node.type&&!state.option.eqnull||\"true\"===node.type||\"false\"===node.type||\"undefined\"===node.type)}function isTypoTypeof(left,right,state){var values;return state.option.notypeof?!1:left&&right?(values=state.inES6()?typeofValues.es6:typeofValues.es3,\"(identifier)\"===right.type&&\"typeof\"===right.value&&\"(string)\"===left.type?!_.contains(values,left.value):!1):!1}function isGlobalEval(left,state){var isGlobal=!1;return\"this\"===left.type&&null===state.funct[\"(context)\"]?isGlobal=!0:\"(identifier)\"===left.type&&(state.option.node&&\"global\"===left.value?isGlobal=!0:!state.option.browser||\"window\"!==left.value&&\"document\"!==left.value||(isGlobal=!0)),isGlobal}function findNativePrototype(left){function walkPrototype(obj){return\"object\"==typeof obj?\"prototype\"===obj.right?obj:walkPrototype(obj.left):void 0}function walkNative(obj){for(;!obj.identifier&&\"object\"==typeof obj.left;)obj=obj.left;return obj.identifier&&natives.indexOf(obj.value)>=0?obj.value:void 0}var natives=[\"Array\",\"ArrayBuffer\",\"Boolean\",\"Collator\",\"DataView\",\"Date\",\"DateTimeFormat\",\"Error\",\"EvalError\",\"Float32Array\",\"Float64Array\",\"Function\",\"Infinity\",\"Intl\",\"Int16Array\",\"Int32Array\",\"Int8Array\",\"Iterator\",\"Number\",\"NumberFormat\",\"Object\",\"RangeError\",\"ReferenceError\",\"RegExp\",\"StopIteration\",\"String\",\"SyntaxError\",\"TypeError\",\"Uint16Array\",\"Uint32Array\",\"Uint8Array\",\"Uint8ClampedArray\",\"URIError\"],prototype=walkPrototype(left);return prototype?walkNative(prototype):void 0}function checkLeftSideAssign(left,assignToken,options){var allowDestructuring=options&&options.allowDestructuring;if(assignToken=assignToken||left,state.option.freeze){var nativeObject=findNativePrototype(left);nativeObject&&warning(\"W121\",left,nativeObject)}return left.identifier&&!left.isMetaProperty&&state.funct[\"(scope)\"].block.reassign(left.value,left),\".\"===left.id?((!left.left||\"arguments\"===left.left.value&&!state.isStrict())&&warning(\"E031\",assignToken),state.nameStack.set(state.tokens.prev),!0):\"{\"===left.id||\"[\"===left.id?(allowDestructuring&&state.tokens.curr.left.destructAssign?state.tokens.curr.left.destructAssign.forEach(function(t){t.id&&state.funct[\"(scope)\"].block.modify(t.id,t.token)}):\"{\"!==left.id&&left.left?\"arguments\"!==left.left.value||state.isStrict()||warning(\"E031\",assignToken):warning(\"E031\",assignToken),\"[\"===left.id&&state.nameStack.set(left.right),!0):left.isMetaProperty?(error(\"E031\",assignToken),!0):left.identifier&&!isReserved(left)?(\"exception\"===state.funct[\"(scope)\"].labeltype(left.value)&&warning(\"W022\",left),state.nameStack.set(left),!0):(left===state.syntax[\"function\"]&&warning(\"W023\",state.tokens.curr),!1)}function assignop(s,f,p){var x=infix(s,\"function\"==typeof f?f:function(left,that){return that.left=left,left&&checkLeftSideAssign(left,that,{allowDestructuring:!0})?(that.right=expression(10),that):(error(\"E031\",that),void 0)},p);return x.exps=!0,x.assign=!0,x}function bitwise(s,f,p){var x=symbol(s,p);return reserveName(x),x.led=\"function\"==typeof f?f:function(left){return state.option.bitwise&&warning(\"W016\",this,this.id),this.left=left,this.right=expression(p),this},x}function bitwiseassignop(s){return assignop(s,function(left,that){return state.option.bitwise&&warning(\"W016\",that,that.id),left&&checkLeftSideAssign(left,that)?(that.right=expression(10),that):(error(\"E031\",that),void 0)},20)}function suffix(s){var x=symbol(s,150);return x.led=function(left){return state.option.plusplus?warning(\"W016\",this,this.id):left.identifier&&!isReserved(left)||\".\"===left.id||\"[\"===left.id||warning(\"W017\",this),left.isMetaProperty?error(\"E031\",this):left&&left.identifier&&state.funct[\"(scope)\"].block.modify(left.value,left),this.left=left,this},x}function optionalidentifier(fnparam,prop,preserve){if(state.tokens.next.identifier){preserve||advance();var curr=state.tokens.curr,val=state.tokens.curr.value;return isReserved(curr)?prop&&state.inES5()?val:fnparam&&\"undefined\"===val?val:(warning(\"W024\",state.tokens.curr,state.tokens.curr.id),val):val}}function identifier(fnparam,prop){var i=optionalidentifier(fnparam,prop,!1);if(i)return i;if(\"...\"===state.tokens.next.value){if(state.inES6(!0)||warning(\"W119\",state.tokens.next,\"spread/rest operator\",\"6\"),advance(),checkPunctuator(state.tokens.next,\"...\"))for(warning(\"E024\",state.tokens.next,\"...\");checkPunctuator(state.tokens.next,\"...\");)advance();return state.tokens.next.identifier?identifier(fnparam,prop):(warning(\"E024\",state.tokens.curr,\"...\"),void 0)}error(\"E030\",state.tokens.next,state.tokens.next.value),\";\"!==state.tokens.next.id&&advance()}function reachable(controlToken){var t,i=0;if(\";\"===state.tokens.next.id&&!controlToken.inBracelessBlock)for(;;){do t=peek(i),i+=1;while(\"(end)\"!==t.id&&\"(comment)\"===t.id);if(t.reach)return;if(\"(endline)\"!==t.id){if(\"function\"===t.id){state.option.latedef===!0&&warning(\"W026\",t);break}warning(\"W027\",t,t.value,controlToken.value);break}}}function parseFinalSemicolon(){if(\";\"!==state.tokens.next.id){if(state.tokens.next.isUnclosed)return advance();var sameLine=startLine(state.tokens.next)===state.tokens.curr.line&&\"(end)\"!==state.tokens.next.id,blockEnd=checkPunctuator(state.tokens.next,\"}\");sameLine&&!blockEnd?errorAt(\"E058\",state.tokens.curr.line,state.tokens.curr.character):state.option.asi||(blockEnd&&!state.option.lastsemic||!sameLine)&&warningAt(\"W033\",state.tokens.curr.line,state.tokens.curr.character)}else advance(\";\")}function statement(){var r,i=indent,t=state.tokens.next,hasOwnScope=!1;if(\";\"===t.id)return advance(\";\"),void 0;var res=isReserved(t);if(res&&t.meta&&t.meta.isFutureReservedWord&&\":\"===peek().id&&(warning(\"W024\",t,t.id),res=!1),t.identifier&&!res&&\":\"===peek().id&&(advance(),advance(\":\"),hasOwnScope=!0,state.funct[\"(scope)\"].stack(),state.funct[\"(scope)\"].block.addBreakLabel(t.value,{token:state.tokens.curr}),state.tokens.next.labelled||\"{\"===state.tokens.next.value||warning(\"W028\",state.tokens.next,t.value,state.tokens.next.value),state.tokens.next.label=t.value,t=state.tokens.next),\"{\"===t.id){var iscase=\"case\"===state.funct[\"(verb)\"]&&\":\"===state.tokens.curr.value;return block(!0,!0,!1,!1,iscase),void 0}return r=expression(0,!0),!r||r.identifier&&\"function\"===r.value||\"(punctuator)\"===r.type&&r.left&&r.left.identifier&&\"function\"===r.left.value||state.isStrict()||\"global\"!==state.option.strict||warning(\"E007\"),t.block||(state.option.expr||r&&r.exps?state.option.nonew&&r&&r.left&&\"(\"===r.id&&\"new\"===r.left.id&&warning(\"W031\",t):warning(\"W030\",state.tokens.curr),parseFinalSemicolon()),indent=i,hasOwnScope&&state.funct[\"(scope)\"].unstack(),r}function statements(){for(var p,a=[];!state.tokens.next.reach&&\"(end)\"!==state.tokens.next.id;)\";\"===state.tokens.next.id?(p=peek(),(!p||\"(\"!==p.id&&\"[\"!==p.id)&&warning(\"W032\"),advance(\";\")):a.push(statement());return a}function directives(){for(var i,p,pn;\"(string)\"===state.tokens.next.id;){if(p=peek(0),\"(endline)\"===p.id){i=1;do pn=peek(i++);while(\"(endline)\"===pn.id);if(\";\"===pn.id)p=pn;else{if(\"[\"===pn.value||\".\"===pn.value)break;state.option.asi&&\"(\"!==pn.value||warning(\"W033\",state.tokens.next)}}else{if(\".\"===p.id||\"[\"===p.id)break;\";\"!==p.id&&warning(\"W033\",p)}advance();var directive=state.tokens.curr.value;(state.directive[directive]||\"use strict\"===directive&&\"implied\"===state.option.strict)&&warning(\"W034\",state.tokens.curr,directive),state.directive[directive]=!0,\";\"===p.id&&advance(\";\")}state.isStrict()&&(state.option[\"(explicitNewcap)\"]||(state.option.newcap=!0),state.option.undef=!0)}function block(ordinary,stmt,isfunc,isfatarrow,iscase){var a,m,t,line,d,b=inblock,old_indent=indent;inblock=ordinary,t=state.tokens.next;var metrics=state.funct[\"(metrics)\"];if(metrics.nestedBlockDepth+=1,metrics.verifyMaxNestedBlockDepthPerFunction(),\"{\"===state.tokens.next.id){if(advance(\"{\"),state.funct[\"(scope)\"].stack(),line=state.tokens.curr.line,\"}\"!==state.tokens.next.id){for(indent+=state.option.indent;!ordinary&&state.tokens.next.from>indent;)indent+=state.option.indent;if(isfunc){m={};for(d in state.directive)_.has(state.directive,d)&&(m[d]=state.directive[d]);directives(),state.option.strict&&state.funct[\"(context)\"][\"(global)\"]&&(m[\"use strict\"]||state.isStrict()||warning(\"E007\"))}a=statements(),metrics.statementCount+=a.length,indent-=state.option.indent}advance(\"}\",t),isfunc&&(state.funct[\"(scope)\"].validateParams(),m&&(state.directive=m)),state.funct[\"(scope)\"].unstack(),indent=old_indent}else if(ordinary)state.funct[\"(noblockscopedvar)\"]=\"for\"!==state.tokens.next.id,state.funct[\"(scope)\"].stack(),(!stmt||state.option.curly)&&warning(\"W116\",state.tokens.next,\"{\",state.tokens.next.value),state.tokens.next.inBracelessBlock=!0,indent+=state.option.indent,a=[statement()],indent-=state.option.indent,state.funct[\"(scope)\"].unstack(),delete state.funct[\"(noblockscopedvar)\"];else if(isfunc){if(state.funct[\"(scope)\"].stack(),m={},!stmt||isfatarrow||state.inMoz()||error(\"W118\",state.tokens.curr,\"function closure expressions\"),!stmt)for(d in state.directive)_.has(state.directive,d)&&(m[d]=state.directive[d]);expression(10),state.option.strict&&state.funct[\"(context)\"][\"(global)\"]&&(m[\"use strict\"]||state.isStrict()||warning(\"E007\")),state.funct[\"(scope)\"].unstack()}else error(\"E021\",state.tokens.next,\"{\",state.tokens.next.value);switch(state.funct[\"(verb)\"]){case\"break\":case\"continue\":case\"return\":case\"throw\":if(iscase)break;default:state.funct[\"(verb)\"]=null}return inblock=b,!ordinary||!state.option.noempty||a&&0!==a.length||warning(\"W035\",state.tokens.prev),metrics.nestedBlockDepth-=1,a}function countMember(m){membersOnly&&\"boolean\"!=typeof membersOnly[m]&&warning(\"W036\",state.tokens.curr,m),\"number\"==typeof member[m]?member[m]+=1:member[m]=1}function comprehensiveArrayExpression(){var res={};res.exps=!0,state.funct[\"(comparray)\"].stack();var reversed=!1;return\"for\"!==state.tokens.next.value&&(reversed=!0,state.inMoz()||warning(\"W116\",state.tokens.next,\"for\",state.tokens.next.value),state.funct[\"(comparray)\"].setState(\"use\"),res.right=expression(10)),advance(\"for\"),\"each\"===state.tokens.next.value&&(advance(\"each\"),state.inMoz()||warning(\"W118\",state.tokens.curr,\"for each\")),advance(\"(\"),state.funct[\"(comparray)\"].setState(\"define\"),res.left=expression(130),_.contains([\"in\",\"of\"],state.tokens.next.value)?advance():error(\"E045\",state.tokens.curr),state.funct[\"(comparray)\"].setState(\"generate\"),expression(10),advance(\")\"),\"if\"===state.tokens.next.value&&(advance(\"if\"),advance(\"(\"),state.funct[\"(comparray)\"].setState(\"filter\"),res.filter=expression(10),advance(\")\")),reversed||(state.funct[\"(comparray)\"].setState(\"use\"),res.right=expression(10)),advance(\"]\"),state.funct[\"(comparray)\"].unstack(),res}function isMethod(){return state.funct[\"(statement)\"]&&\"class\"===state.funct[\"(statement)\"].type||state.funct[\"(context)\"]&&\"class\"===state.funct[\"(context)\"][\"(verb)\"]}function isPropertyName(token){return token.identifier||\"(string)\"===token.id||\"(number)\"===token.id}function propertyName(preserveOrToken){var id,preserve=!0;return\"object\"==typeof preserveOrToken?id=preserveOrToken:(preserve=preserveOrToken,id=optionalidentifier(!1,!0,preserve)),id?\"object\"==typeof id&&(\"(string)\"===id.id||\"(identifier)\"===id.id?id=id.value:\"(number)\"===id.id&&(id=\"\"+id.value)):\"(string)\"===state.tokens.next.id?(id=state.tokens.next.value,preserve||advance()):\"(number)\"===state.tokens.next.id&&(id=\"\"+state.tokens.next.value,preserve||advance()),\"hasOwnProperty\"===id&&warning(\"W001\"),id}function functionparams(options){function addParam(addParamArgs){state.funct[\"(scope)\"].addParam.apply(state.funct[\"(scope)\"],addParamArgs)}var next,ident,t,paramsIds=[],tokens=[],pastDefault=!1,pastRest=!1,arity=0,loneArg=options&&options.loneArg;if(loneArg&&loneArg.identifier===!0)return state.funct[\"(scope)\"].addParam(loneArg.value,loneArg),{arity:1,params:[loneArg.value]};if(next=state.tokens.next,options&&options.parsedOpening||advance(\"(\"),\")\"===state.tokens.next.id)return advance(\")\"),void 0;for(;;){arity++;var currentParams=[];if(_.contains([\"{\",\"[\"],state.tokens.next.id)){tokens=destructuringPattern();for(t in tokens)t=tokens[t],t.id&&(paramsIds.push(t.id),currentParams.push([t.id,t.token]))}else if(checkPunctuator(state.tokens.next,\"...\")&&(pastRest=!0),ident=identifier(!0))paramsIds.push(ident),currentParams.push([ident,state.tokens.curr]);else for(;!checkPunctuators(state.tokens.next,[\",\",\")\"]);)advance();if(pastDefault&&\"=\"!==state.tokens.next.id&&error(\"W138\",state.tokens.current),\"=\"===state.tokens.next.id&&(state.inES6()||warning(\"W119\",state.tokens.next,\"default parameters\",\"6\"),advance(\"=\"),pastDefault=!0,expression(10)),currentParams.forEach(addParam),\",\"!==state.tokens.next.id)return advance(\")\",next),{arity:arity,params:paramsIds};pastRest&&warning(\"W131\",state.tokens.next),comma()}}function functor(name,token,overwrites){var funct={\"(name)\":name,\"(breakage)\":0,\"(loopage)\":0,\"(tokens)\":{},\"(properties)\":{},\"(catch)\":!1,\"(global)\":!1,\"(line)\":null,\"(character)\":null,\"(metrics)\":null,\"(statement)\":null,\"(context)\":null,\"(scope)\":null,\"(comparray)\":null,\"(generator)\":null,\"(arrow)\":null,\"(params)\":null};return token&&_.extend(funct,{\"(line)\":token.line,\"(character)\":token.character,\"(metrics)\":createMetrics(token)}),_.extend(funct,overwrites),funct[\"(context)\"]&&(funct[\"(scope)\"]=funct[\"(context)\"][\"(scope)\"],funct[\"(comparray)\"]=funct[\"(context)\"][\"(comparray)\"]),funct}function isFunctor(token){return\"(scope)\"in token}function hasParsedCode(funct){return funct[\"(global)\"]&&!funct[\"(verb)\"]}function doTemplateLiteral(left){function end(){if(state.tokens.curr.template&&state.tokens.curr.tail&&state.tokens.curr.context===ctx)return!0;var complete=state.tokens.next.template&&state.tokens.next.tail&&state.tokens.next.context===ctx;return complete&&advance(),complete||state.tokens.next.isUnclosed}var ctx=this.context,noSubst=this.noSubst,depth=this.depth;if(!noSubst)for(;!end();)!state.tokens.next.template||state.tokens.next.depth>depth?expression(0):advance();return{id:\"(template)\",type:\"(template)\",tag:left}}function doFunction(options){var f,token,name,statement,classExprBinding,isGenerator,isArrow,ignoreLoopFunc,oldOption=state.option,oldIgnored=state.ignored;options&&(name=options.name,statement=options.statement,classExprBinding=options.classExprBinding,isGenerator=\"generator\"===options.type,isArrow=\"arrow\"===options.type,ignoreLoopFunc=options.ignoreLoopFunc),state.option=Object.create(state.option),state.ignored=Object.create(state.ignored),state.funct=functor(name||state.nameStack.infer(),state.tokens.next,{\"(statement)\":statement,\"(context)\":state.funct,\"(arrow)\":isArrow,\"(generator)\":isGenerator}),f=state.funct,token=state.tokens.curr,token.funct=state.funct,functions.push(state.funct),state.funct[\"(scope)\"].stack(\"functionouter\");var internallyAccessibleName=name||classExprBinding;internallyAccessibleName&&state.funct[\"(scope)\"].block.add(internallyAccessibleName,classExprBinding?\"class\":\"function\",state.tokens.curr,!1),state.funct[\"(scope)\"].stack(\"functionparams\");var paramsInfo=functionparams(options);return paramsInfo?(state.funct[\"(params)\"]=paramsInfo.params,state.funct[\"(metrics)\"].arity=paramsInfo.arity,state.funct[\"(metrics)\"].verifyMaxParametersPerFunction()):state.funct[\"(metrics)\"].arity=0,isArrow&&(state.inES6(!0)||warning(\"W119\",state.tokens.curr,\"arrow function syntax (=>)\",\"6\"),options.loneArg||advance(\"=>\")),block(!1,!0,!0,isArrow),!state.option.noyield&&isGenerator&&\"yielded\"!==state.funct[\"(generator)\"]&&warning(\"W124\",state.tokens.curr),state.funct[\"(metrics)\"].verifyMaxStatementsPerFunction(),state.funct[\"(metrics)\"].verifyMaxComplexityPerFunction(),state.funct[\"(unusedOption)\"]=state.option.unused,state.option=oldOption,state.ignored=oldIgnored,state.funct[\"(last)\"]=state.tokens.curr.line,state.funct[\"(lastcharacter)\"]=state.tokens.curr.character,state.funct[\"(scope)\"].unstack(),state.funct[\"(scope)\"].unstack(),state.funct=state.funct[\"(context)\"],ignoreLoopFunc||state.option.loopfunc||!state.funct[\"(loopage)\"]||f[\"(isCapturing)\"]&&warning(\"W083\",token),f}function createMetrics(functionStartToken){return{statementCount:0,nestedBlockDepth:-1,ComplexityCount:1,arity:0,verifyMaxStatementsPerFunction:function(){state.option.maxstatements&&this.statementCount>state.option.maxstatements&&warning(\"W071\",functionStartToken,this.statementCount)\n},verifyMaxParametersPerFunction:function(){_.isNumber(state.option.maxparams)&&this.arity>state.option.maxparams&&warning(\"W072\",functionStartToken,this.arity)},verifyMaxNestedBlockDepthPerFunction:function(){state.option.maxdepth&&this.nestedBlockDepth>0&&this.nestedBlockDepth===state.option.maxdepth+1&&warning(\"W073\",null,this.nestedBlockDepth)},verifyMaxComplexityPerFunction:function(){var max=state.option.maxcomplexity,cc=this.ComplexityCount;max&&cc>max&&warning(\"W074\",functionStartToken,cc)}}}function increaseComplexityCount(){state.funct[\"(metrics)\"].ComplexityCount+=1}function checkCondAssignment(expr){var id,paren;switch(expr&&(id=expr.id,paren=expr.paren,\",\"===id&&(expr=expr.exprs[expr.exprs.length-1])&&(id=expr.id,paren=paren||expr.paren)),id){case\"=\":case\"+=\":case\"-=\":case\"*=\":case\"%=\":case\"&=\":case\"|=\":case\"^=\":case\"/=\":paren||state.option.boss||warning(\"W084\")}}function checkProperties(props){if(state.inES5())for(var name in props)props[name]&&props[name].setterToken&&!props[name].getterToken&&warning(\"W078\",props[name].setterToken)}function metaProperty(name,c){if(checkPunctuator(state.tokens.next,\".\")){var left=state.tokens.curr.id;advance(\".\");var id=identifier();return state.tokens.curr.isMetaProperty=!0,name!==id?error(\"E057\",state.tokens.prev,left,id):c(),state.tokens.curr}}function destructuringPattern(options){var isAssignment=options&&options.assignment;return state.inES6()||warning(\"W104\",state.tokens.curr,isAssignment?\"destructuring assignment\":\"destructuring binding\",\"6\"),destructuringPatternRecursive(options)}function destructuringPatternRecursive(options){var ids,identifiers=[],openingParsed=options&&options.openingParsed,isAssignment=options&&options.assignment,recursiveOptions=isAssignment?{assignment:isAssignment}:null,firstToken=openingParsed?state.tokens.curr:state.tokens.next,nextInnerDE=function(){var ident;if(checkPunctuators(state.tokens.next,[\"[\",\"{\"])){ids=destructuringPatternRecursive(recursiveOptions);for(var id in ids)id=ids[id],identifiers.push({id:id.id,token:id.token})}else if(checkPunctuator(state.tokens.next,\",\"))identifiers.push({id:null,token:state.tokens.curr});else{if(!checkPunctuator(state.tokens.next,\"(\")){var is_rest=checkPunctuator(state.tokens.next,\"...\");if(isAssignment){var identifierToken=is_rest?peek(0):state.tokens.next;identifierToken.identifier||warning(\"E030\",identifierToken,identifierToken.value);var assignTarget=expression(155);assignTarget&&(checkLeftSideAssign(assignTarget),assignTarget.identifier&&(ident=assignTarget.value))}else ident=identifier();return ident&&identifiers.push({id:ident,token:state.tokens.curr}),is_rest}advance(\"(\"),nextInnerDE(),advance(\")\")}return!1},assignmentProperty=function(){var id;checkPunctuator(state.tokens.next,\"[\")?(advance(\"[\"),expression(10),advance(\"]\"),advance(\":\"),nextInnerDE()):\"(string)\"===state.tokens.next.id||\"(number)\"===state.tokens.next.id?(advance(),advance(\":\"),nextInnerDE()):(id=identifier(),checkPunctuator(state.tokens.next,\":\")?(advance(\":\"),nextInnerDE()):id&&(isAssignment&&checkLeftSideAssign(state.tokens.curr),identifiers.push({id:id,token:state.tokens.curr})))};if(checkPunctuator(firstToken,\"[\")){openingParsed||advance(\"[\"),checkPunctuator(state.tokens.next,\"]\")&&warning(\"W137\",state.tokens.curr);for(var element_after_rest=!1;!checkPunctuator(state.tokens.next,\"]\");)nextInnerDE()&&!element_after_rest&&checkPunctuator(state.tokens.next,\",\")&&(warning(\"W130\",state.tokens.next),element_after_rest=!0),checkPunctuator(state.tokens.next,\"=\")&&(checkPunctuator(state.tokens.prev,\"...\")?advance(\"]\"):advance(\"=\"),\"undefined\"===state.tokens.next.id&&warning(\"W080\",state.tokens.prev,state.tokens.prev.value),expression(10)),checkPunctuator(state.tokens.next,\"]\")||advance(\",\");advance(\"]\")}else if(checkPunctuator(firstToken,\"{\")){for(openingParsed||advance(\"{\"),checkPunctuator(state.tokens.next,\"}\")&&warning(\"W137\",state.tokens.curr);!checkPunctuator(state.tokens.next,\"}\")&&(assignmentProperty(),checkPunctuator(state.tokens.next,\"=\")&&(advance(\"=\"),\"undefined\"===state.tokens.next.id&&warning(\"W080\",state.tokens.prev,state.tokens.prev.value),expression(10)),checkPunctuator(state.tokens.next,\"}\")||(advance(\",\"),!checkPunctuator(state.tokens.next,\"}\"))););advance(\"}\")}return identifiers}function destructuringPatternMatch(tokens,value){var first=value.first;first&&_.zip(tokens,Array.isArray(first)?first:[first]).forEach(function(val){var token=val[0],value=val[1];token&&value?token.first=value:token&&token.first&&!value&&warning(\"W080\",token.first,token.first.value)})}function blockVariableStatement(type,statement,context){var tokens,lone,value,letblock,prefix=context&&context.prefix,inexport=context&&context.inexport,isLet=\"let\"===type,isConst=\"const\"===type;for(state.inES6()||warning(\"W104\",state.tokens.curr,type,\"6\"),isLet&&\"(\"===state.tokens.next.value?(state.inMoz()||warning(\"W118\",state.tokens.next,\"let block\"),advance(\"(\"),state.funct[\"(scope)\"].stack(),letblock=!0):state.funct[\"(noblockscopedvar)\"]&&error(\"E048\",state.tokens.curr,isConst?\"Const\":\"Let\"),statement.first=[];;){var names=[];_.contains([\"{\",\"[\"],state.tokens.next.value)?(tokens=destructuringPattern(),lone=!1):(tokens=[{id:identifier(),token:state.tokens.curr}],lone=!0),!prefix&&isConst&&\"=\"!==state.tokens.next.id&&warning(\"E012\",state.tokens.curr,state.tokens.curr.value);for(var t in tokens)tokens.hasOwnProperty(t)&&(t=tokens[t],state.funct[\"(scope)\"].block.isGlobal()&&predefined[t.id]===!1&&warning(\"W079\",t.token,t.id),t.id&&!state.funct[\"(noblockscopedvar)\"]&&(state.funct[\"(scope)\"].addlabel(t.id,{type:type,token:t.token}),names.push(t.token),lone&&inexport&&state.funct[\"(scope)\"].setExported(t.token.value,t.token)));if(\"=\"===state.tokens.next.id&&(advance(\"=\"),prefix||\"undefined\"!==state.tokens.next.id||warning(\"W080\",state.tokens.prev,state.tokens.prev.value),!prefix&&\"=\"===peek(0).id&&state.tokens.next.identifier&&warning(\"W120\",state.tokens.next,state.tokens.next.value),value=expression(prefix?120:10),lone?tokens[0].first=value:destructuringPatternMatch(names,value)),statement.first=statement.first.concat(names),\",\"!==state.tokens.next.id)break;comma()}return letblock&&(advance(\")\"),block(!0,!0),statement.block=!0,state.funct[\"(scope)\"].unstack()),statement}function classdef(isStatement){return state.inES6()||warning(\"W104\",state.tokens.curr,\"class\",\"6\"),isStatement?(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"class\",token:state.tokens.curr})):state.tokens.next.identifier&&\"extends\"!==state.tokens.next.value?(this.name=identifier(),this.namedExpr=!0):this.name=state.nameStack.infer(),classtail(this),this}function classtail(c){var wasInClassBody=state.inClassBody;\"extends\"===state.tokens.next.value&&(advance(\"extends\"),c.heritage=expression(10)),state.inClassBody=!0,advance(\"{\"),c.body=classbody(c),advance(\"}\"),state.inClassBody=wasInClassBody}function classbody(c){for(var name,isStatic,isGenerator,getset,computed,props=Object.create(null),staticProps=Object.create(null),i=0;\"}\"!==state.tokens.next.id;++i)if(name=state.tokens.next,isStatic=!1,isGenerator=!1,getset=null,\";\"!==name.id){if(\"*\"===name.id&&(isGenerator=!0,advance(\"*\"),name=state.tokens.next),\"[\"===name.id)name=computedPropertyName(),computed=!0;else{if(!isPropertyName(name)){warning(\"W052\",state.tokens.next,state.tokens.next.value||state.tokens.next.type),advance();continue}advance(),computed=!1,name.identifier&&\"static\"===name.value&&(checkPunctuator(state.tokens.next,\"*\")&&(isGenerator=!0,advance(\"*\")),(isPropertyName(state.tokens.next)||\"[\"===state.tokens.next.id)&&(computed=\"[\"===state.tokens.next.id,isStatic=!0,name=state.tokens.next,\"[\"===state.tokens.next.id?name=computedPropertyName():advance())),!name.identifier||\"get\"!==name.value&&\"set\"!==name.value||(isPropertyName(state.tokens.next)||\"[\"===state.tokens.next.id)&&(computed=\"[\"===state.tokens.next.id,getset=name,name=state.tokens.next,\"[\"===state.tokens.next.id?name=computedPropertyName():advance())}if(!checkPunctuator(state.tokens.next,\"(\")){for(error(\"E054\",state.tokens.next,state.tokens.next.value);\"}\"!==state.tokens.next.id&&!checkPunctuator(state.tokens.next,\"(\");)advance();\"(\"!==state.tokens.next.value&&doFunction({statement:c})}if(computed||(getset?saveAccessor(getset.value,isStatic?staticProps:props,name.value,name,!0,isStatic):(\"constructor\"===name.value?state.nameStack.set(c):state.nameStack.set(name),saveProperty(isStatic?staticProps:props,name.value,name,!0,isStatic))),getset&&\"constructor\"===name.value){var propDesc=\"get\"===getset.value?\"class getter method\":\"class setter method\";error(\"E049\",name,propDesc,\"constructor\")}else\"prototype\"===name.value&&error(\"E049\",name,\"class method\",\"prototype\");propertyName(name),doFunction({statement:c,type:isGenerator?\"generator\":null,classExprBinding:c.namedExpr?c.name:null})}else warning(\"W032\"),advance(\";\");checkProperties(props)}function saveProperty(props,name,tkn,isClass,isStatic){var msg=[\"key\",\"class method\",\"static class method\"];msg=msg[(isClass||!1)+(isStatic||!1)],tkn.identifier&&(name=tkn.value),props[name]&&\"__proto__\"!==name?warning(\"W075\",state.tokens.next,msg,name):props[name]=Object.create(null),props[name].basic=!0,props[name].basictkn=tkn}function saveAccessor(accessorType,props,name,tkn,isClass,isStatic){var flagName=\"get\"===accessorType?\"getterToken\":\"setterToken\",msg=\"\";isClass?(isStatic&&(msg+=\"static \"),msg+=accessorType+\"ter method\"):msg=\"key\",state.tokens.curr.accessorType=accessorType,state.nameStack.set(tkn),props[name]?(props[name].basic||props[name][flagName])&&\"__proto__\"!==name&&warning(\"W075\",state.tokens.next,msg,name):props[name]=Object.create(null),props[name][flagName]=tkn}function computedPropertyName(){advance(\"[\"),state.inES6()||warning(\"W119\",state.tokens.curr,\"computed property names\",\"6\");var value=expression(10);return advance(\"]\"),value}function checkPunctuators(token,values){return\"(punctuator)\"===token.type?_.contains(values,token.value):!1}function checkPunctuator(token,value){return\"(punctuator)\"===token.type&&token.value===value}function destructuringAssignOrJsonValue(){var block=lookupBlockType();block.notJson?(!state.inES6()&&block.isDestAssign&&warning(\"W104\",state.tokens.curr,\"destructuring assignment\",\"6\"),statements()):(state.option.laxbreak=!0,state.jsonMode=!0,jsonValue())}function jsonValue(){function jsonObject(){var o={},t=state.tokens.next;if(advance(\"{\"),\"}\"!==state.tokens.next.id)for(;;){if(\"(end)\"===state.tokens.next.id)error(\"E026\",state.tokens.next,t.line);else{if(\"}\"===state.tokens.next.id){warning(\"W094\",state.tokens.curr);break}\",\"===state.tokens.next.id?error(\"E028\",state.tokens.next):\"(string)\"!==state.tokens.next.id&&warning(\"W095\",state.tokens.next,state.tokens.next.value)}if(o[state.tokens.next.value]===!0?warning(\"W075\",state.tokens.next,\"key\",state.tokens.next.value):\"__proto__\"===state.tokens.next.value&&!state.option.proto||\"__iterator__\"===state.tokens.next.value&&!state.option.iterator?warning(\"W096\",state.tokens.next,state.tokens.next.value):o[state.tokens.next.value]=!0,advance(),advance(\":\"),jsonValue(),\",\"!==state.tokens.next.id)break;advance(\",\")}advance(\"}\")}function jsonArray(){var t=state.tokens.next;if(advance(\"[\"),\"]\"!==state.tokens.next.id)for(;;){if(\"(end)\"===state.tokens.next.id)error(\"E027\",state.tokens.next,t.line);else{if(\"]\"===state.tokens.next.id){warning(\"W094\",state.tokens.curr);break}\",\"===state.tokens.next.id&&error(\"E028\",state.tokens.next)}if(jsonValue(),\",\"!==state.tokens.next.id)break;advance(\",\")}advance(\"]\")}switch(state.tokens.next.id){case\"{\":jsonObject();break;case\"[\":jsonArray();break;case\"true\":case\"false\":case\"null\":case\"(number)\":case\"(string)\":advance();break;case\"-\":advance(\"-\"),advance(\"(number)\");break;default:error(\"E003\",state.tokens.next)}}var api,declared,functions,inblock,indent,lookahead,lex,member,membersOnly,predefined,stack,urls,bang={\"<\":!0,\"<=\":!0,\"==\":!0,\"===\":!0,\"!==\":!0,\"!=\":!0,\">\":!0,\">=\":!0,\"+\":!0,\"-\":!0,\"*\":!0,\"/\":!0,\"%\":!0},functionicity=[\"closure\",\"exception\",\"global\",\"label\",\"outer\",\"unused\",\"var\"],extraModules=[],emitter=new events.EventEmitter,typeofValues={};typeofValues.legacy=[\"xml\",\"unknown\"],typeofValues.es3=[\"undefined\",\"boolean\",\"number\",\"string\",\"function\",\"object\"],typeofValues.es3=typeofValues.es3.concat(typeofValues.legacy),typeofValues.es6=typeofValues.es3.concat(\"symbol\"),type(\"(number)\",function(){return this}),type(\"(string)\",function(){return this}),state.syntax[\"(identifier)\"]={type:\"(identifier)\",lbp:0,identifier:!0,nud:function(){var v=this.value;return\"=>\"===state.tokens.next.id?this:(state.funct[\"(comparray)\"].check(v)||state.funct[\"(scope)\"].block.use(v,state.tokens.curr),this)},led:function(){error(\"E033\",state.tokens.next,state.tokens.next.value)}};var baseTemplateSyntax={lbp:0,identifier:!1,template:!0};state.syntax[\"(template)\"]=_.extend({type:\"(template)\",nud:doTemplateLiteral,led:doTemplateLiteral,noSubst:!1},baseTemplateSyntax),state.syntax[\"(template middle)\"]=_.extend({type:\"(template middle)\",middle:!0,noSubst:!1},baseTemplateSyntax),state.syntax[\"(template tail)\"]=_.extend({type:\"(template tail)\",tail:!0,noSubst:!1},baseTemplateSyntax),state.syntax[\"(no subst template)\"]=_.extend({type:\"(template)\",nud:doTemplateLiteral,led:doTemplateLiteral,noSubst:!0,tail:!0},baseTemplateSyntax),type(\"(regexp)\",function(){return this}),delim(\"(endline)\"),delim(\"(begin)\"),delim(\"(end)\").reach=!0,delim(\"(error)\").reach=!0,delim(\"}\").reach=!0,delim(\")\"),delim(\"]\"),delim('\"').reach=!0,delim(\"'\").reach=!0,delim(\";\"),delim(\":\").reach=!0,delim(\"#\"),reserve(\"else\"),reserve(\"case\").reach=!0,reserve(\"catch\"),reserve(\"default\").reach=!0,reserve(\"finally\"),reservevar(\"arguments\",function(x){state.isStrict()&&state.funct[\"(global)\"]&&warning(\"E008\",x)}),reservevar(\"eval\"),reservevar(\"false\"),reservevar(\"Infinity\"),reservevar(\"null\"),reservevar(\"this\",function(x){state.isStrict()&&!isMethod()&&!state.option.validthis&&(state.funct[\"(statement)\"]&&state.funct[\"(name)\"].charAt(0)>\"Z\"||state.funct[\"(global)\"])&&warning(\"W040\",x)}),reservevar(\"true\"),reservevar(\"undefined\"),assignop(\"=\",\"assign\",20),assignop(\"+=\",\"assignadd\",20),assignop(\"-=\",\"assignsub\",20),assignop(\"*=\",\"assignmult\",20),assignop(\"/=\",\"assigndiv\",20).nud=function(){error(\"E014\")},assignop(\"%=\",\"assignmod\",20),bitwiseassignop(\"&=\"),bitwiseassignop(\"|=\"),bitwiseassignop(\"^=\"),bitwiseassignop(\"<<=\"),bitwiseassignop(\">>=\"),bitwiseassignop(\">>>=\"),infix(\",\",function(left,that){var expr;if(that.exprs=[left],state.option.nocomma&&warning(\"W127\"),!comma({peek:!0}))return that;for(;;){if(!(expr=expression(10)))break;if(that.exprs.push(expr),\",\"!==state.tokens.next.value||!comma())break}return that},10,!0),infix(\"?\",function(left,that){return increaseComplexityCount(),that.left=left,that.right=expression(10),advance(\":\"),that[\"else\"]=expression(10),that},30);var orPrecendence=40;infix(\"||\",function(left,that){return increaseComplexityCount(),that.left=left,that.right=expression(orPrecendence),that},orPrecendence),infix(\"&&\",\"and\",50),bitwise(\"|\",\"bitor\",70),bitwise(\"^\",\"bitxor\",80),bitwise(\"&\",\"bitand\",90),relation(\"==\",function(left,right){var eqnull=state.option.eqnull&&(\"null\"===(left&&left.value)||\"null\"===(right&&right.value));switch(!0){case!eqnull&&state.option.eqeqeq:this.from=this.character,warning(\"W116\",this,\"===\",\"==\");break;case isPoorRelation(left):warning(\"W041\",this,\"===\",left.value);break;case isPoorRelation(right):warning(\"W041\",this,\"===\",right.value);break;case isTypoTypeof(right,left,state):warning(\"W122\",this,right.value);break;case isTypoTypeof(left,right,state):warning(\"W122\",this,left.value)}return this}),relation(\"===\",function(left,right){return isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"!=\",function(left,right){var eqnull=state.option.eqnull&&(\"null\"===(left&&left.value)||\"null\"===(right&&right.value));return!eqnull&&state.option.eqeqeq?(this.from=this.character,warning(\"W116\",this,\"!==\",\"!=\")):isPoorRelation(left)?warning(\"W041\",this,\"!==\",left.value):isPoorRelation(right)?warning(\"W041\",this,\"!==\",right.value):isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"!==\",function(left,right){return isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"<\"),relation(\">\"),relation(\"<=\"),relation(\">=\"),bitwise(\"<<\",\"shiftleft\",120),bitwise(\">>\",\"shiftright\",120),bitwise(\">>>\",\"shiftrightunsigned\",120),infix(\"in\",\"in\",120),infix(\"instanceof\",\"instanceof\",120),infix(\"+\",function(left,that){var right;return that.left=left,that.right=right=expression(130),left&&right&&\"(string)\"===left.id&&\"(string)\"===right.id?(left.value+=right.value,left.character=right.character,!state.option.scripturl&®.javascriptURL.test(left.value)&&warning(\"W050\",left),left):that},130),prefix(\"+\",\"num\"),prefix(\"+++\",function(){return warning(\"W007\"),this.arity=\"unary\",this.right=expression(150),this}),infix(\"+++\",function(left){return warning(\"W007\"),this.left=left,this.right=expression(130),this},130),infix(\"-\",\"sub\",130),prefix(\"-\",\"neg\"),prefix(\"---\",function(){return warning(\"W006\"),this.arity=\"unary\",this.right=expression(150),this}),infix(\"---\",function(left){return warning(\"W006\"),this.left=left,this.right=expression(130),this},130),infix(\"*\",\"mult\",140),infix(\"/\",\"div\",140),infix(\"%\",\"mod\",140),suffix(\"++\"),prefix(\"++\",\"preinc\"),state.syntax[\"++\"].exps=!0,suffix(\"--\"),prefix(\"--\",\"predec\"),state.syntax[\"--\"].exps=!0,prefix(\"delete\",function(){var p=expression(10);return p?(\".\"!==p.id&&\"[\"!==p.id&&warning(\"W051\"),this.first=p,p.identifier&&!state.isStrict()&&(p.forgiveUndef=!0),this):this}).exps=!0,prefix(\"~\",function(){return state.option.bitwise&&warning(\"W016\",this,\"~\"),this.arity=\"unary\",this.right=expression(150),this}),prefix(\"...\",function(){return state.inES6(!0)||warning(\"W119\",this,\"spread/rest operator\",\"6\"),state.tokens.next.identifier||\"(string)\"===state.tokens.next.type||checkPunctuators(state.tokens.next,[\"[\",\"(\"])||error(\"E030\",state.tokens.next,state.tokens.next.value),expression(150),this}),prefix(\"!\",function(){return this.arity=\"unary\",this.right=expression(150),this.right||quit(\"E041\",this.line||0),bang[this.right.id]===!0&&warning(\"W018\",this,\"!\"),this}),prefix(\"typeof\",function(){var p=expression(150);return this.first=this.right=p,p||quit(\"E041\",this.line||0,this.character||0),p.identifier&&(p.forgiveUndef=!0),this}),prefix(\"new\",function(){var mp=metaProperty(\"target\",function(){state.inES6(!0)||warning(\"W119\",state.tokens.prev,\"new.target\",\"6\");for(var inFunction,c=state.funct;c&&(inFunction=!c[\"(global)\"],c[\"(arrow)\"]);)c=c[\"(context)\"];inFunction||warning(\"W136\",state.tokens.prev,\"new.target\")});if(mp)return mp;var i,c=expression(155);if(c&&\"function\"!==c.id)if(c.identifier)switch(c[\"new\"]=!0,c.value){case\"Number\":case\"String\":case\"Boolean\":case\"Math\":case\"JSON\":warning(\"W053\",state.tokens.prev,c.value);break;case\"Symbol\":state.inES6()&&warning(\"W053\",state.tokens.prev,c.value);break;case\"Function\":state.option.evil||warning(\"W054\");break;case\"Date\":case\"RegExp\":case\"this\":break;default:\"function\"!==c.id&&(i=c.value.substr(0,1),state.option.newcap&&(\"A\">i||i>\"Z\")&&!state.funct[\"(scope)\"].isPredefined(c.value)&&warning(\"W055\",state.tokens.curr))}else\".\"!==c.id&&\"[\"!==c.id&&\"(\"!==c.id&&warning(\"W056\",state.tokens.curr);else state.option.supernew||warning(\"W057\",this);return\"(\"===state.tokens.next.id||state.option.supernew||warning(\"W058\",state.tokens.curr,state.tokens.curr.value),this.first=this.right=c,this}),state.syntax[\"new\"].exps=!0,prefix(\"void\").exps=!0,infix(\".\",function(left,that){var m=identifier(!1,!0);return\"string\"==typeof m&&countMember(m),that.left=left,that.right=m,m&&\"hasOwnProperty\"===m&&\"=\"===state.tokens.next.value&&warning(\"W001\"),!left||\"arguments\"!==left.value||\"callee\"!==m&&\"caller\"!==m?state.option.evil||!left||\"document\"!==left.value||\"write\"!==m&&\"writeln\"!==m||warning(\"W060\",left):state.option.noarg?warning(\"W059\",left,m):state.isStrict()&&error(\"E008\"),state.option.evil||\"eval\"!==m&&\"execScript\"!==m||isGlobalEval(left,state)&&warning(\"W061\"),that},160,!0),infix(\"(\",function(left,that){state.option.immed&&left&&!left.immed&&\"function\"===left.id&&warning(\"W062\");var n=0,p=[];if(left&&\"(identifier)\"===left.type&&left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)&&-1===\"Array Number String Boolean Date Object Error Symbol\".indexOf(left.value)&&(\"Math\"===left.value?warning(\"W063\",left):state.option.newcap&&warning(\"W064\",left)),\")\"!==state.tokens.next.id)for(;p[p.length]=expression(10),n+=1,\",\"===state.tokens.next.id;)comma();return advance(\")\"),\"object\"==typeof left&&(state.inES5()||\"parseInt\"!==left.value||1!==n||warning(\"W065\",state.tokens.curr),state.option.evil||(\"eval\"===left.value||\"Function\"===left.value||\"execScript\"===left.value?(warning(\"W061\",left),p[0]&&\"(string)\"===[0].id&&addInternalSrc(left,p[0].value)):!p[0]||\"(string)\"!==p[0].id||\"setTimeout\"!==left.value&&\"setInterval\"!==left.value?!p[0]||\"(string)\"!==p[0].id||\".\"!==left.value||\"window\"!==left.left.value||\"setTimeout\"!==left.right&&\"setInterval\"!==left.right||(warning(\"W066\",left),addInternalSrc(left,p[0].value)):(warning(\"W066\",left),addInternalSrc(left,p[0].value))),left.identifier||\".\"===left.id||\"[\"===left.id||\"=>\"===left.id||\"(\"===left.id||\"&&\"===left.id||\"||\"===left.id||\"?\"===left.id||state.inES6()&&left[\"(name)\"]||warning(\"W067\",that)),that.left=left,that},155,!0).exps=!0,prefix(\"(\",function(){var pn1,ret,triggerFnExpr,first,last,pn=state.tokens.next,i=-1,parens=1,opening=state.tokens.curr,preceeding=state.tokens.prev,isNecessary=!state.option.singleGroups;do\"(\"===pn.value?parens+=1:\")\"===pn.value&&(parens-=1),i+=1,pn1=pn,pn=peek(i);while((0!==parens||\")\"!==pn1.value)&&\";\"!==pn.value&&\"(end)\"!==pn.type);if(\"function\"===state.tokens.next.id&&(triggerFnExpr=state.tokens.next.immed=!0),\"=>\"===pn.value)return doFunction({type:\"arrow\",parsedOpening:!0});var exprs=[];if(\")\"!==state.tokens.next.id)for(;exprs.push(expression(10)),\",\"===state.tokens.next.id;)state.option.nocomma&&warning(\"W127\"),comma();return advance(\")\",this),state.option.immed&&exprs[0]&&\"function\"===exprs[0].id&&\"(\"!==state.tokens.next.id&&\".\"!==state.tokens.next.id&&\"[\"!==state.tokens.next.id&&warning(\"W068\",this),exprs.length?(exprs.length>1?(ret=Object.create(state.syntax[\",\"]),ret.exprs=exprs,first=exprs[0],last=exprs[exprs.length-1],isNecessary||(isNecessary=preceeding.assign||preceeding.delim)):(ret=first=last=exprs[0],isNecessary||(isNecessary=opening.beginsStmt&&(\"{\"===ret.id||triggerFnExpr||isFunctor(ret))||triggerFnExpr&&(!isEndOfExpr()||\"}\"!==state.tokens.prev.id)||isFunctor(ret)&&!isEndOfExpr()||\"{\"===ret.id&&\"=>\"===preceeding.id||\"(number)\"===ret.type&&checkPunctuator(pn,\".\")&&/^\\d+$/.test(ret.value))),ret&&(!isNecessary&&(first.left||first.right||ret.exprs)&&(isNecessary=!isBeginOfExpr(preceeding)&&first.lbp<=preceeding.lbp||!isEndOfExpr()&&last.lbp\"),infix(\"[\",function(left,that){var s,e=expression(10);return e&&\"(string)\"===e.type&&(state.option.evil||\"eval\"!==e.value&&\"execScript\"!==e.value||isGlobalEval(left,state)&&warning(\"W061\"),countMember(e.value),!state.option.sub&®.identifier.test(e.value)&&(s=state.syntax[e.value],s&&isReserved(s)||warning(\"W069\",state.tokens.prev,e.value))),advance(\"]\",that),e&&\"hasOwnProperty\"===e.value&&\"=\"===state.tokens.next.value&&warning(\"W001\"),that.left=left,that.right=e,that},160,!0),prefix(\"[\",function(){var blocktype=lookupBlockType();if(blocktype.isCompArray)return state.option.esnext||state.inMoz()||warning(\"W118\",state.tokens.curr,\"array comprehension\"),comprehensiveArrayExpression();if(blocktype.isDestAssign)return this.destructAssign=destructuringPattern({openingParsed:!0,assignment:!0}),this;var b=state.tokens.curr.line!==startLine(state.tokens.next);for(this.first=[],b&&(indent+=state.option.indent,state.tokens.next.from===indent+state.option.indent&&(indent+=state.option.indent));\"(end)\"!==state.tokens.next.id;){for(;\",\"===state.tokens.next.id;){if(!state.option.elision){if(state.inES5()){warning(\"W128\");do advance(\",\");while(\",\"===state.tokens.next.id);continue}warning(\"W070\")}advance(\",\")}if(\"]\"===state.tokens.next.id)break;if(this.first.push(expression(10)),\",\"!==state.tokens.next.id)break;if(comma({allowTrailing:!0}),\"]\"===state.tokens.next.id&&!state.inES5()){warning(\"W070\",state.tokens.curr);break}}return b&&(indent-=state.option.indent),advance(\"]\",this),this}),function(x){x.nud=function(){var b,f,i,p,t,nextVal,isGeneratorMethod=!1,props=Object.create(null);b=state.tokens.curr.line!==startLine(state.tokens.next),b&&(indent+=state.option.indent,state.tokens.next.from===indent+state.option.indent&&(indent+=state.option.indent));var blocktype=lookupBlockType();if(blocktype.isDestAssign)return this.destructAssign=destructuringPattern({openingParsed:!0,assignment:!0}),this;for(;\"}\"!==state.tokens.next.id;){if(nextVal=state.tokens.next.value,!state.tokens.next.identifier||\",\"!==peekIgnoreEOL().id&&\"}\"!==peekIgnoreEOL().id)if(\":\"===peek().id||\"get\"!==nextVal&&\"set\"!==nextVal){if(\"*\"===state.tokens.next.value&&\"(punctuator)\"===state.tokens.next.type?(state.inES6()||warning(\"W104\",state.tokens.next,\"generator functions\",\"6\"),advance(\"*\"),isGeneratorMethod=!0):isGeneratorMethod=!1,\"[\"===state.tokens.next.id)i=computedPropertyName(),state.nameStack.set(i);else if(state.nameStack.set(state.tokens.next),i=propertyName(),saveProperty(props,i,state.tokens.next),\"string\"!=typeof i)break;\"(\"===state.tokens.next.value?(state.inES6()||warning(\"W104\",state.tokens.curr,\"concise methods\",\"6\"),doFunction({type:isGeneratorMethod?\"generator\":null})):(advance(\":\"),expression(10))}else advance(nextVal),state.inES5()||error(\"E034\"),i=propertyName(),i||state.inES6()||error(\"E035\"),i&&saveAccessor(nextVal,props,i,state.tokens.curr),t=state.tokens.next,f=doFunction(),p=f[\"(params)\"],\"get\"===nextVal&&i&&p?warning(\"W076\",t,p[0],i):\"set\"!==nextVal||!i||p&&1===p.length||warning(\"W077\",t,i);else state.inES6()||warning(\"W104\",state.tokens.next,\"object short notation\",\"6\"),i=propertyName(!0),saveProperty(props,i,state.tokens.next),expression(10);if(countMember(i),\",\"!==state.tokens.next.id)break;comma({allowTrailing:!0,property:!0}),\",\"===state.tokens.next.id?warning(\"W070\",state.tokens.curr):\"}\"!==state.tokens.next.id||state.inES5()||warning(\"W070\",state.tokens.curr)}return b&&(indent-=state.option.indent),advance(\"}\",this),checkProperties(props),this},x.fud=function(){error(\"E036\",state.tokens.curr)}}(delim(\"{\"));var conststatement=stmt(\"const\",function(context){return blockVariableStatement(\"const\",this,context)});conststatement.exps=!0;var letstatement=stmt(\"let\",function(context){return blockVariableStatement(\"let\",this,context)});letstatement.exps=!0;var varstatement=stmt(\"var\",function(context){var tokens,lone,value,prefix=context&&context.prefix,inexport=context&&context.inexport,implied=context&&context.implied,report=!(context&&context.ignore);for(this.first=[];;){var names=[];_.contains([\"{\",\"[\"],state.tokens.next.value)?(tokens=destructuringPattern(),lone=!1):(tokens=[{id:identifier(),token:state.tokens.curr}],lone=!0),prefix&&implied||!report||!state.option.varstmt||warning(\"W132\",this),this.first=this.first.concat(names);for(var t in tokens)tokens.hasOwnProperty(t)&&(t=tokens[t],!implied&&state.funct[\"(global)\"]&&(predefined[t.id]===!1?warning(\"W079\",t.token,t.id):state.option.futurehostile===!1&&(!state.inES5()&&vars.ecmaIdentifiers[5][t.id]===!1||!state.inES6()&&vars.ecmaIdentifiers[6][t.id]===!1)&&warning(\"W129\",t.token,t.id)),t.id&&(\"for\"===implied?(state.funct[\"(scope)\"].has(t.id)||report&&warning(\"W088\",t.token,t.id),state.funct[\"(scope)\"].block.use(t.id,t.token)):(state.funct[\"(scope)\"].addlabel(t.id,{type:\"var\",token:t.token}),lone&&inexport&&state.funct[\"(scope)\"].setExported(t.id,t.token)),names.push(t.token)));if(\"=\"===state.tokens.next.id&&(state.nameStack.set(state.tokens.curr),advance(\"=\"),prefix||!report||state.funct[\"(loopage)\"]||\"undefined\"!==state.tokens.next.id||warning(\"W080\",state.tokens.prev,state.tokens.prev.value),\"=\"===peek(0).id&&state.tokens.next.identifier&&(!prefix&&report&&!state.funct[\"(params)\"]||-1===state.funct[\"(params)\"].indexOf(state.tokens.next.value))&&warning(\"W120\",state.tokens.next,state.tokens.next.value),value=expression(prefix?120:10),lone?tokens[0].first=value:destructuringPatternMatch(names,value)),\",\"!==state.tokens.next.id)break;comma()}return this});varstatement.exps=!0,blockstmt(\"class\",function(){return classdef.call(this,!0)}),blockstmt(\"function\",function(context){var inexport=context&&context.inexport,generator=!1;\"*\"===state.tokens.next.value&&(advance(\"*\"),state.inES6({strict:!0})?generator=!0:warning(\"W119\",state.tokens.curr,\"function*\",\"6\")),inblock&&warning(\"W082\",state.tokens.curr);var i=optionalidentifier();return state.funct[\"(scope)\"].addlabel(i,{type:\"function\",token:state.tokens.curr}),void 0===i?warning(\"W025\"):inexport&&state.funct[\"(scope)\"].setExported(i,state.tokens.prev),doFunction({name:i,statement:this,type:generator?\"generator\":null,ignoreLoopFunc:inblock}),\"(\"===state.tokens.next.id&&state.tokens.next.line===state.tokens.curr.line&&error(\"E039\"),this}),prefix(\"function\",function(){var generator=!1;\"*\"===state.tokens.next.value&&(state.inES6()||warning(\"W119\",state.tokens.curr,\"function*\",\"6\"),advance(\"*\"),generator=!0);var i=optionalidentifier();return doFunction({name:i,type:generator?\"generator\":null}),this}),blockstmt(\"if\",function(){var t=state.tokens.next;increaseComplexityCount(),state.condition=!0,advance(\"(\");var expr=expression(0);checkCondAssignment(expr);var forinifcheck=null;state.option.forin&&state.forinifcheckneeded&&(state.forinifcheckneeded=!1,forinifcheck=state.forinifchecks[state.forinifchecks.length-1],forinifcheck.type=\"(punctuator)\"===expr.type&&\"!\"===expr.value?\"(negative)\":\"(positive)\"),advance(\")\",t),state.condition=!1;var s=block(!0,!0);return forinifcheck&&\"(negative)\"===forinifcheck.type&&s&&s[0]&&\"(identifier)\"===s[0].type&&\"continue\"===s[0].value&&(forinifcheck.type=\"(negative-with-continue)\"),\"else\"===state.tokens.next.id&&(advance(\"else\"),\"if\"===state.tokens.next.id||\"switch\"===state.tokens.next.id?statement():block(!0,!0)),this}),blockstmt(\"try\",function(){function doCatch(){if(advance(\"catch\"),advance(\"(\"),state.funct[\"(scope)\"].stack(\"catchparams\"),checkPunctuators(state.tokens.next,[\"[\",\"{\"])){var tokens=destructuringPattern();_.each(tokens,function(token){token.id&&state.funct[\"(scope)\"].addParam(token.id,token,\"exception\")})}else\"(identifier)\"!==state.tokens.next.type?warning(\"E030\",state.tokens.next,state.tokens.next.value):state.funct[\"(scope)\"].addParam(identifier(),state.tokens.curr,\"exception\");\"if\"===state.tokens.next.value&&(state.inMoz()||warning(\"W118\",state.tokens.curr,\"catch filter\"),advance(\"if\"),expression(0)),advance(\")\"),block(!1),state.funct[\"(scope)\"].unstack()}var b;for(block(!0);\"catch\"===state.tokens.next.id;)increaseComplexityCount(),b&&!state.inMoz()&&warning(\"W118\",state.tokens.next,\"multiple catch blocks\"),doCatch(),b=!0;return\"finally\"===state.tokens.next.id?(advance(\"finally\"),block(!0),void 0):(b||error(\"E021\",state.tokens.next,\"catch\",state.tokens.next.value),this)}),blockstmt(\"while\",function(){var t=state.tokens.next;return state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,increaseComplexityCount(),advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),block(!0,!0),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1,this}).labelled=!0,blockstmt(\"with\",function(){var t=state.tokens.next;return state.isStrict()?error(\"E010\",state.tokens.curr):state.option.withstmt||warning(\"W085\",state.tokens.curr),advance(\"(\"),expression(0),advance(\")\",t),block(!0,!0),this}),blockstmt(\"switch\",function(){var t=state.tokens.next,g=!1,noindent=!1;\nfor(state.funct[\"(breakage)\"]+=1,advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),t=state.tokens.next,advance(\"{\"),state.tokens.next.from===indent&&(noindent=!0),noindent||(indent+=state.option.indent),this.cases=[];;)switch(state.tokens.next.id){case\"case\":switch(state.funct[\"(verb)\"]){case\"yield\":case\"break\":case\"case\":case\"continue\":case\"return\":case\"switch\":case\"throw\":break;default:state.tokens.curr.caseFallsThrough||warning(\"W086\",state.tokens.curr,\"case\")}advance(\"case\"),this.cases.push(expression(0)),increaseComplexityCount(),g=!0,advance(\":\"),state.funct[\"(verb)\"]=\"case\";break;case\"default\":switch(state.funct[\"(verb)\"]){case\"yield\":case\"break\":case\"continue\":case\"return\":case\"throw\":break;default:this.cases.length&&(state.tokens.curr.caseFallsThrough||warning(\"W086\",state.tokens.curr,\"default\"))}advance(\"default\"),g=!0,advance(\":\");break;case\"}\":return noindent||(indent-=state.option.indent),advance(\"}\",t),state.funct[\"(breakage)\"]-=1,state.funct[\"(verb)\"]=void 0,void 0;case\"(end)\":return error(\"E023\",state.tokens.next,\"}\"),void 0;default:if(indent+=state.option.indent,g)switch(state.tokens.curr.id){case\",\":return error(\"E040\"),void 0;case\":\":g=!1,statements();break;default:return error(\"E025\",state.tokens.curr),void 0}else{if(\":\"!==state.tokens.curr.id)return error(\"E021\",state.tokens.next,\"case\",state.tokens.next.value),void 0;advance(\":\"),error(\"E024\",state.tokens.curr,\":\"),statements()}indent-=state.option.indent}return this}).labelled=!0,stmt(\"debugger\",function(){return state.option.debug||warning(\"W087\",this),this}).exps=!0,function(){var x=stmt(\"do\",function(){state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,increaseComplexityCount(),this.first=block(!0,!0),advance(\"while\");var t=state.tokens.next;return advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1,this});x.labelled=!0,x.exps=!0}(),blockstmt(\"for\",function(){var s,t=state.tokens.next,letscope=!1,foreachtok=null;\"each\"===t.value&&(foreachtok=t,advance(\"each\"),state.inMoz()||warning(\"W118\",state.tokens.curr,\"for each\")),increaseComplexityCount(),advance(\"(\");var nextop,comma,initializer,i=0,inof=[\"in\",\"of\"],level=0;checkPunctuators(state.tokens.next,[\"{\",\"[\"])&&++level;do{if(nextop=peek(i),++i,checkPunctuators(nextop,[\"{\",\"[\"])?++level:checkPunctuators(nextop,[\"}\",\"]\"])&&--level,0>level)break;0===level&&(!comma&&checkPunctuator(nextop,\",\")?comma=nextop:!initializer&&checkPunctuator(nextop,\"=\")&&(initializer=nextop))}while(level>0||!_.contains(inof,nextop.value)&&\";\"!==nextop.value&&\"(end)\"!==nextop.type);if(_.contains(inof,nextop.value)){state.inES6()||\"of\"!==nextop.value||warning(\"W104\",nextop,\"for of\",\"6\");var ok=!(initializer||comma);if(initializer&&error(\"W133\",comma,nextop.value,\"initializer is forbidden\"),comma&&error(\"W133\",comma,nextop.value,\"more than one ForBinding\"),\"var\"===state.tokens.next.id?(advance(\"var\"),state.tokens.curr.fud({prefix:!0})):\"let\"===state.tokens.next.id||\"const\"===state.tokens.next.id?(advance(state.tokens.next.id),letscope=!0,state.funct[\"(scope)\"].stack(),state.tokens.curr.fud({prefix:!0})):Object.create(varstatement).fud({prefix:!0,implied:\"for\",ignore:!ok}),advance(nextop.value),expression(20),advance(\")\",t),\"in\"===nextop.value&&state.option.forin&&(state.forinifcheckneeded=!0,void 0===state.forinifchecks&&(state.forinifchecks=[]),state.forinifchecks.push({type:\"(none)\"})),state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,s=block(!0,!0),\"in\"===nextop.value&&state.option.forin){if(state.forinifchecks&&state.forinifchecks.length>0){var check=state.forinifchecks.pop();(s&&s.length>0&&(\"object\"!=typeof s[0]||\"if\"!==s[0].value)||\"(positive)\"===check.type&&s.length>1||\"(negative)\"===check.type)&&warning(\"W089\",this)}state.forinifcheckneeded=!1}state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1}else{if(foreachtok&&error(\"E045\",foreachtok),\";\"!==state.tokens.next.id)if(\"var\"===state.tokens.next.id)advance(\"var\"),state.tokens.curr.fud();else if(\"let\"===state.tokens.next.id)advance(\"let\"),letscope=!0,state.funct[\"(scope)\"].stack(),state.tokens.curr.fud();else for(;expression(0,\"for\"),\",\"===state.tokens.next.id;)comma();if(nolinebreak(state.tokens.curr),advance(\";\"),state.funct[\"(loopage)\"]+=1,\";\"!==state.tokens.next.id&&checkCondAssignment(expression(0)),nolinebreak(state.tokens.curr),advance(\";\"),\";\"===state.tokens.next.id&&error(\"E021\",state.tokens.next,\")\",\";\"),\")\"!==state.tokens.next.id)for(;expression(0,\"for\"),\",\"===state.tokens.next.id;)comma();advance(\")\",t),state.funct[\"(breakage)\"]+=1,block(!0,!0),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1}return letscope&&state.funct[\"(scope)\"].unstack(),this}).labelled=!0,stmt(\"break\",function(){var v=state.tokens.next.value;return state.option.asi||nolinebreak(this),\";\"===state.tokens.next.id||state.tokens.next.reach||state.tokens.curr.line!==startLine(state.tokens.next)?0===state.funct[\"(breakage)\"]&&warning(\"W052\",state.tokens.next,this.value):(state.funct[\"(scope)\"].funct.hasBreakLabel(v)||warning(\"W090\",state.tokens.next,v),this.first=state.tokens.next,advance()),reachable(this),this}).exps=!0,stmt(\"continue\",function(){var v=state.tokens.next.value;return 0===state.funct[\"(breakage)\"]&&warning(\"W052\",state.tokens.next,this.value),state.funct[\"(loopage)\"]||warning(\"W052\",state.tokens.next,this.value),state.option.asi||nolinebreak(this),\";\"===state.tokens.next.id||state.tokens.next.reach||state.tokens.curr.line===startLine(state.tokens.next)&&(state.funct[\"(scope)\"].funct.hasBreakLabel(v)||warning(\"W090\",state.tokens.next,v),this.first=state.tokens.next,advance()),reachable(this),this}).exps=!0,stmt(\"return\",function(){return this.line===startLine(state.tokens.next)?\";\"===state.tokens.next.id||state.tokens.next.reach||(this.first=expression(0),!this.first||\"(punctuator)\"!==this.first.type||\"=\"!==this.first.value||this.first.paren||state.option.boss||warningAt(\"W093\",this.first.line,this.first.character)):\"(punctuator)\"===state.tokens.next.type&&[\"[\",\"{\",\"+\",\"-\"].indexOf(state.tokens.next.value)>-1&&nolinebreak(this),reachable(this),this}).exps=!0,function(x){x.exps=!0,x.lbp=25}(prefix(\"yield\",function(){var prev=state.tokens.prev;state.inES6(!0)&&!state.funct[\"(generator)\"]?\"(catch)\"===state.funct[\"(name)\"]&&state.funct[\"(context)\"][\"(generator)\"]||error(\"E046\",state.tokens.curr,\"yield\"):state.inES6()||warning(\"W104\",state.tokens.curr,\"yield\",\"6\"),state.funct[\"(generator)\"]=\"yielded\";var delegatingYield=!1;return\"*\"===state.tokens.next.value&&(delegatingYield=!0,advance(\"*\")),this.line!==startLine(state.tokens.next)&&state.inMoz()?state.option.asi||nolinebreak(this):((delegatingYield||\";\"!==state.tokens.next.id&&!state.option.asi&&!state.tokens.next.reach&&state.tokens.next.nud)&&(nobreaknonadjacent(state.tokens.curr,state.tokens.next),this.first=expression(10),\"(punctuator)\"!==this.first.type||\"=\"!==this.first.value||this.first.paren||state.option.boss||warningAt(\"W093\",this.first.line,this.first.character)),state.inMoz()&&\")\"!==state.tokens.next.id&&(prev.lbp>30||!prev.assign&&!isEndOfExpr()||\"yield\"===prev.id)&&error(\"E050\",this)),this})),stmt(\"throw\",function(){return nolinebreak(this),this.first=expression(20),reachable(this),this}).exps=!0,stmt(\"import\",function(){if(state.inES6()||warning(\"W119\",state.tokens.curr,\"import\",\"6\"),\"(string)\"===state.tokens.next.type)return advance(\"(string)\"),this;if(state.tokens.next.identifier){if(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"const\",token:state.tokens.curr}),\",\"!==state.tokens.next.value)return advance(\"from\"),advance(\"(string)\"),this;advance(\",\")}if(\"*\"===state.tokens.next.id)advance(\"*\"),advance(\"as\"),state.tokens.next.identifier&&(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"const\",token:state.tokens.curr}));else for(advance(\"{\");;){if(\"}\"===state.tokens.next.value){advance(\"}\");break}var importName;if(\"default\"===state.tokens.next.type?(importName=\"default\",advance(\"default\")):importName=identifier(),\"as\"===state.tokens.next.value&&(advance(\"as\"),importName=identifier()),state.funct[\"(scope)\"].addlabel(importName,{type:\"const\",token:state.tokens.curr}),\",\"!==state.tokens.next.value){if(\"}\"===state.tokens.next.value){advance(\"}\");break}error(\"E024\",state.tokens.next,state.tokens.next.value);break}advance(\",\")}return advance(\"from\"),advance(\"(string)\"),this}).exps=!0,stmt(\"export\",function(){var token,identifier,ok=!0;if(state.inES6()||(warning(\"W119\",state.tokens.curr,\"export\",\"6\"),ok=!1),state.funct[\"(scope)\"].block.isGlobal()||(error(\"E053\",state.tokens.curr),ok=!1),\"*\"===state.tokens.next.value)return advance(\"*\"),advance(\"from\"),advance(\"(string)\"),this;if(\"default\"===state.tokens.next.type){state.nameStack.set(state.tokens.next),advance(\"default\");var exportType=state.tokens.next.id;return(\"function\"===exportType||\"class\"===exportType)&&(this.block=!0),token=peek(),expression(10),identifier=token.value,this.block&&(state.funct[\"(scope)\"].addlabel(identifier,{type:exportType,token:token}),state.funct[\"(scope)\"].setExported(identifier,token)),this}if(\"{\"===state.tokens.next.value){advance(\"{\");for(var exportedTokens=[];;){if(state.tokens.next.identifier||error(\"E030\",state.tokens.next,state.tokens.next.value),advance(),exportedTokens.push(state.tokens.curr),\"as\"===state.tokens.next.value&&(advance(\"as\"),state.tokens.next.identifier||error(\"E030\",state.tokens.next,state.tokens.next.value),advance()),\",\"!==state.tokens.next.value){if(\"}\"===state.tokens.next.value){advance(\"}\");break}error(\"E024\",state.tokens.next,state.tokens.next.value);break}advance(\",\")}return\"from\"===state.tokens.next.value?(advance(\"from\"),advance(\"(string)\")):ok&&exportedTokens.forEach(function(token){state.funct[\"(scope)\"].setExported(token.value,token)}),this}if(\"var\"===state.tokens.next.id)advance(\"var\"),state.tokens.curr.fud({inexport:!0});else if(\"let\"===state.tokens.next.id)advance(\"let\"),state.tokens.curr.fud({inexport:!0});else if(\"const\"===state.tokens.next.id)advance(\"const\"),state.tokens.curr.fud({inexport:!0});else if(\"function\"===state.tokens.next.id)this.block=!0,advance(\"function\"),state.syntax[\"function\"].fud({inexport:!0});else if(\"class\"===state.tokens.next.id){this.block=!0,advance(\"class\");var classNameToken=state.tokens.next;state.syntax[\"class\"].fud(),state.funct[\"(scope)\"].setExported(classNameToken.value,classNameToken)}else error(\"E024\",state.tokens.next,state.tokens.next.value);return this}).exps=!0,FutureReservedWord(\"abstract\"),FutureReservedWord(\"boolean\"),FutureReservedWord(\"byte\"),FutureReservedWord(\"char\"),FutureReservedWord(\"class\",{es5:!0,nud:classdef}),FutureReservedWord(\"double\"),FutureReservedWord(\"enum\",{es5:!0}),FutureReservedWord(\"export\",{es5:!0}),FutureReservedWord(\"extends\",{es5:!0}),FutureReservedWord(\"final\"),FutureReservedWord(\"float\"),FutureReservedWord(\"goto\"),FutureReservedWord(\"implements\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"import\",{es5:!0}),FutureReservedWord(\"int\"),FutureReservedWord(\"interface\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"long\"),FutureReservedWord(\"native\"),FutureReservedWord(\"package\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"private\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"protected\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"public\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"short\"),FutureReservedWord(\"static\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"super\",{es5:!0}),FutureReservedWord(\"synchronized\"),FutureReservedWord(\"transient\"),FutureReservedWord(\"volatile\");var lookupBlockType=function(){var pn,pn1,prev,i=-1,bracketStack=0,ret={};checkPunctuators(state.tokens.curr,[\"[\",\"{\"])&&(bracketStack+=1);do{if(prev=-1===i?state.tokens.curr:pn,pn=-1===i?state.tokens.next:peek(i),pn1=peek(i+1),i+=1,checkPunctuators(pn,[\"[\",\"{\"])?bracketStack+=1:checkPunctuators(pn,[\"]\",\"}\"])&&(bracketStack-=1),1===bracketStack&&pn.identifier&&\"for\"===pn.value&&!checkPunctuator(prev,\".\")){ret.isCompArray=!0,ret.notJson=!0;break}if(0===bracketStack&&checkPunctuators(pn,[\"}\",\"]\"])){if(\"=\"===pn1.value){ret.isDestAssign=!0,ret.notJson=!0;break}if(\".\"===pn1.value){ret.notJson=!0;break}}checkPunctuator(pn,\";\")&&(ret.isBlock=!0,ret.notJson=!0)}while(bracketStack>0&&\"(end)\"!==pn.id);return ret},arrayComprehension=function(){function declare(v){var l=_current.variables.filter(function(elt){return elt.value===v?(elt.undef=!1,v):void 0}).length;return 0!==l}function use(v){var l=_current.variables.filter(function(elt){return elt.value!==v||elt.undef?void 0:(elt.unused===!0&&(elt.unused=!1),v)}).length;return 0===l}var _current,CompArray=function(){this.mode=\"use\",this.variables=[]},_carrays=[];return{stack:function(){_current=new CompArray,_carrays.push(_current)},unstack:function(){_current.variables.filter(function(v){v.unused&&warning(\"W098\",v.token,v.raw_text||v.value),v.undef&&state.funct[\"(scope)\"].block.use(v.value,v.token)}),_carrays.splice(-1,1),_current=_carrays[_carrays.length-1]},setState:function(s){_.contains([\"use\",\"define\",\"generate\",\"filter\"],s)&&(_current.mode=s)},check:function(v){return _current?_current&&\"use\"===_current.mode?(use(v)&&_current.variables.push({funct:state.funct,token:state.tokens.curr,value:v,undef:!0,unused:!1}),!0):_current&&\"define\"===_current.mode?(declare(v)||_current.variables.push({funct:state.funct,token:state.tokens.curr,value:v,undef:!1,unused:!0}),!0):_current&&\"generate\"===_current.mode?(state.funct[\"(scope)\"].block.use(v,state.tokens.curr),!0):_current&&\"filter\"===_current.mode?(use(v)&&state.funct[\"(scope)\"].block.use(v,state.tokens.curr),!0):!1:void 0}}},escapeRegex=function(str){return str.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g,\"\\\\$&\")},itself=function(s,o,g){function each(obj,cb){obj&&(Array.isArray(obj)||\"object\"!=typeof obj||(obj=Object.keys(obj)),obj.forEach(cb))}var i,k,x,reIgnoreStr,reIgnore,optionKeys,newOptionObj={},newIgnoredObj={};o=_.clone(o),state.reset(),o&&o.scope?JSHINT.scope=o.scope:(JSHINT.errors=[],JSHINT.undefs=[],JSHINT.internals=[],JSHINT.blacklist={},JSHINT.scope=\"(main)\"),predefined=Object.create(null),combine(predefined,vars.ecmaIdentifiers[3]),combine(predefined,vars.reservedVars),combine(predefined,g||{}),declared=Object.create(null);var exported=Object.create(null);if(o)for(each(o.predef||null,function(item){var slice,prop;\"-\"===item[0]?(slice=item.slice(1),JSHINT.blacklist[slice]=slice,delete predefined[slice]):(prop=Object.getOwnPropertyDescriptor(o.predef,item),predefined[item]=prop?prop.value:!1)}),each(o.exported||null,function(item){exported[item]=!0}),delete o.predef,delete o.exported,optionKeys=Object.keys(o),x=0;optionKeys.length>x;x++)if(/^-W\\d{3}$/g.test(optionKeys[x]))newIgnoredObj[optionKeys[x].slice(1)]=!0;else{var optionKey=optionKeys[x];newOptionObj[optionKey]=o[optionKey],(\"esversion\"===optionKey&&5===o[optionKey]||\"es5\"===optionKey&&o[optionKey])&&warning(\"I003\"),\"newcap\"===optionKeys[x]&&o[optionKey]===!1&&(newOptionObj[\"(explicitNewcap)\"]=!0)}state.option=newOptionObj,state.ignored=newIgnoredObj,state.option.indent=state.option.indent||4,state.option.maxerr=state.option.maxerr||50,indent=1;var scopeManagerInst=scopeManager(state,predefined,exported,declared);if(scopeManagerInst.on(\"warning\",function(ev){warning.apply(null,[ev.code,ev.token].concat(ev.data))}),scopeManagerInst.on(\"error\",function(ev){error.apply(null,[ev.code,ev.token].concat(ev.data))}),state.funct=functor(\"(global)\",null,{\"(global)\":!0,\"(scope)\":scopeManagerInst,\"(comparray)\":arrayComprehension(),\"(metrics)\":createMetrics(state.tokens.next)}),functions=[state.funct],urls=[],stack=null,member={},membersOnly=null,inblock=!1,lookahead=[],!isString(s)&&!Array.isArray(s))return errorAt(\"E004\",0),!1;api={get isJSON(){return state.jsonMode},getOption:function(name){return state.option[name]||null},getCache:function(name){return state.cache[name]},setCache:function(name,value){state.cache[name]=value},warn:function(code,data){warningAt.apply(null,[code,data.line,data.char].concat(data.data))},on:function(names,listener){names.split(\" \").forEach(function(name){emitter.on(name,listener)}.bind(this))}},emitter.removeAllListeners(),(extraModules||[]).forEach(function(func){func(api)}),state.tokens.prev=state.tokens.curr=state.tokens.next=state.syntax[\"(begin)\"],o&&o.ignoreDelimiters&&(Array.isArray(o.ignoreDelimiters)||(o.ignoreDelimiters=[o.ignoreDelimiters]),o.ignoreDelimiters.forEach(function(delimiterPair){delimiterPair.start&&delimiterPair.end&&(reIgnoreStr=escapeRegex(delimiterPair.start)+\"[\\\\s\\\\S]*?\"+escapeRegex(delimiterPair.end),reIgnore=RegExp(reIgnoreStr,\"ig\"),s=s.replace(reIgnore,function(match){return match.replace(/./g,\" \")}))})),lex=new Lexer(s),lex.on(\"warning\",function(ev){warningAt.apply(null,[ev.code,ev.line,ev.character].concat(ev.data))}),lex.on(\"error\",function(ev){errorAt.apply(null,[ev.code,ev.line,ev.character].concat(ev.data))}),lex.on(\"fatal\",function(ev){quit(\"E041\",ev.line,ev.from)}),lex.on(\"Identifier\",function(ev){emitter.emit(\"Identifier\",ev)}),lex.on(\"String\",function(ev){emitter.emit(\"String\",ev)}),lex.on(\"Number\",function(ev){emitter.emit(\"Number\",ev)}),lex.start();for(var name in o)_.has(o,name)&&checkOption(name,state.tokens.curr);assume(),combine(predefined,g||{}),comma.first=!0;try{switch(advance(),state.tokens.next.id){case\"{\":case\"[\":destructuringAssignOrJsonValue();break;default:directives(),state.directive[\"use strict\"]&&\"global\"!==state.option.strict&&warning(\"W097\",state.tokens.prev),statements()}\"(end)\"!==state.tokens.next.id&&quit(\"E041\",state.tokens.curr.line),state.funct[\"(scope)\"].unstack()}catch(err){if(!err||\"JSHintError\"!==err.name)throw err;var nt=state.tokens.next||{};JSHINT.errors.push({scope:\"(main)\",raw:err.raw,code:err.code,reason:err.message,line:err.line||nt.line,character:err.character||nt.from},null)}if(\"(main)\"===JSHINT.scope)for(o=o||{},i=0;JSHINT.internals.length>i;i+=1)k=JSHINT.internals[i],o.scope=k.elem,itself(k.value,o,g);return 0===JSHINT.errors.length};return itself.addModule=function(func){extraModules.push(func)},itself.addModule(style.register),itself.data=function(){var fu,f,i,j,n,globals,data={functions:[],options:state.option};itself.errors.length&&(data.errors=itself.errors),state.jsonMode&&(data.json=!0);var impliedGlobals=state.funct[\"(scope)\"].getImpliedGlobals();for(impliedGlobals.length>0&&(data.implieds=impliedGlobals),urls.length>0&&(data.urls=urls),globals=state.funct[\"(scope)\"].getUsedOrDefinedGlobals(),globals.length>0&&(data.globals=globals),i=1;functions.length>i;i+=1){for(f=functions[i],fu={},j=0;functionicity.length>j;j+=1)fu[functionicity[j]]=[];for(j=0;functionicity.length>j;j+=1)0===fu[functionicity[j]].length&&delete fu[functionicity[j]];fu.name=f[\"(name)\"],fu.param=f[\"(params)\"],fu.line=f[\"(line)\"],fu.character=f[\"(character)\"],fu.last=f[\"(last)\"],fu.lastcharacter=f[\"(lastcharacter)\"],fu.metrics={complexity:f[\"(metrics)\"].ComplexityCount,parameters:f[\"(metrics)\"].arity,statements:f[\"(metrics)\"].statementCount},data.functions.push(fu)}var unuseds=state.funct[\"(scope)\"].getUnuseds();unuseds.length>0&&(data.unused=unuseds);for(n in member)if(\"number\"==typeof member[n]){data.member=member;break}return data},itself.jshint=itself,itself}();\"object\"==typeof exports&&exports&&(exports.JSHINT=JSHINT)},{\"../lodash\":\"/node_modules/jshint/lodash.js\",\"./lex.js\":\"/node_modules/jshint/src/lex.js\",\"./messages.js\":\"/node_modules/jshint/src/messages.js\",\"./options.js\":\"/node_modules/jshint/src/options.js\",\"./reg.js\":\"/node_modules/jshint/src/reg.js\",\"./scope-manager.js\":\"/node_modules/jshint/src/scope-manager.js\",\"./state.js\":\"/node_modules/jshint/src/state.js\",\"./style.js\":\"/node_modules/jshint/src/style.js\",\"./vars.js\":\"/node_modules/jshint/src/vars.js\",events:\"/node_modules/browserify/node_modules/events/events.js\"}],\"/node_modules/jshint/src/lex.js\":[function(_dereq_,module,exports){\"use strict\";function asyncTrigger(){var _checks=[];return{push:function(fn){_checks.push(fn)},check:function(){for(var check=0;_checks.length>check;++check)_checks[check]();_checks.splice(0,_checks.length)}}}function Lexer(source){var lines=source;\"string\"==typeof lines&&(lines=lines.replace(/\\r\\n/g,\"\\n\").replace(/\\r/g,\"\\n\").split(\"\\n\")),lines[0]&&\"#!\"===lines[0].substr(0,2)&&(-1!==lines[0].indexOf(\"node\")&&(state.option.node=!0),lines[0]=\"\"),this.emitter=new events.EventEmitter,this.source=source,this.setLines(lines),this.prereg=!0,this.line=0,this.char=1,this.from=1,this.input=\"\",this.inComment=!1,this.context=[],this.templateStarts=[];for(var i=0;state.option.indent>i;i+=1)state.tab+=\" \";this.ignoreLinterErrors=!1}var _=_dereq_(\"../lodash\"),events=_dereq_(\"events\"),reg=_dereq_(\"./reg.js\"),state=_dereq_(\"./state.js\").state,unicodeData=_dereq_(\"../data/ascii-identifier-data.js\"),asciiIdentifierStartTable=unicodeData.asciiIdentifierStartTable,asciiIdentifierPartTable=unicodeData.asciiIdentifierPartTable,Token={Identifier:1,Punctuator:2,NumericLiteral:3,StringLiteral:4,Comment:5,Keyword:6,NullLiteral:7,BooleanLiteral:8,RegExp:9,TemplateHead:10,TemplateMiddle:11,TemplateTail:12,NoSubstTemplate:13},Context={Block:1,Template:2};Lexer.prototype={_lines:[],inContext:function(ctxType){return this.context.length>0&&this.context[this.context.length-1].type===ctxType},pushContext:function(ctxType){this.context.push({type:ctxType})},popContext:function(){return this.context.pop()},isContext:function(context){return this.context.length>0&&this.context[this.context.length-1]===context},currentContext:function(){return this.context.length>0&&this.context[this.context.length-1]},getLines:function(){return this._lines=state.lines,this._lines},setLines:function(val){this._lines=val,state.lines=this._lines},peek:function(i){return this.input.charAt(i||0)},skip:function(i){i=i||1,this.char+=i,this.input=this.input.slice(i)},on:function(names,listener){names.split(\" \").forEach(function(name){this.emitter.on(name,listener)}.bind(this))},trigger:function(){this.emitter.emit.apply(this.emitter,Array.prototype.slice.call(arguments))},triggerAsync:function(type,args,checks,fn){checks.push(function(){fn()&&this.trigger(type,args)}.bind(this))},scanPunctuator:function(){var ch2,ch3,ch4,ch1=this.peek();switch(ch1){case\".\":if(/^[0-9]$/.test(this.peek(1)))return null;if(\".\"===this.peek(1)&&\".\"===this.peek(2))return{type:Token.Punctuator,value:\"...\"};case\"(\":case\")\":case\";\":case\",\":case\"[\":case\"]\":case\":\":case\"~\":case\"?\":return{type:Token.Punctuator,value:ch1};case\"{\":return this.pushContext(Context.Block),{type:Token.Punctuator,value:ch1};case\"}\":return this.inContext(Context.Block)&&this.popContext(),{type:Token.Punctuator,value:ch1};case\"#\":return{type:Token.Punctuator,value:ch1};case\"\":return null}return ch2=this.peek(1),ch3=this.peek(2),ch4=this.peek(3),\">\"===ch1&&\">\"===ch2&&\">\"===ch3&&\"=\"===ch4?{type:Token.Punctuator,value:\">>>=\"}:\"=\"===ch1&&\"=\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"===\"}:\"!\"===ch1&&\"=\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"!==\"}:\">\"===ch1&&\">\"===ch2&&\">\"===ch3?{type:Token.Punctuator,value:\">>>\"}:\"<\"===ch1&&\"<\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"<<=\"}:\">\"===ch1&&\">\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\">>=\"}:\"=\"===ch1&&\">\"===ch2?{type:Token.Punctuator,value:ch1+ch2}:ch1===ch2&&\"+-<>&|\".indexOf(ch1)>=0?{type:Token.Punctuator,value:ch1+ch2}:\"<>=!+-*%&|^\".indexOf(ch1)>=0?\"=\"===ch2?{type:Token.Punctuator,value:ch1+ch2}:{type:Token.Punctuator,value:ch1}:\"/\"===ch1?\"=\"===ch2?{type:Token.Punctuator,value:\"/=\"}:{type:Token.Punctuator,value:\"/\"}:null},scanComments:function(){function commentToken(label,body,opt){var special=[\"jshint\",\"jslint\",\"members\",\"member\",\"globals\",\"global\",\"exported\"],isSpecial=!1,value=label+body,commentType=\"plain\";return opt=opt||{},opt.isMultiline&&(value+=\"*/\"),body=body.replace(/\\n/g,\" \"),\"/*\"===label&®.fallsThrough.test(body)&&(isSpecial=!0,commentType=\"falls through\"),special.forEach(function(str){if(!isSpecial&&(\"//\"!==label||\"jshint\"===str)&&(\" \"===body.charAt(str.length)&&body.substr(0,str.length)===str&&(isSpecial=!0,label+=str,body=body.substr(str.length)),isSpecial||\" \"!==body.charAt(0)||\" \"!==body.charAt(str.length+1)||body.substr(1,str.length)!==str||(isSpecial=!0,label=label+\" \"+str,body=body.substr(str.length+1)),isSpecial))switch(str){case\"member\":commentType=\"members\";break;case\"global\":commentType=\"globals\";break;default:var options=body.split(\":\").map(function(v){return v.replace(/^\\s+/,\"\").replace(/\\s+$/,\"\")});if(2===options.length)switch(options[0]){case\"ignore\":switch(options[1]){case\"start\":self.ignoringLinterErrors=!0,isSpecial=!1;break;case\"end\":self.ignoringLinterErrors=!1,isSpecial=!1}}commentType=str}}),{type:Token.Comment,commentType:commentType,value:value,body:body,isSpecial:isSpecial,isMultiline:opt.isMultiline||!1,isMalformed:opt.isMalformed||!1}}var ch1=this.peek(),ch2=this.peek(1),rest=this.input.substr(2),startLine=this.line,startChar=this.char,self=this;if(\"*\"===ch1&&\"/\"===ch2)return this.trigger(\"error\",{code:\"E018\",line:startLine,character:startChar}),this.skip(2),null;if(\"/\"!==ch1||\"*\"!==ch2&&\"/\"!==ch2)return null;if(\"/\"===ch2)return this.skip(this.input.length),commentToken(\"//\",rest);var body=\"\";if(\"*\"===ch2){for(this.inComment=!0,this.skip(2);\"*\"!==this.peek()||\"/\"!==this.peek(1);)if(\"\"===this.peek()){if(body+=\"\\n\",!this.nextLine())return this.trigger(\"error\",{code:\"E017\",line:startLine,character:startChar}),this.inComment=!1,commentToken(\"/*\",body,{isMultiline:!0,isMalformed:!0})}else body+=this.peek(),this.skip();return this.skip(2),this.inComment=!1,commentToken(\"/*\",body,{isMultiline:!0})}},scanKeyword:function(){var result=/^[a-zA-Z_$][a-zA-Z0-9_$]*/.exec(this.input),keywords=[\"if\",\"in\",\"do\",\"var\",\"for\",\"new\",\"try\",\"let\",\"this\",\"else\",\"case\",\"void\",\"with\",\"enum\",\"while\",\"break\",\"catch\",\"throw\",\"const\",\"yield\",\"class\",\"super\",\"return\",\"typeof\",\"delete\",\"switch\",\"export\",\"import\",\"default\",\"finally\",\"extends\",\"function\",\"continue\",\"debugger\",\"instanceof\"];return result&&keywords.indexOf(result[0])>=0?{type:Token.Keyword,value:result[0]}:null},scanIdentifier:function(){function isNonAsciiIdentifierStart(code){return code>256}function isNonAsciiIdentifierPart(code){return code>256}function isHexDigit(str){return/^[0-9a-fA-F]$/.test(str)}function removeEscapeSequences(id){return id.replace(/\\\\u([0-9a-fA-F]{4})/g,function(m0,codepoint){return String.fromCharCode(parseInt(codepoint,16))})}var type,char,id=\"\",index=0,readUnicodeEscapeSequence=function(){if(index+=1,\"u\"!==this.peek(index))return null;var code,ch1=this.peek(index+1),ch2=this.peek(index+2),ch3=this.peek(index+3),ch4=this.peek(index+4);return isHexDigit(ch1)&&isHexDigit(ch2)&&isHexDigit(ch3)&&isHexDigit(ch4)?(code=parseInt(ch1+ch2+ch3+ch4,16),asciiIdentifierPartTable[code]||isNonAsciiIdentifierPart(code)?(index+=5,\"\\\\u\"+ch1+ch2+ch3+ch4):null):null}.bind(this),getIdentifierStart=function(){var chr=this.peek(index),code=chr.charCodeAt(0);return 92===code?readUnicodeEscapeSequence():128>code?asciiIdentifierStartTable[code]?(index+=1,chr):null:isNonAsciiIdentifierStart(code)?(index+=1,chr):null}.bind(this),getIdentifierPart=function(){var chr=this.peek(index),code=chr.charCodeAt(0);return 92===code?readUnicodeEscapeSequence():128>code?asciiIdentifierPartTable[code]?(index+=1,chr):null:isNonAsciiIdentifierPart(code)?(index+=1,chr):null}.bind(this);if(char=getIdentifierStart(),null===char)return null;for(id=char;char=getIdentifierPart(),null!==char;)id+=char;switch(id){case\"true\":case\"false\":type=Token.BooleanLiteral;break;case\"null\":type=Token.NullLiteral;break;default:type=Token.Identifier}return{type:type,value:removeEscapeSequences(id),text:id,tokenLength:id.length}},scanNumericLiteral:function(){function isDecimalDigit(str){return/^[0-9]$/.test(str)}function isOctalDigit(str){return/^[0-7]$/.test(str)}function isBinaryDigit(str){return/^[01]$/.test(str)}function isHexDigit(str){return/^[0-9a-fA-F]$/.test(str)}function isIdentifierStart(ch){return\"$\"===ch||\"_\"===ch||\"\\\\\"===ch||ch>=\"a\"&&\"z\">=ch||ch>=\"A\"&&\"Z\">=ch}var bad,index=0,value=\"\",length=this.input.length,char=this.peek(index),isAllowedDigit=isDecimalDigit,base=10,isLegacy=!1;if(\".\"!==char&&!isDecimalDigit(char))return null;if(\".\"!==char){for(value=this.peek(index),index+=1,char=this.peek(index),\"0\"===value&&((\"x\"===char||\"X\"===char)&&(isAllowedDigit=isHexDigit,base=16,index+=1,value+=char),(\"o\"===char||\"O\"===char)&&(isAllowedDigit=isOctalDigit,base=8,state.inES6(!0)||this.trigger(\"warning\",{code:\"W119\",line:this.line,character:this.char,data:[\"Octal integer literal\",\"6\"]}),index+=1,value+=char),(\"b\"===char||\"B\"===char)&&(isAllowedDigit=isBinaryDigit,base=2,state.inES6(!0)||this.trigger(\"warning\",{code:\"W119\",line:this.line,character:this.char,data:[\"Binary integer literal\",\"6\"]}),index+=1,value+=char),isOctalDigit(char)&&(isAllowedDigit=isOctalDigit,base=8,isLegacy=!0,bad=!1,index+=1,value+=char),!isOctalDigit(char)&&isDecimalDigit(char)&&(index+=1,value+=char));length>index;){if(char=this.peek(index),isLegacy&&isDecimalDigit(char))bad=!0;else if(!isAllowedDigit(char))break;value+=char,index+=1}if(isAllowedDigit!==isDecimalDigit)return!isLegacy&&2>=value.length?{type:Token.NumericLiteral,value:value,isMalformed:!0}:length>index&&(char=this.peek(index),isIdentifierStart(char))?null:{type:Token.NumericLiteral,value:value,base:base,isLegacy:isLegacy,isMalformed:!1}}if(\".\"===char)for(value+=char,index+=1;length>index&&(char=this.peek(index),isDecimalDigit(char));)value+=char,index+=1;if(\"e\"===char||\"E\"===char){if(value+=char,index+=1,char=this.peek(index),(\"+\"===char||\"-\"===char)&&(value+=this.peek(index),index+=1),char=this.peek(index),!isDecimalDigit(char))return null;for(value+=char,index+=1;length>index&&(char=this.peek(index),isDecimalDigit(char));)value+=char,index+=1}return length>index&&(char=this.peek(index),isIdentifierStart(char))?null:{type:Token.NumericLiteral,value:value,base:base,isMalformed:!isFinite(value)}},scanEscapeSequence:function(checks){var allowNewLine=!1,jump=1;this.skip();var char=this.peek();switch(char){case\"'\":this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\'\"]},checks,function(){return state.jsonMode});break;case\"b\":char=\"\\\\b\";break;case\"f\":char=\"\\\\f\";break;case\"n\":char=\"\\\\n\";break;case\"r\":char=\"\\\\r\";break;case\"t\":char=\"\\\\t\";break;case\"0\":char=\"\\\\0\";var n=parseInt(this.peek(1),10);this.triggerAsync(\"warning\",{code:\"W115\",line:this.line,character:this.char},checks,function(){return n>=0&&7>=n&&state.isStrict()});break;case\"u\":var hexCode=this.input.substr(1,4),code=parseInt(hexCode,16);isNaN(code)&&this.trigger(\"warning\",{code:\"W052\",line:this.line,character:this.char,data:[\"u\"+hexCode]}),char=String.fromCharCode(code),jump=5;break;case\"v\":this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\v\"]},checks,function(){return state.jsonMode}),char=\"\u000b\";break;case\"x\":var x=parseInt(this.input.substr(1,2),16);this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\x-\"]},checks,function(){return state.jsonMode}),char=String.fromCharCode(x),jump=3;break;case\"\\\\\":char=\"\\\\\\\\\";break;case'\"':char='\\\\\"';break;case\"/\":break;case\"\":allowNewLine=!0,char=\"\"}return{\"char\":char,jump:jump,allowNewLine:allowNewLine}},scanTemplateLiteral:function(checks){var tokenType,ch,value=\"\",startLine=this.line,startChar=this.char,depth=this.templateStarts.length;if(!state.inES6(!0))return null;if(\"`\"===this.peek())tokenType=Token.TemplateHead,this.templateStarts.push({line:this.line,\"char\":this.char}),depth=this.templateStarts.length,this.skip(1),this.pushContext(Context.Template);else{if(!this.inContext(Context.Template)||\"}\"!==this.peek())return null;tokenType=Token.TemplateMiddle}for(;\"`\"!==this.peek();){for(;\"\"===(ch=this.peek());)if(value+=\"\\n\",!this.nextLine()){var startPos=this.templateStarts.pop();return this.trigger(\"error\",{code:\"E052\",line:startPos.line,character:startPos.char}),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!0,depth:depth,context:this.popContext()}}if(\"$\"===ch&&\"{\"===this.peek(1))return value+=\"${\",this.skip(2),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,depth:depth,context:this.currentContext()};\nif(\"\\\\\"===ch){var escape=this.scanEscapeSequence(checks);value+=escape.char,this.skip(escape.jump)}else\"`\"!==ch&&(value+=ch,this.skip(1))}return tokenType=tokenType===Token.TemplateHead?Token.NoSubstTemplate:Token.TemplateTail,this.skip(1),this.templateStarts.pop(),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,depth:depth,context:this.popContext()}},scanStringLiteral:function(checks){var quote=this.peek();if('\"'!==quote&&\"'\"!==quote)return null;this.triggerAsync(\"warning\",{code:\"W108\",line:this.line,character:this.char},checks,function(){return state.jsonMode&&'\"'!==quote});var value=\"\",startLine=this.line,startChar=this.char,allowNewLine=!1;for(this.skip();this.peek()!==quote;)if(\"\"===this.peek()){if(allowNewLine?(allowNewLine=!1,this.triggerAsync(\"warning\",{code:\"W043\",line:this.line,character:this.char},checks,function(){return!state.option.multistr}),this.triggerAsync(\"warning\",{code:\"W042\",line:this.line,character:this.char},checks,function(){return state.jsonMode&&state.option.multistr})):this.trigger(\"warning\",{code:\"W112\",line:this.line,character:this.char}),!this.nextLine())return this.trigger(\"error\",{code:\"E029\",line:startLine,character:startChar}),{type:Token.StringLiteral,value:value,startLine:startLine,startChar:startChar,isUnclosed:!0,quote:quote}}else{allowNewLine=!1;var char=this.peek(),jump=1;if(\" \">char&&this.trigger(\"warning\",{code:\"W113\",line:this.line,character:this.char,data:[\"\"]}),\"\\\\\"===char){var parsed=this.scanEscapeSequence(checks);char=parsed.char,jump=parsed.jump,allowNewLine=parsed.allowNewLine}value+=char,this.skip(jump)}return this.skip(),{type:Token.StringLiteral,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,quote:quote}},scanRegExp:function(){var terminated,index=0,length=this.input.length,char=this.peek(),value=char,body=\"\",flags=[],malformed=!1,isCharSet=!1,scanUnexpectedChars=function(){\" \">char&&(malformed=!0,this.trigger(\"warning\",{code:\"W048\",line:this.line,character:this.char})),\"<\"===char&&(malformed=!0,this.trigger(\"warning\",{code:\"W049\",line:this.line,character:this.char,data:[char]}))}.bind(this);if(!this.prereg||\"/\"!==char)return null;for(index+=1,terminated=!1;length>index;)if(char=this.peek(index),value+=char,body+=char,isCharSet)\"]\"===char&&(\"\\\\\"!==this.peek(index-1)||\"\\\\\"===this.peek(index-2))&&(isCharSet=!1),\"\\\\\"===char&&(index+=1,char=this.peek(index),body+=char,value+=char,scanUnexpectedChars()),index+=1;else{if(\"\\\\\"===char){if(index+=1,char=this.peek(index),body+=char,value+=char,scanUnexpectedChars(),\"/\"===char){index+=1;continue}if(\"[\"===char){index+=1;continue}}if(\"[\"!==char){if(\"/\"===char){body=body.substr(0,body.length-1),terminated=!0,index+=1;break}index+=1}else isCharSet=!0,index+=1}if(!terminated)return this.trigger(\"error\",{code:\"E015\",line:this.line,character:this.from}),void this.trigger(\"fatal\",{line:this.line,from:this.from});for(;length>index&&(char=this.peek(index),/[gim]/.test(char));)flags.push(char),value+=char,index+=1;try{RegExp(body,flags.join(\"\"))}catch(err){malformed=!0,this.trigger(\"error\",{code:\"E016\",line:this.line,character:this.char,data:[err.message]})}return{type:Token.RegExp,value:value,flags:flags,isMalformed:malformed}},scanNonBreakingSpaces:function(){return state.option.nonbsp?this.input.search(/(\\u00A0)/):-1},scanUnsafeChars:function(){return this.input.search(reg.unsafeChars)},next:function(checks){this.from=this.char;var start;if(/\\s/.test(this.peek()))for(start=this.char;/\\s/.test(this.peek());)this.from+=1,this.skip();var match=this.scanComments()||this.scanStringLiteral(checks)||this.scanTemplateLiteral(checks);return match?match:(match=this.scanRegExp()||this.scanPunctuator()||this.scanKeyword()||this.scanIdentifier()||this.scanNumericLiteral(),match?(this.skip(match.tokenLength||match.value.length),match):null)},nextLine:function(){var char;if(this.line>=this.getLines().length)return!1;this.input=this.getLines()[this.line],this.line+=1,this.char=1,this.from=1;var inputTrimmed=this.input.trim(),startsWith=function(){return _.some(arguments,function(prefix){return 0===inputTrimmed.indexOf(prefix)})},endsWith=function(){return _.some(arguments,function(suffix){return-1!==inputTrimmed.indexOf(suffix,inputTrimmed.length-suffix.length)})};if(this.ignoringLinterErrors===!0&&(startsWith(\"/*\",\"//\")||this.inComment&&endsWith(\"*/\")||(this.input=\"\")),char=this.scanNonBreakingSpaces(),char>=0&&this.trigger(\"warning\",{code:\"W125\",line:this.line,character:char+1}),this.input=this.input.replace(/\\t/g,state.tab),char=this.scanUnsafeChars(),char>=0&&this.trigger(\"warning\",{code:\"W100\",line:this.line,character:char}),!this.ignoringLinterErrors&&state.option.maxlen&&state.option.maxlen=0;--i){var scopeLabels=_scopeStack[i][\"(labels)\"];if(scopeLabels[labelName])return scopeLabels}}function usedSoFarInCurrentFunction(labelName){for(var i=_scopeStack.length-1;i>=0;i--){var current=_scopeStack[i];if(current[\"(usages)\"][labelName])return current[\"(usages)\"][labelName];if(current===_currentFunctBody)break}return!1}function _checkOuterShadow(labelName,token){if(\"outer\"===state.option.shadow)for(var isGlobal=\"global\"===_currentFunctBody[\"(type)\"],isNewFunction=\"functionparams\"===_current[\"(type)\"],outsideCurrentFunction=!isGlobal,i=0;_scopeStack.length>i;i++){var stackItem=_scopeStack[i];isNewFunction||_scopeStack[i+1]!==_currentFunctBody||(outsideCurrentFunction=!1),outsideCurrentFunction&&stackItem[\"(labels)\"][labelName]&&warning(\"W123\",token,labelName),stackItem[\"(breakLabels)\"][labelName]&&warning(\"W123\",token,labelName)}}function _latedefWarning(type,labelName,token){state.option.latedef&&(state.option.latedef===!0&&\"function\"===type||\"function\"!==type)&&warning(\"W003\",token,labelName)}var _current,_scopeStack=[];_newScope(\"global\"),_current[\"(predefined)\"]=predefined;var _currentFunctBody=_current,usedPredefinedAndGlobals=Object.create(null),impliedGlobals=Object.create(null),unuseds=[],emitter=new events.EventEmitter,_getUnusedOption=function(unused_opt){return void 0===unused_opt&&(unused_opt=state.option.unused),unused_opt===!0&&(unused_opt=\"last-param\"),unused_opt},_warnUnused=function(name,tkn,type,unused_opt){var line=tkn.line,chr=tkn.from,raw_name=tkn.raw_text||name;unused_opt=_getUnusedOption(unused_opt);var warnable_types={vars:[\"var\"],\"last-param\":[\"var\",\"param\"],strict:[\"var\",\"param\",\"last-param\"]};unused_opt&&warnable_types[unused_opt]&&-1!==warnable_types[unused_opt].indexOf(type)&&warning(\"W098\",{line:line,from:chr},raw_name),(unused_opt||\"var\"===type)&&unuseds.push({name:name,line:line,character:chr})},scopeManagerInst={on:function(names,listener){names.split(\" \").forEach(function(name){emitter.on(name,listener)})},isPredefined:function(labelName){return!this.has(labelName)&&_.has(_scopeStack[0][\"(predefined)\"],labelName)},stack:function(type){var previousScope=_current;_newScope(type),type||\"functionparams\"!==previousScope[\"(type)\"]||(_current[\"(isFuncBody)\"]=!0,_current[\"(context)\"]=_currentFunctBody,_currentFunctBody=_current)},unstack:function(){var i,j,subScope=_scopeStack.length>1?_scopeStack[_scopeStack.length-2]:null,isUnstackingFunctionBody=_current===_currentFunctBody,isUnstackingFunctionParams=\"functionparams\"===_current[\"(type)\"],isUnstackingFunctionOuter=\"functionouter\"===_current[\"(type)\"],currentUsages=_current[\"(usages)\"],currentLabels=_current[\"(labels)\"],usedLabelNameList=Object.keys(currentUsages);for(currentUsages.__proto__&&-1===usedLabelNameList.indexOf(\"__proto__\")&&usedLabelNameList.push(\"__proto__\"),i=0;usedLabelNameList.length>i;i++){var usedLabelName=usedLabelNameList[i],usage=currentUsages[usedLabelName],usedLabel=currentLabels[usedLabelName];if(usedLabel){var usedLabelType=usedLabel[\"(type)\"];if(usedLabel[\"(useOutsideOfScope)\"]&&!state.option.funcscope){var usedTokens=usage[\"(tokens)\"];if(usedTokens)for(j=0;usedTokens.length>j;j++)usedLabel[\"(function)\"]===usedTokens[j][\"(function)\"]&&error(\"W038\",usedTokens[j],usedLabelName)}if(_current[\"(labels)\"][usedLabelName][\"(unused)\"]=!1,\"const\"===usedLabelType&&usage[\"(modified)\"])for(j=0;usage[\"(modified)\"].length>j;j++)error(\"E013\",usage[\"(modified)\"][j],usedLabelName);if((\"function\"===usedLabelType||\"class\"===usedLabelType)&&usage[\"(reassigned)\"])for(j=0;usage[\"(reassigned)\"].length>j;j++)error(\"W021\",usage[\"(reassigned)\"][j],usedLabelName,usedLabelType)}else if(isUnstackingFunctionOuter&&(state.funct[\"(isCapturing)\"]=!0),subScope)if(subScope[\"(usages)\"][usedLabelName]){var subScopeUsage=subScope[\"(usages)\"][usedLabelName];subScopeUsage[\"(modified)\"]=subScopeUsage[\"(modified)\"].concat(usage[\"(modified)\"]),subScopeUsage[\"(tokens)\"]=subScopeUsage[\"(tokens)\"].concat(usage[\"(tokens)\"]),subScopeUsage[\"(reassigned)\"]=subScopeUsage[\"(reassigned)\"].concat(usage[\"(reassigned)\"]),subScopeUsage[\"(onlyUsedSubFunction)\"]=!1}else subScope[\"(usages)\"][usedLabelName]=usage,isUnstackingFunctionBody&&(subScope[\"(usages)\"][usedLabelName][\"(onlyUsedSubFunction)\"]=!0);else if(\"boolean\"==typeof _current[\"(predefined)\"][usedLabelName]){if(delete declared[usedLabelName],usedPredefinedAndGlobals[usedLabelName]=marker,_current[\"(predefined)\"][usedLabelName]===!1&&usage[\"(reassigned)\"])for(j=0;usage[\"(reassigned)\"].length>j;j++)warning(\"W020\",usage[\"(reassigned)\"][j])}else if(usage[\"(tokens)\"])for(j=0;usage[\"(tokens)\"].length>j;j++){var undefinedToken=usage[\"(tokens)\"][j];undefinedToken.forgiveUndef||(state.option.undef&&!undefinedToken.ignoreUndef&&warning(\"W117\",undefinedToken,usedLabelName),impliedGlobals[usedLabelName]?impliedGlobals[usedLabelName].line.push(undefinedToken.line):impliedGlobals[usedLabelName]={name:usedLabelName,line:[undefinedToken.line]})}}if(subScope||Object.keys(declared).forEach(function(labelNotUsed){_warnUnused(labelNotUsed,declared[labelNotUsed],\"var\")}),subScope&&!isUnstackingFunctionBody&&!isUnstackingFunctionParams&&!isUnstackingFunctionOuter){var labelNames=Object.keys(currentLabels);for(i=0;labelNames.length>i;i++){var defLabelName=labelNames[i];currentLabels[defLabelName][\"(blockscoped)\"]||\"exception\"===currentLabels[defLabelName][\"(type)\"]||this.funct.has(defLabelName,{excludeCurrent:!0})||(subScope[\"(labels)\"][defLabelName]=currentLabels[defLabelName],\"global\"!==_currentFunctBody[\"(type)\"]&&(subScope[\"(labels)\"][defLabelName][\"(useOutsideOfScope)\"]=!0),delete currentLabels[defLabelName])}}_checkForUnused(),_scopeStack.pop(),isUnstackingFunctionBody&&(_currentFunctBody=_scopeStack[_.findLastIndex(_scopeStack,function(scope){return scope[\"(isFuncBody)\"]||\"global\"===scope[\"(type)\"]})]),_current=subScope},addParam:function(labelName,token,type){if(type=type||\"param\",\"exception\"===type){var previouslyDefinedLabelType=this.funct.labeltype(labelName);previouslyDefinedLabelType&&\"exception\"!==previouslyDefinedLabelType&&(state.option.node||warning(\"W002\",state.tokens.next,labelName))}if(_.has(_current[\"(labels)\"],labelName)?_current[\"(labels)\"][labelName].duplicated=!0:(_checkOuterShadow(labelName,token,type),_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":token,\"(unused)\":!0},_current[\"(params)\"].push(labelName)),_.has(_current[\"(usages)\"],labelName)){var usage=_current[\"(usages)\"][labelName];usage[\"(onlyUsedSubFunction)\"]?_latedefWarning(type,labelName,token):warning(\"E056\",token,labelName,type)}},validateParams:function(){if(\"global\"!==_currentFunctBody[\"(type)\"]){var isStrict=state.isStrict(),currentFunctParamScope=_currentFunctBody[\"(parent)\"];currentFunctParamScope[\"(params)\"]&¤tFunctParamScope[\"(params)\"].forEach(function(labelName){var label=currentFunctParamScope[\"(labels)\"][labelName];label&&label.duplicated&&(isStrict?warning(\"E011\",label[\"(token)\"],labelName):state.option.shadow!==!0&&warning(\"W004\",label[\"(token)\"],labelName))})}},getUsedOrDefinedGlobals:function(){var list=Object.keys(usedPredefinedAndGlobals);return usedPredefinedAndGlobals.__proto__===marker&&-1===list.indexOf(\"__proto__\")&&list.push(\"__proto__\"),list},getImpliedGlobals:function(){var values=_.values(impliedGlobals),hasProto=!1;return impliedGlobals.__proto__&&(hasProto=values.some(function(value){return\"__proto__\"===value.name}),hasProto||values.push(impliedGlobals.__proto__)),values},getUnuseds:function(){return unuseds},has:function(labelName){return Boolean(_getLabel(labelName))},labeltype:function(labelName){var scopeLabels=_getLabel(labelName);return scopeLabels?scopeLabels[labelName][\"(type)\"]:null},addExported:function(labelName){var globalLabels=_scopeStack[0][\"(labels)\"];if(_.has(declared,labelName))delete declared[labelName];else if(_.has(globalLabels,labelName))globalLabels[labelName][\"(unused)\"]=!1;else{for(var i=1;_scopeStack.length>i;i++){var scope=_scopeStack[i];if(scope[\"(type)\"])break;if(_.has(scope[\"(labels)\"],labelName)&&!scope[\"(labels)\"][labelName][\"(blockscoped)\"])return scope[\"(labels)\"][labelName][\"(unused)\"]=!1,void 0}exported[labelName]=!0}},setExported:function(labelName,token){this.block.use(labelName,token)\n},addlabel:function(labelName,opts){var type=opts.type,token=opts.token,isblockscoped=\"let\"===type||\"const\"===type||\"class\"===type,isexported=\"global\"===(isblockscoped?_current:_currentFunctBody)[\"(type)\"]&&_.has(exported,labelName);if(_checkOuterShadow(labelName,token,type),isblockscoped){var declaredInCurrentScope=_current[\"(labels)\"][labelName];if(declaredInCurrentScope||_current!==_currentFunctBody||\"global\"===_current[\"(type)\"]||(declaredInCurrentScope=!!_currentFunctBody[\"(parent)\"][\"(labels)\"][labelName]),!declaredInCurrentScope&&_current[\"(usages)\"][labelName]){var usage=_current[\"(usages)\"][labelName];usage[\"(onlyUsedSubFunction)\"]?_latedefWarning(type,labelName,token):warning(\"E056\",token,labelName,type)}declaredInCurrentScope?warning(\"E011\",token,labelName):\"outer\"===state.option.shadow&&scopeManagerInst.funct.has(labelName)&&warning(\"W004\",token,labelName),scopeManagerInst.block.add(labelName,type,token,!isexported)}else{var declaredInCurrentFunctionScope=scopeManagerInst.funct.has(labelName);!declaredInCurrentFunctionScope&&usedSoFarInCurrentFunction(labelName)&&_latedefWarning(type,labelName,token),scopeManagerInst.funct.has(labelName,{onlyBlockscoped:!0})?warning(\"E011\",token,labelName):state.option.shadow!==!0&&declaredInCurrentFunctionScope&&\"__proto__\"!==labelName&&\"global\"!==_currentFunctBody[\"(type)\"]&&warning(\"W004\",token,labelName),scopeManagerInst.funct.add(labelName,type,token,!isexported),\"global\"===_currentFunctBody[\"(type)\"]&&(usedPredefinedAndGlobals[labelName]=marker)}},funct:{labeltype:function(labelName,options){for(var onlyBlockscoped=options&&options.onlyBlockscoped,excludeParams=options&&options.excludeParams,currentScopeIndex=_scopeStack.length-(options&&options.excludeCurrent?2:1),i=currentScopeIndex;i>=0;i--){var current=_scopeStack[i];if(current[\"(labels)\"][labelName]&&(!onlyBlockscoped||current[\"(labels)\"][labelName][\"(blockscoped)\"]))return current[\"(labels)\"][labelName][\"(type)\"];var scopeCheck=excludeParams?_scopeStack[i-1]:current;if(scopeCheck&&\"functionparams\"===scopeCheck[\"(type)\"])return null}return null},hasBreakLabel:function(labelName){for(var i=_scopeStack.length-1;i>=0;i--){var current=_scopeStack[i];if(current[\"(breakLabels)\"][labelName])return!0;if(\"functionparams\"===current[\"(type)\"])return!1}return!1},has:function(labelName,options){return Boolean(this.labeltype(labelName,options))},add:function(labelName,type,tok,unused){_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":tok,\"(blockscoped)\":!1,\"(function)\":_currentFunctBody,\"(unused)\":unused}}},block:{isGlobal:function(){return\"global\"===_current[\"(type)\"]},use:function(labelName,token){var paramScope=_currentFunctBody[\"(parent)\"];paramScope&¶mScope[\"(labels)\"][labelName]&&\"param\"===paramScope[\"(labels)\"][labelName][\"(type)\"]&&(scopeManagerInst.funct.has(labelName,{excludeParams:!0,onlyBlockscoped:!0})||(paramScope[\"(labels)\"][labelName][\"(unused)\"]=!1)),token&&(state.ignored.W117||state.option.undef===!1)&&(token.ignoreUndef=!0),_setupUsages(labelName),token&&(token[\"(function)\"]=_currentFunctBody,_current[\"(usages)\"][labelName][\"(tokens)\"].push(token))},reassign:function(labelName,token){this.modify(labelName,token),_current[\"(usages)\"][labelName][\"(reassigned)\"].push(token)},modify:function(labelName,token){_setupUsages(labelName),_current[\"(usages)\"][labelName][\"(modified)\"].push(token)},add:function(labelName,type,tok,unused){_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":tok,\"(blockscoped)\":!0,\"(unused)\":unused}},addBreakLabel:function(labelName,opts){var token=opts.token;scopeManagerInst.funct.hasBreakLabel(labelName)?warning(\"E011\",token,labelName):\"outer\"===state.option.shadow&&(scopeManagerInst.funct.has(labelName)?warning(\"W004\",token,labelName):_checkOuterShadow(labelName,token)),_current[\"(breakLabels)\"][labelName]=token}}};return scopeManagerInst};module.exports=scopeManager},{\"../lodash\":\"/node_modules/jshint/lodash.js\",events:\"/node_modules/browserify/node_modules/events/events.js\"}],\"/node_modules/jshint/src/state.js\":[function(_dereq_,module,exports){\"use strict\";var NameStack=_dereq_(\"./name-stack.js\"),state={syntax:{},isStrict:function(){return this.directive[\"use strict\"]||this.inClassBody||this.option.module||\"implied\"===this.option.strict},inMoz:function(){return this.option.moz},inES6:function(){return this.option.moz||this.option.esversion>=6},inES5:function(strict){return strict?!(this.option.esversion&&5!==this.option.esversion||this.option.moz):!this.option.esversion||this.option.esversion>=5||this.option.moz},reset:function(){this.tokens={prev:null,next:null,curr:null},this.option={},this.funct=null,this.ignored={},this.directive={},this.jsonMode=!1,this.jsonWarnings=[],this.lines=[],this.tab=\"\",this.cache={},this.ignoredLines={},this.forinifcheckneeded=!1,this.nameStack=new NameStack,this.inClassBody=!1}};exports.state=state},{\"./name-stack.js\":\"/node_modules/jshint/src/name-stack.js\"}],\"/node_modules/jshint/src/style.js\":[function(_dereq_,module,exports){\"use strict\";exports.register=function(linter){linter.on(\"Identifier\",function(data){linter.getOption(\"proto\")||\"__proto__\"===data.name&&linter.warn(\"W103\",{line:data.line,\"char\":data.char,data:[data.name,\"6\"]})}),linter.on(\"Identifier\",function(data){linter.getOption(\"iterator\")||\"__iterator__\"===data.name&&linter.warn(\"W103\",{line:data.line,\"char\":data.char,data:[data.name]})}),linter.on(\"Identifier\",function(data){linter.getOption(\"camelcase\")&&data.name.replace(/^_+|_+$/g,\"\").indexOf(\"_\")>-1&&!data.name.match(/^[A-Z0-9_]*$/)&&linter.warn(\"W106\",{line:data.line,\"char\":data.from,data:[data.name]})}),linter.on(\"String\",function(data){var code,quotmark=linter.getOption(\"quotmark\");quotmark&&(\"single\"===quotmark&&\"'\"!==data.quote&&(code=\"W109\"),\"double\"===quotmark&&'\"'!==data.quote&&(code=\"W108\"),quotmark===!0&&(linter.getCache(\"quotmark\")||linter.setCache(\"quotmark\",data.quote),linter.getCache(\"quotmark\")!==data.quote&&(code=\"W110\")),code&&linter.warn(code,{line:data.line,\"char\":data.char}))}),linter.on(\"Number\",function(data){\".\"===data.value.charAt(0)&&linter.warn(\"W008\",{line:data.line,\"char\":data.char,data:[data.value]}),\".\"===data.value.substr(data.value.length-1)&&linter.warn(\"W047\",{line:data.line,\"char\":data.char,data:[data.value]}),/^00+/.test(data.value)&&linter.warn(\"W046\",{line:data.line,\"char\":data.char,data:[data.value]})}),linter.on(\"String\",function(data){var re=/^(?:javascript|jscript|ecmascript|vbscript|livescript)\\s*:/i;linter.getOption(\"scripturl\")||re.test(data.value)&&linter.warn(\"W107\",{line:data.line,\"char\":data.char})})}},{}],\"/node_modules/jshint/src/vars.js\":[function(_dereq_,module,exports){\"use strict\";exports.reservedVars={arguments:!1,NaN:!1},exports.ecmaIdentifiers={3:{Array:!1,Boolean:!1,Date:!1,decodeURI:!1,decodeURIComponent:!1,encodeURI:!1,encodeURIComponent:!1,Error:!1,eval:!1,EvalError:!1,Function:!1,hasOwnProperty:!1,isFinite:!1,isNaN:!1,Math:!1,Number:!1,Object:!1,parseInt:!1,parseFloat:!1,RangeError:!1,ReferenceError:!1,RegExp:!1,String:!1,SyntaxError:!1,TypeError:!1,URIError:!1},5:{JSON:!1},6:{Map:!1,Promise:!1,Proxy:!1,Reflect:!1,Set:!1,Symbol:!1,WeakMap:!1,WeakSet:!1}},exports.browser={Audio:!1,Blob:!1,addEventListener:!1,applicationCache:!1,atob:!1,blur:!1,btoa:!1,cancelAnimationFrame:!1,CanvasGradient:!1,CanvasPattern:!1,CanvasRenderingContext2D:!1,CSS:!1,clearInterval:!1,clearTimeout:!1,close:!1,closed:!1,Comment:!1,CustomEvent:!1,DOMParser:!1,defaultStatus:!1,Document:!1,document:!1,DocumentFragment:!1,Element:!1,ElementTimeControl:!1,Event:!1,event:!1,fetch:!1,FileReader:!1,FormData:!1,focus:!1,frames:!1,getComputedStyle:!1,HTMLElement:!1,HTMLAnchorElement:!1,HTMLBaseElement:!1,HTMLBlockquoteElement:!1,HTMLBodyElement:!1,HTMLBRElement:!1,HTMLButtonElement:!1,HTMLCanvasElement:!1,HTMLCollection:!1,HTMLDirectoryElement:!1,HTMLDivElement:!1,HTMLDListElement:!1,HTMLFieldSetElement:!1,HTMLFontElement:!1,HTMLFormElement:!1,HTMLFrameElement:!1,HTMLFrameSetElement:!1,HTMLHeadElement:!1,HTMLHeadingElement:!1,HTMLHRElement:!1,HTMLHtmlElement:!1,HTMLIFrameElement:!1,HTMLImageElement:!1,HTMLInputElement:!1,HTMLIsIndexElement:!1,HTMLLabelElement:!1,HTMLLayerElement:!1,HTMLLegendElement:!1,HTMLLIElement:!1,HTMLLinkElement:!1,HTMLMapElement:!1,HTMLMenuElement:!1,HTMLMetaElement:!1,HTMLModElement:!1,HTMLObjectElement:!1,HTMLOListElement:!1,HTMLOptGroupElement:!1,HTMLOptionElement:!1,HTMLParagraphElement:!1,HTMLParamElement:!1,HTMLPreElement:!1,HTMLQuoteElement:!1,HTMLScriptElement:!1,HTMLSelectElement:!1,HTMLStyleElement:!1,HTMLTableCaptionElement:!1,HTMLTableCellElement:!1,HTMLTableColElement:!1,HTMLTableElement:!1,HTMLTableRowElement:!1,HTMLTableSectionElement:!1,HTMLTemplateElement:!1,HTMLTextAreaElement:!1,HTMLTitleElement:!1,HTMLUListElement:!1,HTMLVideoElement:!1,history:!1,Image:!1,Intl:!1,length:!1,localStorage:!1,location:!1,matchMedia:!1,MessageChannel:!1,MessageEvent:!1,MessagePort:!1,MouseEvent:!1,moveBy:!1,moveTo:!1,MutationObserver:!1,name:!1,Node:!1,NodeFilter:!1,NodeList:!1,Notification:!1,navigator:!1,onbeforeunload:!0,onblur:!0,onerror:!0,onfocus:!0,onload:!0,onresize:!0,onunload:!0,open:!1,openDatabase:!1,opener:!1,Option:!1,parent:!1,performance:!1,print:!1,Range:!1,requestAnimationFrame:!1,removeEventListener:!1,resizeBy:!1,resizeTo:!1,screen:!1,scroll:!1,scrollBy:!1,scrollTo:!1,sessionStorage:!1,setInterval:!1,setTimeout:!1,SharedWorker:!1,status:!1,SVGAElement:!1,SVGAltGlyphDefElement:!1,SVGAltGlyphElement:!1,SVGAltGlyphItemElement:!1,SVGAngle:!1,SVGAnimateColorElement:!1,SVGAnimateElement:!1,SVGAnimateMotionElement:!1,SVGAnimateTransformElement:!1,SVGAnimatedAngle:!1,SVGAnimatedBoolean:!1,SVGAnimatedEnumeration:!1,SVGAnimatedInteger:!1,SVGAnimatedLength:!1,SVGAnimatedLengthList:!1,SVGAnimatedNumber:!1,SVGAnimatedNumberList:!1,SVGAnimatedPathData:!1,SVGAnimatedPoints:!1,SVGAnimatedPreserveAspectRatio:!1,SVGAnimatedRect:!1,SVGAnimatedString:!1,SVGAnimatedTransformList:!1,SVGAnimationElement:!1,SVGCSSRule:!1,SVGCircleElement:!1,SVGClipPathElement:!1,SVGColor:!1,SVGColorProfileElement:!1,SVGColorProfileRule:!1,SVGComponentTransferFunctionElement:!1,SVGCursorElement:!1,SVGDefsElement:!1,SVGDescElement:!1,SVGDocument:!1,SVGElement:!1,SVGElementInstance:!1,SVGElementInstanceList:!1,SVGEllipseElement:!1,SVGExternalResourcesRequired:!1,SVGFEBlendElement:!1,SVGFEColorMatrixElement:!1,SVGFEComponentTransferElement:!1,SVGFECompositeElement:!1,SVGFEConvolveMatrixElement:!1,SVGFEDiffuseLightingElement:!1,SVGFEDisplacementMapElement:!1,SVGFEDistantLightElement:!1,SVGFEFloodElement:!1,SVGFEFuncAElement:!1,SVGFEFuncBElement:!1,SVGFEFuncGElement:!1,SVGFEFuncRElement:!1,SVGFEGaussianBlurElement:!1,SVGFEImageElement:!1,SVGFEMergeElement:!1,SVGFEMergeNodeElement:!1,SVGFEMorphologyElement:!1,SVGFEOffsetElement:!1,SVGFEPointLightElement:!1,SVGFESpecularLightingElement:!1,SVGFESpotLightElement:!1,SVGFETileElement:!1,SVGFETurbulenceElement:!1,SVGFilterElement:!1,SVGFilterPrimitiveStandardAttributes:!1,SVGFitToViewBox:!1,SVGFontElement:!1,SVGFontFaceElement:!1,SVGFontFaceFormatElement:!1,SVGFontFaceNameElement:!1,SVGFontFaceSrcElement:!1,SVGFontFaceUriElement:!1,SVGForeignObjectElement:!1,SVGGElement:!1,SVGGlyphElement:!1,SVGGlyphRefElement:!1,SVGGradientElement:!1,SVGHKernElement:!1,SVGICCColor:!1,SVGImageElement:!1,SVGLangSpace:!1,SVGLength:!1,SVGLengthList:!1,SVGLineElement:!1,SVGLinearGradientElement:!1,SVGLocatable:!1,SVGMPathElement:!1,SVGMarkerElement:!1,SVGMaskElement:!1,SVGMatrix:!1,SVGMetadataElement:!1,SVGMissingGlyphElement:!1,SVGNumber:!1,SVGNumberList:!1,SVGPaint:!1,SVGPathElement:!1,SVGPathSeg:!1,SVGPathSegArcAbs:!1,SVGPathSegArcRel:!1,SVGPathSegClosePath:!1,SVGPathSegCurvetoCubicAbs:!1,SVGPathSegCurvetoCubicRel:!1,SVGPathSegCurvetoCubicSmoothAbs:!1,SVGPathSegCurvetoCubicSmoothRel:!1,SVGPathSegCurvetoQuadraticAbs:!1,SVGPathSegCurvetoQuadraticRel:!1,SVGPathSegCurvetoQuadraticSmoothAbs:!1,SVGPathSegCurvetoQuadraticSmoothRel:!1,SVGPathSegLinetoAbs:!1,SVGPathSegLinetoHorizontalAbs:!1,SVGPathSegLinetoHorizontalRel:!1,SVGPathSegLinetoRel:!1,SVGPathSegLinetoVerticalAbs:!1,SVGPathSegLinetoVerticalRel:!1,SVGPathSegList:!1,SVGPathSegMovetoAbs:!1,SVGPathSegMovetoRel:!1,SVGPatternElement:!1,SVGPoint:!1,SVGPointList:!1,SVGPolygonElement:!1,SVGPolylineElement:!1,SVGPreserveAspectRatio:!1,SVGRadialGradientElement:!1,SVGRect:!1,SVGRectElement:!1,SVGRenderingIntent:!1,SVGSVGElement:!1,SVGScriptElement:!1,SVGSetElement:!1,SVGStopElement:!1,SVGStringList:!1,SVGStylable:!1,SVGStyleElement:!1,SVGSwitchElement:!1,SVGSymbolElement:!1,SVGTRefElement:!1,SVGTSpanElement:!1,SVGTests:!1,SVGTextContentElement:!1,SVGTextElement:!1,SVGTextPathElement:!1,SVGTextPositioningElement:!1,SVGTitleElement:!1,SVGTransform:!1,SVGTransformList:!1,SVGTransformable:!1,SVGURIReference:!1,SVGUnitTypes:!1,SVGUseElement:!1,SVGVKernElement:!1,SVGViewElement:!1,SVGViewSpec:!1,SVGZoomAndPan:!1,Text:!1,TextDecoder:!1,TextEncoder:!1,TimeEvent:!1,top:!1,URL:!1,WebGLActiveInfo:!1,WebGLBuffer:!1,WebGLContextEvent:!1,WebGLFramebuffer:!1,WebGLProgram:!1,WebGLRenderbuffer:!1,WebGLRenderingContext:!1,WebGLShader:!1,WebGLShaderPrecisionFormat:!1,WebGLTexture:!1,WebGLUniformLocation:!1,WebSocket:!1,window:!1,Window:!1,Worker:!1,XDomainRequest:!1,XMLHttpRequest:!1,XMLSerializer:!1,XPathEvaluator:!1,XPathException:!1,XPathExpression:!1,XPathNamespace:!1,XPathNSResolver:!1,XPathResult:!1},exports.devel={alert:!1,confirm:!1,console:!1,Debug:!1,opera:!1,prompt:!1},exports.worker={importScripts:!0,postMessage:!0,self:!0,FileReaderSync:!0},exports.nonstandard={escape:!1,unescape:!1},exports.couch={require:!1,respond:!1,getRow:!1,emit:!1,send:!1,start:!1,sum:!1,log:!1,exports:!1,module:!1,provides:!1},exports.node={__filename:!1,__dirname:!1,GLOBAL:!1,global:!1,module:!1,acequire:!1,Buffer:!0,console:!0,exports:!0,process:!0,setTimeout:!0,clearTimeout:!0,setInterval:!0,clearInterval:!0,setImmediate:!0,clearImmediate:!0},exports.browserify={__filename:!1,__dirname:!1,global:!1,module:!1,acequire:!1,Buffer:!0,exports:!0,process:!0},exports.phantom={phantom:!0,acequire:!0,WebPage:!0,console:!0,exports:!0},exports.qunit={asyncTest:!1,deepEqual:!1,equal:!1,expect:!1,module:!1,notDeepEqual:!1,notEqual:!1,notPropEqual:!1,notStrictEqual:!1,ok:!1,propEqual:!1,QUnit:!1,raises:!1,start:!1,stop:!1,strictEqual:!1,test:!1,\"throws\":!1},exports.rhino={defineClass:!1,deserialize:!1,gc:!1,help:!1,importClass:!1,importPackage:!1,java:!1,load:!1,loadClass:!1,Packages:!1,print:!1,quit:!1,readFile:!1,readUrl:!1,runCommand:!1,seal:!1,serialize:!1,spawn:!1,sync:!1,toint32:!1,version:!1},exports.shelljs={target:!1,echo:!1,exit:!1,cd:!1,pwd:!1,ls:!1,find:!1,cp:!1,rm:!1,mv:!1,mkdir:!1,test:!1,cat:!1,sed:!1,grep:!1,which:!1,dirs:!1,pushd:!1,popd:!1,env:!1,exec:!1,chmod:!1,config:!1,error:!1,tempdir:!1},exports.typed={ArrayBuffer:!1,ArrayBufferView:!1,DataView:!1,Float32Array:!1,Float64Array:!1,Int16Array:!1,Int32Array:!1,Int8Array:!1,Uint16Array:!1,Uint32Array:!1,Uint8Array:!1,Uint8ClampedArray:!1},exports.wsh={ActiveXObject:!0,Enumerator:!0,GetObject:!0,ScriptEngine:!0,ScriptEngineBuildVersion:!0,ScriptEngineMajorVersion:!0,ScriptEngineMinorVersion:!0,VBArray:!0,WSH:!0,WScript:!0,XDomainRequest:!0},exports.dojo={dojo:!1,dijit:!1,dojox:!1,define:!1,require:!1},exports.jquery={$:!1,jQuery:!1},exports.mootools={$:!1,$$:!1,Asset:!1,Browser:!1,Chain:!1,Class:!1,Color:!1,Cookie:!1,Core:!1,Document:!1,DomReady:!1,DOMEvent:!1,DOMReady:!1,Drag:!1,Element:!1,Elements:!1,Event:!1,Events:!1,Fx:!1,Group:!1,Hash:!1,HtmlTable:!1,IFrame:!1,IframeShim:!1,InputValidator:!1,instanceOf:!1,Keyboard:!1,Locale:!1,Mask:!1,MooTools:!1,Native:!1,Options:!1,OverText:!1,Request:!1,Scroller:!1,Slick:!1,Slider:!1,Sortables:!1,Spinner:!1,Swiff:!1,Tips:!1,Type:!1,typeOf:!1,URI:!1,Window:!1},exports.prototypejs={$:!1,$$:!1,$A:!1,$F:!1,$H:!1,$R:!1,$break:!1,$continue:!1,$w:!1,Abstract:!1,Ajax:!1,Class:!1,Enumerable:!1,Element:!1,Event:!1,Field:!1,Form:!1,Hash:!1,Insertion:!1,ObjectRange:!1,PeriodicalExecuter:!1,Position:!1,Prototype:!1,Selector:!1,Template:!1,Toggle:!1,Try:!1,Autocompleter:!1,Builder:!1,Control:!1,Draggable:!1,Draggables:!1,Droppables:!1,Effect:!1,Sortable:!1,SortableObserver:!1,Sound:!1,Scriptaculous:!1},exports.yui={YUI:!1,Y:!1,YUI_config:!1},exports.mocha={mocha:!1,describe:!1,xdescribe:!1,it:!1,xit:!1,context:!1,xcontext:!1,before:!1,after:!1,beforeEach:!1,afterEach:!1,suite:!1,test:!1,setup:!1,teardown:!1,suiteSetup:!1,suiteTeardown:!1},exports.jasmine={jasmine:!1,describe:!1,xdescribe:!1,it:!1,xit:!1,beforeEach:!1,afterEach:!1,setFixtures:!1,loadFixtures:!1,spyOn:!1,expect:!1,runs:!1,waitsFor:!1,waits:!1,beforeAll:!1,afterAll:!1,fail:!1,fdescribe:!1,fit:!1,pending:!1}},{}]},{},[\"/node_modules/jshint/src/jshint.js\"])}),ace.define(\"ace/mode/javascript_worker\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/worker/mirror\",\"ace/mode/javascript/jshint\"],function(acequire,exports,module){\"use strict\";function startRegex(arr){return RegExp(\"^(\"+arr.join(\"|\")+\")\")}var oop=acequire(\"../lib/oop\"),Mirror=acequire(\"../worker/mirror\").Mirror,lint=acequire(\"./javascript/jshint\").JSHINT,disabledWarningsRe=startRegex([\"Bad for in variable '(.+)'.\",'Missing \"use strict\"']),errorsRe=startRegex([\"Unexpected\",\"Expected \",\"Confusing (plus|minus)\",\"\\\\{a\\\\} unterminated regular expression\",\"Unclosed \",\"Unmatched \",\"Unbegun comment\",\"Bad invocation\",\"Missing space after\",\"Missing operator at\"]),infoRe=startRegex([\"Expected an assignment\",\"Bad escapement of EOL\",\"Unexpected comma\",\"Unexpected space\",\"Missing radix parameter.\",\"A leading decimal point can\",\"\\\\['{a}'\\\\] is better written in dot notation.\",\"'{a}' used out of scope\"]),JavaScriptWorker=exports.JavaScriptWorker=function(sender){Mirror.call(this,sender),this.setTimeout(500),this.setOptions()};oop.inherits(JavaScriptWorker,Mirror),function(){this.setOptions=function(options){this.options=options||{esnext:!0,moz:!0,devel:!0,browser:!0,node:!0,laxcomma:!0,laxbreak:!0,lastsemic:!0,onevar:!1,passfail:!1,maxerr:100,expr:!0,multistr:!0,globalstrict:!0},this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.changeOptions=function(newOptions){oop.mixin(this.options,newOptions),this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.isValidJS=function(str){try{eval(\"throw 0;\"+str)}catch(e){if(0===e)return!0}return!1},this.onUpdate=function(){var value=this.doc.getValue();if(value=value.replace(/^#!.*\\n/,\"\\n\"),!value)return this.sender.emit(\"annotate\",[]);var errors=[],maxErrorLevel=this.isValidJS(value)?\"warning\":\"error\";lint(value,this.options,this.options.globals);for(var results=lint.errors,errorAdded=!1,i=0;results.length>i;i++){var error=results[i];if(error){var raw=error.raw,type=\"warning\";if(\"Missing semicolon.\"==raw){var str=error.evidence.substr(error.character);str=str.charAt(str.search(/\\S/)),\"error\"==maxErrorLevel&&str&&/[\\w\\d{(['\"]/.test(str)?(error.reason='Missing \";\" before statement',type=\"error\"):type=\"info\"}else{if(disabledWarningsRe.test(raw))continue;infoRe.test(raw)?type=\"info\":errorsRe.test(raw)?(errorAdded=!0,type=maxErrorLevel):\"'{a}' is not defined.\"==raw?type=\"warning\":\"'{a}' is defined but never used.\"==raw&&(type=\"info\")}errors.push({row:error.line-1,column:error.character-1,text:error.reason,type:type,raw:raw})}}this.sender.emit(\"annotate\",errors)}}.call(JavaScriptWorker.prototype)}),ace.define(\"ace/lib/es5-shim\",[\"require\",\"exports\",\"module\"],function(){function Empty(){}function doesDefinePropertyWork(object){try{return Object.defineProperty(object,\"sentinel\",{}),\"sentinel\"in object}catch(exception){}}function toInteger(n){return n=+n,n!==n?n=0:0!==n&&n!==1/0&&n!==-(1/0)&&(n=(n>0||-1)*Math.floor(Math.abs(n))),n}Function.prototype.bind||(Function.prototype.bind=function(that){var target=this;if(\"function\"!=typeof target)throw new TypeError(\"Function.prototype.bind called on incompatible \"+target);var args=slice.call(arguments,1),bound=function(){if(this instanceof bound){var result=target.apply(this,args.concat(slice.call(arguments)));return Object(result)===result?result:this}return target.apply(that,args.concat(slice.call(arguments)))};return target.prototype&&(Empty.prototype=target.prototype,bound.prototype=new Empty,Empty.prototype=null),bound});var defineGetter,defineSetter,lookupGetter,lookupSetter,supportsAccessors,call=Function.prototype.call,prototypeOfArray=Array.prototype,prototypeOfObject=Object.prototype,slice=prototypeOfArray.slice,_toString=call.bind(prototypeOfObject.toString),owns=call.bind(prototypeOfObject.hasOwnProperty);if((supportsAccessors=owns(prototypeOfObject,\"__defineGetter__\"))&&(defineGetter=call.bind(prototypeOfObject.__defineGetter__),defineSetter=call.bind(prototypeOfObject.__defineSetter__),lookupGetter=call.bind(prototypeOfObject.__lookupGetter__),lookupSetter=call.bind(prototypeOfObject.__lookupSetter__)),2!=[1,2].splice(0).length)if(function(){function makeArray(l){var a=Array(l+2);return a[0]=a[1]=0,a}var lengthBefore,array=[];return array.splice.apply(array,makeArray(20)),array.splice.apply(array,makeArray(26)),lengthBefore=array.length,array.splice(5,0,\"XXX\"),lengthBefore+1==array.length,lengthBefore+1==array.length?!0:void 0}()){var array_splice=Array.prototype.splice;Array.prototype.splice=function(start,deleteCount){return arguments.length?array_splice.apply(this,[void 0===start?0:start,void 0===deleteCount?this.length-start:deleteCount].concat(slice.call(arguments,2))):[]}}else Array.prototype.splice=function(pos,removeCount){var length=this.length;pos>0?pos>length&&(pos=length):void 0==pos?pos=0:0>pos&&(pos=Math.max(length+pos,0)),length>pos+removeCount||(removeCount=length-pos);var removed=this.slice(pos,pos+removeCount),insert=slice.call(arguments,2),add=insert.length;if(pos===length)add&&this.push.apply(this,insert);else{var remove=Math.min(removeCount,length-pos),tailOldPos=pos+remove,tailNewPos=tailOldPos+add-remove,tailCount=length-tailOldPos,lengthAfterRemove=length-remove;if(tailOldPos>tailNewPos)for(var i=0;tailCount>i;++i)this[tailNewPos+i]=this[tailOldPos+i];else if(tailNewPos>tailOldPos)for(i=tailCount;i--;)this[tailNewPos+i]=this[tailOldPos+i];if(add&&pos===lengthAfterRemove)this.length=lengthAfterRemove,this.push.apply(this,insert);else for(this.length=lengthAfterRemove+add,i=0;add>i;++i)this[pos+i]=insert[i]}return removed};Array.isArray||(Array.isArray=function(obj){return\"[object Array]\"==_toString(obj)});var boxedString=Object(\"a\"),splitString=\"a\"!=boxedString[0]||!(0 in boxedString);if(Array.prototype.forEach||(Array.prototype.forEach=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,thisp=arguments[1],i=-1,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError;for(;length>++i;)i in self&&fun.call(thisp,self[i],i,object)}),Array.prototype.map||(Array.prototype.map=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,result=Array(length),thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)i in self&&(result[i]=fun.call(thisp,self[i],i,object));return result}),Array.prototype.filter||(Array.prototype.filter=function(fun){var value,object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,result=[],thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)i in self&&(value=self[i],fun.call(thisp,value,i,object)&&result.push(value));return result}),Array.prototype.every||(Array.prototype.every=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)if(i in self&&!fun.call(thisp,self[i],i,object))return!1;return!0}),Array.prototype.some||(Array.prototype.some=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)if(i in self&&fun.call(thisp,self[i],i,object))return!0;return!1}),Array.prototype.reduce||(Array.prototype.reduce=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");if(!length&&1==arguments.length)throw new TypeError(\"reduce of empty array with no initial value\");var result,i=0;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i++];break}if(++i>=length)throw new TypeError(\"reduce of empty array with no initial value\")}for(;length>i;i++)i in self&&(result=fun.call(void 0,result,self[i],i,object));return result}),Array.prototype.reduceRight||(Array.prototype.reduceRight=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");if(!length&&1==arguments.length)throw new TypeError(\"reduceRight of empty array with no initial value\");var result,i=length-1;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i--];break}if(0>--i)throw new TypeError(\"reduceRight of empty array with no initial value\")}do i in this&&(result=fun.call(void 0,result,self[i],i,object));while(i--);return result}),Array.prototype.indexOf&&-1==[0,1].indexOf(1,2)||(Array.prototype.indexOf=function(sought){var self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):toObject(this),length=self.length>>>0;if(!length)return-1;var i=0;for(arguments.length>1&&(i=toInteger(arguments[1])),i=i>=0?i:Math.max(0,length+i);length>i;i++)if(i in self&&self[i]===sought)return i;return-1}),Array.prototype.lastIndexOf&&-1==[0,1].lastIndexOf(0,-3)||(Array.prototype.lastIndexOf=function(sought){var self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):toObject(this),length=self.length>>>0;if(!length)return-1;var i=length-1;for(arguments.length>1&&(i=Math.min(i,toInteger(arguments[1]))),i=i>=0?i:length-Math.abs(i);i>=0;i--)if(i in self&&sought===self[i])return i;return-1}),Object.getPrototypeOf||(Object.getPrototypeOf=function(object){return object.__proto__||(object.constructor?object.constructor.prototype:prototypeOfObject)}),!Object.getOwnPropertyDescriptor){var ERR_NON_OBJECT=\"Object.getOwnPropertyDescriptor called on a non-object: \";Object.getOwnPropertyDescriptor=function(object,property){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT+object);if(owns(object,property)){var descriptor,getter,setter;if(descriptor={enumerable:!0,configurable:!0},supportsAccessors){var prototype=object.__proto__;object.__proto__=prototypeOfObject;var getter=lookupGetter(object,property),setter=lookupSetter(object,property);if(object.__proto__=prototype,getter||setter)return getter&&(descriptor.get=getter),setter&&(descriptor.set=setter),descriptor}return descriptor.value=object[property],descriptor}}}if(Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(object){return Object.keys(object)}),!Object.create){var createEmpty;createEmpty=null===Object.prototype.__proto__?function(){return{__proto__:null}}:function(){var empty={};for(var i in empty)empty[i]=null;return empty.constructor=empty.hasOwnProperty=empty.propertyIsEnumerable=empty.isPrototypeOf=empty.toLocaleString=empty.toString=empty.valueOf=empty.__proto__=null,empty},Object.create=function(prototype,properties){var object;if(null===prototype)object=createEmpty();else{if(\"object\"!=typeof prototype)throw new TypeError(\"typeof prototype[\"+typeof prototype+\"] != 'object'\");var Type=function(){};Type.prototype=prototype,object=new Type,object.__proto__=prototype}return void 0!==properties&&Object.defineProperties(object,properties),object}}if(Object.defineProperty){var definePropertyWorksOnObject=doesDefinePropertyWork({}),definePropertyWorksOnDom=\"undefined\"==typeof document||doesDefinePropertyWork(document.createElement(\"div\"));if(!definePropertyWorksOnObject||!definePropertyWorksOnDom)var definePropertyFallback=Object.defineProperty}if(!Object.defineProperty||definePropertyFallback){var ERR_NON_OBJECT_DESCRIPTOR=\"Property description must be an object: \",ERR_NON_OBJECT_TARGET=\"Object.defineProperty called on non-object: \",ERR_ACCESSORS_NOT_SUPPORTED=\"getters & setters can not be defined on this javascript engine\";Object.defineProperty=function(object,property,descriptor){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT_TARGET+object);if(\"object\"!=typeof descriptor&&\"function\"!=typeof descriptor||null===descriptor)throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR+descriptor);if(definePropertyFallback)try{return definePropertyFallback.call(Object,object,property,descriptor)}catch(exception){}if(owns(descriptor,\"value\"))if(supportsAccessors&&(lookupGetter(object,property)||lookupSetter(object,property))){var prototype=object.__proto__;object.__proto__=prototypeOfObject,delete object[property],object[property]=descriptor.value,object.__proto__=prototype}else object[property]=descriptor.value;else{if(!supportsAccessors)throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);owns(descriptor,\"get\")&&defineGetter(object,property,descriptor.get),owns(descriptor,\"set\")&&defineSetter(object,property,descriptor.set)}return object}}Object.defineProperties||(Object.defineProperties=function(object,properties){for(var property in properties)owns(properties,property)&&Object.defineProperty(object,property,properties[property]);return object}),Object.seal||(Object.seal=function(object){return object}),Object.freeze||(Object.freeze=function(object){return object});try{Object.freeze(function(){})}catch(exception){Object.freeze=function(freezeObject){return function(object){return\"function\"==typeof object?object:freezeObject(object)}}(Object.freeze)}if(Object.preventExtensions||(Object.preventExtensions=function(object){return object}),Object.isSealed||(Object.isSealed=function(){return!1}),Object.isFrozen||(Object.isFrozen=function(){return!1}),Object.isExtensible||(Object.isExtensible=function(object){if(Object(object)===object)throw new TypeError;for(var name=\"\";owns(object,name);)name+=\"?\";object[name]=!0;var returnValue=owns(object,name);return delete object[name],returnValue}),!Object.keys){var hasDontEnumBug=!0,dontEnums=[\"toString\",\"toLocaleString\",\"valueOf\",\"hasOwnProperty\",\"isPrototypeOf\",\"propertyIsEnumerable\",\"constructor\"],dontEnumsLength=dontEnums.length;for(var key in{toString:null})hasDontEnumBug=!1;Object.keys=function(object){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(\"Object.keys called on a non-object\");var keys=[];for(var name in object)owns(object,name)&&keys.push(name);if(hasDontEnumBug)for(var i=0,ii=dontEnumsLength;ii>i;i++){var dontEnum=dontEnums[i];owns(object,dontEnum)&&keys.push(dontEnum)}return keys}}Date.now||(Date.now=function(){return(new Date).getTime()});var ws=\"\t\\n\u000b\\f\\r   ᠎              \\u2028\\u2029\";if(!String.prototype.trim||ws.trim()){ws=\"[\"+ws+\"]\";var trimBeginRegexp=RegExp(\"^\"+ws+ws+\"*\"),trimEndRegexp=RegExp(ws+ws+\"*$\");String.prototype.trim=function(){return(this+\"\").replace(trimBeginRegexp,\"\").replace(trimEndRegexp,\"\")}}var toObject=function(o){if(null==o)throw new TypeError(\"can't convert \"+o+\" to object\");return Object(o)}});"; \ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/node_modules/brace/worker/xml.js b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/node_modules/brace/worker/xml.js new file mode 100644 index 0000000..6ae4cf5 --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/node_modules/brace/worker/xml.js @@ -0,0 +1,2 @@ +module.exports.id = 'ace/mode/xml_worker'; +module.exports.src = "\"no use strict\";!function(window){function resolveModuleId(id,paths){for(var testPath=id,tail=\"\";testPath;){var alias=paths[testPath];if(\"string\"==typeof alias)return alias+tail;if(alias)return alias.location.replace(/\\/*$/,\"/\")+(tail||alias.main||alias.name);if(alias===!1)return\"\";var i=testPath.lastIndexOf(\"/\");if(-1===i)break;tail=testPath.substr(i)+tail,testPath=testPath.slice(0,i)}return id}if(!(void 0!==window.window&&window.document||window.acequire&&window.define)){window.console||(window.console=function(){var msgs=Array.prototype.slice.call(arguments,0);postMessage({type:\"log\",data:msgs})},window.console.error=window.console.warn=window.console.log=window.console.trace=window.console),window.window=window,window.ace=window,window.onerror=function(message,file,line,col,err){postMessage({type:\"error\",data:{message:message,data:err.data,file:file,line:line,col:col,stack:err.stack}})},window.normalizeModule=function(parentId,moduleName){if(-1!==moduleName.indexOf(\"!\")){var chunks=moduleName.split(\"!\");return window.normalizeModule(parentId,chunks[0])+\"!\"+window.normalizeModule(parentId,chunks[1])}if(\".\"==moduleName.charAt(0)){var base=parentId.split(\"/\").slice(0,-1).join(\"/\");for(moduleName=(base?base+\"/\":\"\")+moduleName;-1!==moduleName.indexOf(\".\")&&previous!=moduleName;){var previous=moduleName;moduleName=moduleName.replace(/^\\.\\//,\"\").replace(/\\/\\.\\//,\"/\").replace(/[^\\/]+\\/\\.\\.\\//,\"\")}}return moduleName},window.acequire=function acequire(parentId,id){if(id||(id=parentId,parentId=null),!id.charAt)throw Error(\"worker.js acequire() accepts only (parentId, id) as arguments\");id=window.normalizeModule(parentId,id);var module=window.acequire.modules[id];if(module)return module.initialized||(module.initialized=!0,module.exports=module.factory().exports),module.exports;if(!window.acequire.tlns)return console.log(\"unable to load \"+id);var path=resolveModuleId(id,window.acequire.tlns);return\".js\"!=path.slice(-3)&&(path+=\".js\"),window.acequire.id=id,window.acequire.modules[id]={},importScripts(path),window.acequire(parentId,id)},window.acequire.modules={},window.acequire.tlns={},window.define=function(id,deps,factory){if(2==arguments.length?(factory=deps,\"string\"!=typeof id&&(deps=id,id=window.acequire.id)):1==arguments.length&&(factory=id,deps=[],id=window.acequire.id),\"function\"!=typeof factory)return window.acequire.modules[id]={exports:factory,initialized:!0},void 0;deps.length||(deps=[\"require\",\"exports\",\"module\"]);var req=function(childId){return window.acequire(id,childId)};window.acequire.modules[id]={exports:{},factory:function(){var module=this,returnExports=factory.apply(this,deps.map(function(dep){switch(dep){case\"require\":return req;case\"exports\":return module.exports;case\"module\":return module;default:return req(dep)}}));return returnExports&&(module.exports=returnExports),module}}},window.define.amd={},acequire.tlns={},window.initBaseUrls=function(topLevelNamespaces){for(var i in topLevelNamespaces)acequire.tlns[i]=topLevelNamespaces[i]},window.initSender=function(){var EventEmitter=window.acequire(\"ace/lib/event_emitter\").EventEmitter,oop=window.acequire(\"ace/lib/oop\"),Sender=function(){};return function(){oop.implement(this,EventEmitter),this.callback=function(data,callbackId){postMessage({type:\"call\",id:callbackId,data:data})},this.emit=function(name,data){postMessage({type:\"event\",name:name,data:data})}}.call(Sender.prototype),new Sender};var main=window.main=null,sender=window.sender=null;window.onmessage=function(e){var msg=e.data;if(msg.event&&sender)sender._signal(msg.event,msg.data);else if(msg.command)if(main[msg.command])main[msg.command].apply(main,msg.args);else{if(!window[msg.command])throw Error(\"Unknown command:\"+msg.command);window[msg.command].apply(window,msg.args)}else if(msg.init){window.initBaseUrls(msg.tlns),acequire(\"ace/lib/es5-shim\"),sender=window.sender=window.initSender();var clazz=acequire(msg.module)[msg.classname];main=window.main=new clazz(sender)}}}}(this),ace.define(\"ace/lib/oop\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},exports.mixin=function(obj,mixin){for(var key in mixin)obj[key]=mixin[key];return obj},exports.implement=function(proto,mixin){exports.mixin(proto,mixin)}}),ace.define(\"ace/lib/lang\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.last=function(a){return a[a.length-1]},exports.stringReverse=function(string){return string.split(\"\").reverse().join(\"\")},exports.stringRepeat=function(string,count){for(var result=\"\";count>0;)1&count&&(result+=string),(count>>=1)&&(string+=string);return result};var trimBeginRegexp=/^\\s\\s*/,trimEndRegexp=/\\s\\s*$/;exports.stringTrimLeft=function(string){return string.replace(trimBeginRegexp,\"\")},exports.stringTrimRight=function(string){return string.replace(trimEndRegexp,\"\")},exports.copyObject=function(obj){var copy={};for(var key in obj)copy[key]=obj[key];return copy},exports.copyArray=function(array){for(var copy=[],i=0,l=array.length;l>i;i++)copy[i]=array[i]&&\"object\"==typeof array[i]?this.copyObject(array[i]):array[i];return copy},exports.deepCopy=function deepCopy(obj){if(\"object\"!=typeof obj||!obj)return obj;var copy;if(Array.isArray(obj)){copy=[];for(var key=0;obj.length>key;key++)copy[key]=deepCopy(obj[key]);return copy}if(\"[object Object]\"!==Object.prototype.toString.call(obj))return obj;copy={};for(var key in obj)copy[key]=deepCopy(obj[key]);return copy},exports.arrayToMap=function(arr){for(var map={},i=0;arr.length>i;i++)map[arr[i]]=1;return map},exports.createMap=function(props){var map=Object.create(null);for(var i in props)map[i]=props[i];return map},exports.arrayRemove=function(array,value){for(var i=0;array.length>=i;i++)value===array[i]&&array.splice(i,1)},exports.escapeRegExp=function(str){return str.replace(/([.*+?^${}()|[\\]\\/\\\\])/g,\"\\\\$1\")},exports.escapeHTML=function(str){return str.replace(/&/g,\"&\").replace(/\"/g,\""\").replace(/'/g,\"'\").replace(/ [\"+this.end.row+\"/\"+this.end.column+\"]\"},this.contains=function(row,column){return 0==this.compare(row,column)},this.compareRange=function(range){var cmp,end=range.end,start=range.start;return cmp=this.compare(end.row,end.column),1==cmp?(cmp=this.compare(start.row,start.column),1==cmp?2:0==cmp?1:0):-1==cmp?-2:(cmp=this.compare(start.row,start.column),-1==cmp?-1:1==cmp?42:0)},this.comparePoint=function(p){return this.compare(p.row,p.column)},this.containsRange=function(range){return 0==this.comparePoint(range.start)&&0==this.comparePoint(range.end)},this.intersects=function(range){var cmp=this.compareRange(range);return-1==cmp||0==cmp||1==cmp},this.isEnd=function(row,column){return this.end.row==row&&this.end.column==column},this.isStart=function(row,column){return this.start.row==row&&this.start.column==column},this.setStart=function(row,column){\"object\"==typeof row?(this.start.column=row.column,this.start.row=row.row):(this.start.row=row,this.start.column=column)},this.setEnd=function(row,column){\"object\"==typeof row?(this.end.column=row.column,this.end.row=row.row):(this.end.row=row,this.end.column=column)},this.inside=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)||this.isStart(row,column)?!1:!0:!1},this.insideStart=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)?!1:!0:!1},this.insideEnd=function(row,column){return 0==this.compare(row,column)?this.isStart(row,column)?!1:!0:!1},this.compare=function(row,column){return this.isMultiLine()||row!==this.start.row?this.start.row>row?-1:row>this.end.row?1:this.start.row===row?column>=this.start.column?0:-1:this.end.row===row?this.end.column>=column?0:1:0:this.start.column>column?-1:column>this.end.column?1:0},this.compareStart=function(row,column){return this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.compareEnd=function(row,column){return this.end.row==row&&this.end.column==column?1:this.compare(row,column)},this.compareInside=function(row,column){return this.end.row==row&&this.end.column==column?1:this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.clipRows=function(firstRow,lastRow){if(this.end.row>lastRow)var end={row:lastRow+1,column:0};else if(firstRow>this.end.row)var end={row:firstRow,column:0};if(this.start.row>lastRow)var start={row:lastRow+1,column:0};else if(firstRow>this.start.row)var start={row:firstRow,column:0};return Range.fromPoints(start||this.start,end||this.end)},this.extend=function(row,column){var cmp=this.compare(row,column);if(0==cmp)return this;if(-1==cmp)var start={row:row,column:column};else var end={row:row,column:column};return Range.fromPoints(start||this.start,end||this.end)},this.isEmpty=function(){return this.start.row===this.end.row&&this.start.column===this.end.column},this.isMultiLine=function(){return this.start.row!==this.end.row},this.clone=function(){return Range.fromPoints(this.start,this.end)},this.collapseRows=function(){return 0==this.end.column?new Range(this.start.row,0,Math.max(this.start.row,this.end.row-1),0):new Range(this.start.row,0,this.end.row,0)},this.toScreenRange=function(session){var screenPosStart=session.documentToScreenPosition(this.start),screenPosEnd=session.documentToScreenPosition(this.end);return new Range(screenPosStart.row,screenPosStart.column,screenPosEnd.row,screenPosEnd.column)},this.moveBy=function(row,column){this.start.row+=row,this.start.column+=column,this.end.row+=row,this.end.column+=column}}).call(Range.prototype),Range.fromPoints=function(start,end){return new Range(start.row,start.column,end.row,end.column)},Range.comparePoints=comparePoints,Range.comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},exports.Range=Range}),ace.define(\"ace/apply_delta\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.applyDelta=function(docLines,delta){var row=delta.start.row,startColumn=delta.start.column,line=docLines[row]||\"\";switch(delta.action){case\"insert\":var lines=delta.lines;if(1===lines.length)docLines[row]=line.substring(0,startColumn)+delta.lines[0]+line.substring(startColumn);else{var args=[row,1].concat(delta.lines);docLines.splice.apply(docLines,args),docLines[row]=line.substring(0,startColumn)+docLines[row],docLines[row+delta.lines.length-1]+=line.substring(startColumn)}break;case\"remove\":var endColumn=delta.end.column,endRow=delta.end.row;row===endRow?docLines[row]=line.substring(0,startColumn)+line.substring(endColumn):docLines.splice(row,endRow-row+1,line.substring(0,startColumn)+docLines[endRow].substring(endColumn))}}}),ace.define(\"ace/lib/event_emitter\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";var EventEmitter={},stopPropagation=function(){this.propagationStopped=!0},preventDefault=function(){this.defaultPrevented=!0};EventEmitter._emit=EventEmitter._dispatchEvent=function(eventName,e){this._eventRegistry||(this._eventRegistry={}),this._defaultHandlers||(this._defaultHandlers={});var listeners=this._eventRegistry[eventName]||[],defaultHandler=this._defaultHandlers[eventName];if(listeners.length||defaultHandler){\"object\"==typeof e&&e||(e={}),e.type||(e.type=eventName),e.stopPropagation||(e.stopPropagation=stopPropagation),e.preventDefault||(e.preventDefault=preventDefault),listeners=listeners.slice();for(var i=0;listeners.length>i&&(listeners[i](e,this),!e.propagationStopped);i++);return defaultHandler&&!e.defaultPrevented?defaultHandler(e,this):void 0}},EventEmitter._signal=function(eventName,e){var listeners=(this._eventRegistry||{})[eventName];if(listeners){listeners=listeners.slice();for(var i=0;listeners.length>i;i++)listeners[i](e,this)}},EventEmitter.once=function(eventName,callback){var _self=this;callback&&this.addEventListener(eventName,function newCallback(){_self.removeEventListener(eventName,newCallback),callback.apply(null,arguments)})},EventEmitter.setDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers||(handlers=this._defaultHandlers={_disabled_:{}}),handlers[eventName]){var old=handlers[eventName],disabled=handlers._disabled_[eventName];disabled||(handlers._disabled_[eventName]=disabled=[]),disabled.push(old);var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}handlers[eventName]=callback},EventEmitter.removeDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers){var disabled=handlers._disabled_[eventName];if(handlers[eventName]==callback)handlers[eventName],disabled&&this.setDefaultHandler(eventName,disabled.pop());else if(disabled){var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}}},EventEmitter.on=EventEmitter.addEventListener=function(eventName,callback,capturing){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];return listeners||(listeners=this._eventRegistry[eventName]=[]),-1==listeners.indexOf(callback)&&listeners[capturing?\"unshift\":\"push\"](callback),callback},EventEmitter.off=EventEmitter.removeListener=EventEmitter.removeEventListener=function(eventName,callback){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];if(listeners){var index=listeners.indexOf(callback);-1!==index&&listeners.splice(index,1)}},EventEmitter.removeAllListeners=function(eventName){this._eventRegistry&&(this._eventRegistry[eventName]=[])},exports.EventEmitter=EventEmitter}),ace.define(\"ace/anchor\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/lib/event_emitter\"],function(acequire,exports){\"use strict\";var oop=acequire(\"./lib/oop\"),EventEmitter=acequire(\"./lib/event_emitter\").EventEmitter,Anchor=exports.Anchor=function(doc,row,column){this.$onChange=this.onChange.bind(this),this.attach(doc),column===void 0?this.setPosition(row.row,row.column):this.setPosition(row,column)};(function(){function $pointsInOrder(point1,point2,equalPointsInOrder){var bColIsAfter=equalPointsInOrder?point1.column<=point2.column:point1.columnthis.row)){var point=$getTransformedPoint(delta,{row:this.row,column:this.column},this.$insertRight);this.setPosition(point.row,point.column,!0)}},this.setPosition=function(row,column,noClip){var pos;if(pos=noClip?{row:row,column:column}:this.$clipPositionToDocument(row,column),this.row!=pos.row||this.column!=pos.column){var old={row:this.row,column:this.column};this.row=pos.row,this.column=pos.column,this._signal(\"change\",{old:old,value:pos})}},this.detach=function(){this.document.removeEventListener(\"change\",this.$onChange)},this.attach=function(doc){this.document=doc||this.document,this.document.on(\"change\",this.$onChange)},this.$clipPositionToDocument=function(row,column){var pos={};return row>=this.document.getLength()?(pos.row=Math.max(0,this.document.getLength()-1),pos.column=this.document.getLine(pos.row).length):0>row?(pos.row=0,pos.column=0):(pos.row=row,pos.column=Math.min(this.document.getLine(pos.row).length,Math.max(0,column))),0>column&&(pos.column=0),pos}}).call(Anchor.prototype)}),ace.define(\"ace/document\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/apply_delta\",\"ace/lib/event_emitter\",\"ace/range\",\"ace/anchor\"],function(acequire,exports){\"use strict\";var oop=acequire(\"./lib/oop\"),applyDelta=acequire(\"./apply_delta\").applyDelta,EventEmitter=acequire(\"./lib/event_emitter\").EventEmitter,Range=acequire(\"./range\").Range,Anchor=acequire(\"./anchor\").Anchor,Document=function(textOrLines){this.$lines=[\"\"],0===textOrLines.length?this.$lines=[\"\"]:Array.isArray(textOrLines)?this.insertMergedLines({row:0,column:0},textOrLines):this.insert({row:0,column:0},textOrLines)};(function(){oop.implement(this,EventEmitter),this.setValue=function(text){var len=this.getLength()-1;this.remove(new Range(0,0,len,this.getLine(len).length)),this.insert({row:0,column:0},text)},this.getValue=function(){return this.getAllLines().join(this.getNewLineCharacter())},this.createAnchor=function(row,column){return new Anchor(this,row,column)},this.$split=0===\"aaa\".split(/a/).length?function(text){return text.replace(/\\r\\n|\\r/g,\"\\n\").split(\"\\n\")}:function(text){return text.split(/\\r\\n|\\r|\\n/)},this.$detectNewLine=function(text){var match=text.match(/^.*?(\\r\\n|\\r|\\n)/m);this.$autoNewLine=match?match[1]:\"\\n\",this._signal(\"changeNewLineMode\")},this.getNewLineCharacter=function(){switch(this.$newLineMode){case\"windows\":return\"\\r\\n\";case\"unix\":return\"\\n\";default:return this.$autoNewLine||\"\\n\"}},this.$autoNewLine=\"\",this.$newLineMode=\"auto\",this.setNewLineMode=function(newLineMode){this.$newLineMode!==newLineMode&&(this.$newLineMode=newLineMode,this._signal(\"changeNewLineMode\"))},this.getNewLineMode=function(){return this.$newLineMode},this.isNewLine=function(text){return\"\\r\\n\"==text||\"\\r\"==text||\"\\n\"==text},this.getLine=function(row){return this.$lines[row]||\"\"},this.getLines=function(firstRow,lastRow){return this.$lines.slice(firstRow,lastRow+1)},this.getAllLines=function(){return this.getLines(0,this.getLength())},this.getLength=function(){return this.$lines.length},this.getTextRange=function(range){return this.getLinesForRange(range).join(this.getNewLineCharacter())},this.getLinesForRange=function(range){var lines;if(range.start.row===range.end.row)lines=[this.getLine(range.start.row).substring(range.start.column,range.end.column)];else{lines=this.getLines(range.start.row,range.end.row),lines[0]=(lines[0]||\"\").substring(range.start.column);var l=lines.length-1;range.end.row-range.start.row==l&&(lines[l]=lines[l].substring(0,range.end.column))}return lines},this.insertLines=function(row,lines){return console.warn(\"Use of document.insertLines is deprecated. Use the insertFullLines method instead.\"),this.insertFullLines(row,lines)},this.removeLines=function(firstRow,lastRow){return console.warn(\"Use of document.removeLines is deprecated. Use the removeFullLines method instead.\"),this.removeFullLines(firstRow,lastRow)},this.insertNewLine=function(position){return console.warn(\"Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead.\"),this.insertMergedLines(position,[\"\",\"\"])},this.insert=function(position,text){return 1>=this.getLength()&&this.$detectNewLine(text),this.insertMergedLines(position,this.$split(text))},this.insertInLine=function(position,text){var start=this.clippedPos(position.row,position.column),end=this.pos(position.row,position.column+text.length);return this.applyDelta({start:start,end:end,action:\"insert\",lines:[text]},!0),this.clonePos(end)},this.clippedPos=function(row,column){var length=this.getLength();void 0===row?row=length:0>row?row=0:row>=length&&(row=length-1,column=void 0);var line=this.getLine(row);return void 0==column&&(column=line.length),column=Math.min(Math.max(column,0),line.length),{row:row,column:column}},this.clonePos=function(pos){return{row:pos.row,column:pos.column}},this.pos=function(row,column){return{row:row,column:column}},this.$clipPosition=function(position){var length=this.getLength();return position.row>=length?(position.row=Math.max(0,length-1),position.column=this.getLine(length-1).length):(position.row=Math.max(0,position.row),position.column=Math.min(Math.max(position.column,0),this.getLine(position.row).length)),position},this.insertFullLines=function(row,lines){row=Math.min(Math.max(row,0),this.getLength());var column=0;this.getLength()>row?(lines=lines.concat([\"\"]),column=0):(lines=[\"\"].concat(lines),row--,column=this.$lines[row].length),this.insertMergedLines({row:row,column:column},lines)},this.insertMergedLines=function(position,lines){var start=this.clippedPos(position.row,position.column),end={row:start.row+lines.length-1,column:(1==lines.length?start.column:0)+lines[lines.length-1].length};return this.applyDelta({start:start,end:end,action:\"insert\",lines:lines}),this.clonePos(end)},this.remove=function(range){var start=this.clippedPos(range.start.row,range.start.column),end=this.clippedPos(range.end.row,range.end.column);return this.applyDelta({start:start,end:end,action:\"remove\",lines:this.getLinesForRange({start:start,end:end})}),this.clonePos(start)},this.removeInLine=function(row,startColumn,endColumn){var start=this.clippedPos(row,startColumn),end=this.clippedPos(row,endColumn);return this.applyDelta({start:start,end:end,action:\"remove\",lines:this.getLinesForRange({start:start,end:end})},!0),this.clonePos(start)},this.removeFullLines=function(firstRow,lastRow){firstRow=Math.min(Math.max(0,firstRow),this.getLength()-1),lastRow=Math.min(Math.max(0,lastRow),this.getLength()-1);var deleteFirstNewLine=lastRow==this.getLength()-1&&firstRow>0,deleteLastNewLine=this.getLength()-1>lastRow,startRow=deleteFirstNewLine?firstRow-1:firstRow,startCol=deleteFirstNewLine?this.getLine(startRow).length:0,endRow=deleteLastNewLine?lastRow+1:lastRow,endCol=deleteLastNewLine?0:this.getLine(endRow).length,range=new Range(startRow,startCol,endRow,endCol),deletedLines=this.$lines.slice(firstRow,lastRow+1);return this.applyDelta({start:range.start,end:range.end,action:\"remove\",lines:this.getLinesForRange(range)}),deletedLines},this.removeNewLine=function(row){this.getLength()-1>row&&row>=0&&this.applyDelta({start:this.pos(row,this.getLine(row).length),end:this.pos(row+1,0),action:\"remove\",lines:[\"\",\"\"]})},this.replace=function(range,text){if(range instanceof Range||(range=Range.fromPoints(range.start,range.end)),0===text.length&&range.isEmpty())return range.start;if(text==this.getTextRange(range))return range.end;this.remove(range);var end;return end=text?this.insert(range.start,text):range.start},this.applyDeltas=function(deltas){for(var i=0;deltas.length>i;i++)this.applyDelta(deltas[i])},this.revertDeltas=function(deltas){for(var i=deltas.length-1;i>=0;i--)this.revertDelta(deltas[i])},this.applyDelta=function(delta,doNotValidate){var isInsert=\"insert\"==delta.action;(isInsert?1>=delta.lines.length&&!delta.lines[0]:!Range.comparePoints(delta.start,delta.end))||(isInsert&&delta.lines.length>2e4&&this.$splitAndapplyLargeDelta(delta,2e4),applyDelta(this.$lines,delta,doNotValidate),this._signal(\"change\",delta))},this.$splitAndapplyLargeDelta=function(delta,MAX){for(var lines=delta.lines,l=lines.length,row=delta.start.row,column=delta.start.column,from=0,to=0;;){from=to,to+=MAX-1;var chunk=lines.slice(from,to);if(to>l){delta.lines=chunk,delta.start.row=row+from,delta.start.column=column;break}chunk.push(\"\"),this.applyDelta({start:this.pos(row+from,column),end:this.pos(row+to,column=0),action:delta.action,lines:chunk},!0)}},this.revertDelta=function(delta){this.applyDelta({start:this.clonePos(delta.start),end:this.clonePos(delta.end),action:\"insert\"==delta.action?\"remove\":\"insert\",lines:delta.lines.slice()})},this.indexToPosition=function(index,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,i=startRow||0,l=lines.length;l>i;i++)if(index-=lines[i].length+newlineLength,0>index)return{row:i,column:index+lines[i].length+newlineLength};return{row:l-1,column:lines[l-1].length}},this.positionToIndex=function(pos,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,index=0,row=Math.min(pos.row,lines.length),i=startRow||0;row>i;++i)index+=lines[i].length+newlineLength;return index+pos.column}}).call(Document.prototype),exports.Document=Document}),ace.define(\"ace/worker/mirror\",[\"require\",\"exports\",\"module\",\"ace/range\",\"ace/document\",\"ace/lib/lang\"],function(acequire,exports){\"use strict\";acequire(\"../range\").Range;var Document=acequire(\"../document\").Document,lang=acequire(\"../lib/lang\"),Mirror=exports.Mirror=function(sender){this.sender=sender;var doc=this.doc=new Document(\"\"),deferredUpdate=this.deferredUpdate=lang.delayedCall(this.onUpdate.bind(this)),_self=this;sender.on(\"change\",function(e){var data=e.data;if(data[0].start)doc.applyDeltas(data);else for(var i=0;data.length>i;i+=2){if(Array.isArray(data[i+1]))var d={action:\"insert\",start:data[i],lines:data[i+1]};else var d={action:\"remove\",start:data[i],end:data[i+1]};doc.applyDelta(d,!0)}return _self.$timeout?deferredUpdate.schedule(_self.$timeout):(_self.onUpdate(),void 0)})};(function(){this.$timeout=500,this.setTimeout=function(timeout){this.$timeout=timeout},this.setValue=function(value){this.doc.setValue(value),this.deferredUpdate.schedule(this.$timeout)},this.getValue=function(callbackId){this.sender.callback(this.doc.getValue(),callbackId)},this.onUpdate=function(){},this.isPending=function(){return this.deferredUpdate.isPending()}}).call(Mirror.prototype)}),ace.define(\"ace/mode/xml/sax\",[\"require\",\"exports\",\"module\"],function(){function XMLReader(){}function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){function fixedFromCharCode(code){if(code>65535){code-=65536;var surrogate1=55296+(code>>10),surrogate2=56320+(1023&code);return String.fromCharCode(surrogate1,surrogate2)}return String.fromCharCode(code)}function entityReplacer(a){var k=a.slice(1,-1);return k in entityMap?entityMap[k]:\"#\"===k.charAt(0)?fixedFromCharCode(parseInt(k.substr(1).replace(\"x\",\"0x\"))):(errorHandler.error(\"entity not found:\"+a),a)}function appendText(end){var xt=source.substring(start,end).replace(/&#?\\w+;/g,entityReplacer);locator&&position(start),domBuilder.characters(xt,0,end-start),start=end}function position(start,m){for(;start>=endPos&&(m=linePattern.exec(source));)startPos=m.index,endPos=startPos+m[0].length,locator.lineNumber++;locator.columnNumber=start-startPos+1}for(var startPos=0,endPos=0,linePattern=/.+(?:\\r\\n?|\\n)|.*$/g,locator=domBuilder.locator,parseStack=[{currentNSMap:defaultNSMapCopy}],closeMap={},start=0;;){var i=source.indexOf(\"<\",start);if(0>i){if(!source.substr(start).match(/^\\s*$/)){var doc=domBuilder.document,text=doc.createTextNode(source.substr(start));doc.appendChild(text),domBuilder.currentElement=text}return}switch(i>start&&appendText(i),source.charAt(i+1)){case\"/\":var config,end=source.indexOf(\">\",i+3),tagName=source.substring(i+2,end);if(!(parseStack.length>1)){errorHandler.fatalError(\"end tag name not found for: \"+tagName);break}config=parseStack.pop();var localNSMap=config.localNSMap;if(config.tagName!=tagName&&errorHandler.fatalError(\"end tag name: \"+tagName+\" does not match the current start tagName: \"+config.tagName),domBuilder.endElement(config.uri,config.localName,tagName),localNSMap)for(var prefix in localNSMap)domBuilder.endPrefixMapping(prefix);end++;break;case\"?\":locator&&position(i),end=parseInstruction(source,i,domBuilder);break;case\"!\":locator&&position(i),end=parseDCC(source,i,domBuilder,errorHandler);break;default:try{locator&&position(i);var el=new ElementAttributes,end=parseElementStartPart(source,i,el,entityReplacer,errorHandler),len=el.length;if(len&&locator){for(var backup=copyLocator(locator,{}),i=0;len>i;i++){var a=el[i];position(a.offset),a.offset=copyLocator(locator,{})}copyLocator(backup,locator)}!el.closed&&fixSelfClosed(source,end,el.tagName,closeMap)&&(el.closed=!0,entityMap.nbsp||errorHandler.warning(\"unclosed xml attribute\")),appendElement(el,domBuilder,parseStack),\"http://www.w3.org/1999/xhtml\"!==el.uri||el.closed?end++:end=parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder)}catch(e){errorHandler.error(\"element parse error: \"+e),end=-1}}0>end?appendText(i+1):start=end}}function copyLocator(f,t){return t.lineNumber=f.lineNumber,t.columnNumber=f.columnNumber,t}function parseElementStartPart(source,start,el,entityReplacer,errorHandler){for(var attrName,value,p=++start,s=S_TAG;;){var c=source.charAt(p);switch(c){case\"=\":if(s===S_ATTR)attrName=source.slice(start,p),s=S_EQ;else{if(s!==S_ATTR_S)throw Error(\"attribute equal must after attrName\");s=S_EQ}break;case\"'\":case'\"':if(s===S_EQ){if(start=p+1,p=source.indexOf(c,start),!(p>0))throw Error(\"attribute value no end '\"+c+\"' match\");value=source.slice(start,p).replace(/&#?\\w+;/g,entityReplacer),el.add(attrName,value,start-1),s=S_E}else{if(s!=S_V)throw Error('attribute value must after \"=\"');value=source.slice(start,p).replace(/&#?\\w+;/g,entityReplacer),el.add(attrName,value,start),errorHandler.warning('attribute \"'+attrName+'\" missed start quot('+c+\")!!\"),start=p+1,s=S_E}break;case\"/\":switch(s){case S_TAG:el.setTagName(source.slice(start,p));case S_E:case S_S:case S_C:s=S_C,el.closed=!0;case S_V:case S_ATTR:case S_ATTR_S:break;default:throw Error(\"attribute invalid close char('/')\")}break;case\"\":errorHandler.error(\"unexpected end of input\");case\">\":switch(s){case S_TAG:el.setTagName(source.slice(start,p));case S_E:case S_S:case S_C:break;case S_V:case S_ATTR:value=source.slice(start,p),\"/\"===value.slice(-1)&&(el.closed=!0,value=value.slice(0,-1));case S_ATTR_S:s===S_ATTR_S&&(value=attrName),s==S_V?(errorHandler.warning('attribute \"'+value+'\" missed quot(\")!!'),el.add(attrName,value.replace(/&#?\\w+;/g,entityReplacer),start)):(errorHandler.warning('attribute \"'+value+'\" missed value!! \"'+value+'\" instead!!'),el.add(value,value,start));break;case S_EQ:throw Error(\"attribute value missed!!\")}return p;case\"€\":c=\" \";default:if(\" \">=c)switch(s){case S_TAG:el.setTagName(source.slice(start,p)),s=S_S;break;case S_ATTR:attrName=source.slice(start,p),s=S_ATTR_S;break;case S_V:var value=source.slice(start,p).replace(/&#?\\w+;/g,entityReplacer);errorHandler.warning('attribute \"'+value+'\" missed quot(\")!!'),el.add(attrName,value,start);case S_E:s=S_S}else switch(s){case S_ATTR_S:errorHandler.warning('attribute \"'+attrName+'\" missed value!! \"'+attrName+'\" instead!!'),el.add(attrName,attrName,start),start=p,s=S_ATTR;\nbreak;case S_E:errorHandler.warning('attribute space is acequired\"'+attrName+'\"!!');case S_S:s=S_ATTR,start=p;break;case S_EQ:s=S_V,start=p;break;case S_C:throw Error(\"elements closed character '/' and '>' must be connected to\")}}p++}}function appendElement(el,domBuilder,parseStack){for(var tagName=el.tagName,localNSMap=null,currentNSMap=parseStack[parseStack.length-1].currentNSMap,i=el.length;i--;){var a=el[i],qName=a.qName,value=a.value,nsp=qName.indexOf(\":\");if(nsp>0)var prefix=a.prefix=qName.slice(0,nsp),localName=qName.slice(nsp+1),nsPrefix=\"xmlns\"===prefix&&localName;else localName=qName,prefix=null,nsPrefix=\"xmlns\"===qName&&\"\";a.localName=localName,nsPrefix!==!1&&(null==localNSMap&&(localNSMap={},_copy(currentNSMap,currentNSMap={})),currentNSMap[nsPrefix]=localNSMap[nsPrefix]=value,a.uri=\"http://www.w3.org/2000/xmlns/\",domBuilder.startPrefixMapping(nsPrefix,value))}for(var i=el.length;i--;){a=el[i];var prefix=a.prefix;prefix&&(\"xml\"===prefix&&(a.uri=\"http://www.w3.org/XML/1998/namespace\"),\"xmlns\"!==prefix&&(a.uri=currentNSMap[prefix]))}var nsp=tagName.indexOf(\":\");nsp>0?(prefix=el.prefix=tagName.slice(0,nsp),localName=el.localName=tagName.slice(nsp+1)):(prefix=null,localName=el.localName=tagName);var ns=el.uri=currentNSMap[prefix||\"\"];if(domBuilder.startElement(ns,localName,tagName,el),el.closed){if(domBuilder.endElement(ns,localName,tagName),localNSMap)for(prefix in localNSMap)domBuilder.endPrefixMapping(prefix)}else el.currentNSMap=currentNSMap,el.localNSMap=localNSMap,parseStack.push(el)}function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){if(/^(?:script|textarea)$/i.test(tagName)){var elEndStart=source.indexOf(\"\",elStartEnd),text=source.substring(elStartEnd+1,elEndStart);if(/[&<]/.test(text))return/^script$/i.test(tagName)?(domBuilder.characters(text,0,text.length),elEndStart):(text=text.replace(/&#?\\w+;/g,entityReplacer),domBuilder.characters(text,0,text.length),elEndStart)}return elStartEnd+1}function fixSelfClosed(source,elStartEnd,tagName,closeMap){var pos=closeMap[tagName];return null==pos&&(pos=closeMap[tagName]=source.lastIndexOf(\"\")),elStartEnd>pos}function _copy(source,target){for(var n in source)target[n]=source[n]}function parseDCC(source,start,domBuilder,errorHandler){var next=source.charAt(start+2);switch(next){case\"-\":if(\"-\"===source.charAt(start+3)){var end=source.indexOf(\"-->\",start+4);return end>start?(domBuilder.comment(source,start+4,end-start-4),end+3):(errorHandler.error(\"Unclosed comment\"),-1)}return-1;default:if(\"CDATA[\"==source.substr(start+3,6)){var end=source.indexOf(\"]]>\",start+9);return domBuilder.startCDATA(),domBuilder.characters(source,start+9,end-start-9),domBuilder.endCDATA(),end+3}var matchs=split(source,start),len=matchs.length;if(len>1&&/!doctype/i.test(matchs[0][0])){var name=matchs[1][0],pubid=len>3&&/^public$/i.test(matchs[2][0])&&matchs[3][0],sysid=len>4&&matchs[4][0],lastMatch=matchs[len-1];return domBuilder.startDTD(name,pubid&&pubid.replace(/^(['\"])(.*?)\\1$/,\"$2\"),sysid&&sysid.replace(/^(['\"])(.*?)\\1$/,\"$2\")),domBuilder.endDTD(),lastMatch.index+lastMatch[0].length}}return-1}function parseInstruction(source,start,domBuilder){var end=source.indexOf(\"?>\",start);if(end){var match=source.substring(start,end).match(/^<\\?(\\S*)\\s*([\\s\\S]*?)\\s*$/);return match?(match[0].length,domBuilder.processingInstruction(match[1],match[2]),end+2):-1}return-1}function ElementAttributes(){}function _set_proto_(thiz,parent){return thiz.__proto__=parent,thiz}function split(source,start){var match,buf=[],reg=/'[^']+'|\"[^\"]+\"|[^\\s<>\\/=]+=?|(\\/?\\s*>|<)/g;for(reg.lastIndex=start,reg.exec(source);match=reg.exec(source);)if(buf.push(match),match[1])return buf}var nameStartChar=/[A-Z_a-z\\xC0-\\xD6\\xD8-\\xF6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]/,nameChar=RegExp(\"[\\\\-\\\\.0-9\"+nameStartChar.source.slice(1,-1)+\"·̀-ͯ\\\\ux203F-⁀]\"),tagNamePattern=RegExp(\"^\"+nameStartChar.source+nameChar.source+\"*(?::\"+nameStartChar.source+nameChar.source+\"*)?$\"),S_TAG=0,S_ATTR=1,S_ATTR_S=2,S_EQ=3,S_V=4,S_E=5,S_S=6,S_C=7;return XMLReader.prototype={parse:function(source,defaultNSMap,entityMap){var domBuilder=this.domBuilder;domBuilder.startDocument(),_copy(defaultNSMap,defaultNSMap={}),parse(source,defaultNSMap,entityMap,domBuilder,this.errorHandler),domBuilder.endDocument()}},ElementAttributes.prototype={setTagName:function(tagName){if(!tagNamePattern.test(tagName))throw Error(\"invalid tagName:\"+tagName);this.tagName=tagName},add:function(qName,value,offset){if(!tagNamePattern.test(qName))throw Error(\"invalid attribute:\"+qName);this[this.length++]={qName:qName,value:value,offset:offset}},length:0,getLocalName:function(i){return this[i].localName},getOffset:function(i){return this[i].offset},getQName:function(i){return this[i].qName},getURI:function(i){return this[i].uri},getValue:function(i){return this[i].value}},_set_proto_({},_set_proto_.prototype)instanceof _set_proto_||(_set_proto_=function(thiz,parent){function p(){}p.prototype=parent,p=new p;for(parent in thiz)p[parent]=thiz[parent];return p}),XMLReader}),ace.define(\"ace/mode/xml/dom\",[\"require\",\"exports\",\"module\"],function(){function copy(src,dest){for(var p in src)dest[p]=src[p]}function _extends(Class,Super){function t(){}var pt=Class.prototype;if(Object.create){var ppt=Object.create(Super.prototype);pt.__proto__=ppt}pt instanceof Super||(t.prototype=Super.prototype,t=new t,copy(pt,t),Class.prototype=pt=t),pt.constructor!=Class&&(\"function\"!=typeof Class&&console.error(\"unknow Class:\"+Class),pt.constructor=Class)}function DOMException(code,message){if(message instanceof Error)var error=message;else error=this,Error.call(this,ExceptionMessage[code]),this.message=ExceptionMessage[code],Error.captureStackTrace&&Error.captureStackTrace(this,DOMException);return error.code=code,message&&(this.message=this.message+\": \"+message),error}function NodeList(){}function LiveNodeList(node,refresh){this._node=node,this._refresh=refresh,_updateLiveList(this)}function _updateLiveList(list){var inc=list._node._inc||list._node.ownerDocument._inc;if(list._inc!=inc){var ls=list._refresh(list._node);__set__(list,\"length\",ls.length),copy(ls,list),list._inc=inc}}function NamedNodeMap(){}function _findNodeIndex(list,node){for(var i=list.length;i--;)if(list[i]===node)return i}function _addNamedNode(el,list,newAttr,oldAttr){if(oldAttr?list[_findNodeIndex(list,oldAttr)]=newAttr:list[list.length++]=newAttr,el){newAttr.ownerElement=el;var doc=el.ownerDocument;doc&&(oldAttr&&_onRemoveAttribute(doc,el,oldAttr),_onAddAttribute(doc,el,newAttr))}}function _removeNamedNode(el,list,attr){var i=_findNodeIndex(list,attr);if(!(i>=0))throw DOMException(NOT_FOUND_ERR,Error());for(var lastIndex=list.length-1;lastIndex>i;)list[i]=list[++i];if(list.length=lastIndex,el){var doc=el.ownerDocument;doc&&(_onRemoveAttribute(doc,el,attr),attr.ownerElement=null)}}function DOMImplementation(features){if(this._features={},features)for(var feature in features)this._features=features[feature]}function Node(){}function _xmlEncoder(c){return\"<\"==c&&\"<\"||\">\"==c&&\">\"||\"&\"==c&&\"&\"||'\"'==c&&\""\"||\"&#\"+c.charCodeAt()+\";\"}function _visitNode(node,callback){if(callback(node))return!0;if(node=node.firstChild)do if(_visitNode(node,callback))return!0;while(node=node.nextSibling)}function Document(){}function _onAddAttribute(doc,el,newAttr){doc&&doc._inc++;var ns=newAttr.namespaceURI;\"http://www.w3.org/2000/xmlns/\"==ns&&(el._nsMap[newAttr.prefix?newAttr.localName:\"\"]=newAttr.value)}function _onRemoveAttribute(doc,el,newAttr){doc&&doc._inc++;var ns=newAttr.namespaceURI;\"http://www.w3.org/2000/xmlns/\"==ns&&delete el._nsMap[newAttr.prefix?newAttr.localName:\"\"]}function _onUpdateChild(doc,el,newChild){if(doc&&doc._inc){doc._inc++;var cs=el.childNodes;if(newChild)cs[cs.length++]=newChild;else{for(var child=el.firstChild,i=0;child;)cs[i++]=child,child=child.nextSibling;cs.length=i}}}function _removeChild(parentNode,child){var previous=child.previousSibling,next=child.nextSibling;return previous?previous.nextSibling=next:parentNode.firstChild=next,next?next.previousSibling=previous:parentNode.lastChild=previous,_onUpdateChild(parentNode.ownerDocument,parentNode),child}function _insertBefore(parentNode,newChild,nextChild){var cp=newChild.parentNode;if(cp&&cp.removeChild(newChild),newChild.nodeType===DOCUMENT_FRAGMENT_NODE){var newFirst=newChild.firstChild;if(null==newFirst)return newChild;var newLast=newChild.lastChild}else newFirst=newLast=newChild;var pre=nextChild?nextChild.previousSibling:parentNode.lastChild;newFirst.previousSibling=pre,newLast.nextSibling=nextChild,pre?pre.nextSibling=newFirst:parentNode.firstChild=newFirst,null==nextChild?parentNode.lastChild=newLast:nextChild.previousSibling=newLast;do newFirst.parentNode=parentNode;while(newFirst!==newLast&&(newFirst=newFirst.nextSibling));return _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode),newChild.nodeType==DOCUMENT_FRAGMENT_NODE&&(newChild.firstChild=newChild.lastChild=null),newChild}function _appendSingleChild(parentNode,newChild){var cp=newChild.parentNode;if(cp){var pre=parentNode.lastChild;cp.removeChild(newChild);var pre=parentNode.lastChild}var pre=parentNode.lastChild;return newChild.parentNode=parentNode,newChild.previousSibling=pre,newChild.nextSibling=null,pre?pre.nextSibling=newChild:parentNode.firstChild=newChild,parentNode.lastChild=newChild,_onUpdateChild(parentNode.ownerDocument,parentNode,newChild),newChild}function Element(){this._nsMap={}}function Attr(){}function CharacterData(){}function Text(){}function Comment(){}function CDATASection(){}function DocumentType(){}function Notation(){}function Entity(){}function EntityReference(){}function DocumentFragment(){}function ProcessingInstruction(){}function XMLSerializer(){}function serializeToString(node,buf){switch(node.nodeType){case ELEMENT_NODE:var attrs=node.attributes,len=attrs.length,child=node.firstChild,nodeName=node.tagName,isHTML=htmlns===node.namespaceURI;buf.push(\"<\",nodeName);for(var i=0;len>i;i++)serializeToString(attrs.item(i),buf,isHTML);if(child||isHTML&&!/^(?:meta|link|img|br|hr|input|button)$/i.test(nodeName)){if(buf.push(\">\"),isHTML&&/^script$/i.test(nodeName))child&&buf.push(child.data);else for(;child;)serializeToString(child,buf),child=child.nextSibling;buf.push(\"\")}else buf.push(\"/>\");return;case DOCUMENT_NODE:case DOCUMENT_FRAGMENT_NODE:for(var child=node.firstChild;child;)serializeToString(child,buf),child=child.nextSibling;return;case ATTRIBUTE_NODE:return buf.push(\" \",node.name,'=\"',node.value.replace(/[<&\"]/g,_xmlEncoder),'\"');case TEXT_NODE:return buf.push(node.data.replace(/[<&]/g,_xmlEncoder));case CDATA_SECTION_NODE:return buf.push(\"\");case COMMENT_NODE:return buf.push(\"\");case DOCUMENT_TYPE_NODE:var pubid=node.publicId,sysid=node.systemId;if(buf.push(\"');else if(sysid&&\".\"!=sysid)buf.push(' SYSTEM \"',sysid,'\">');else{var sub=node.internalSubset;sub&&buf.push(\" [\",sub,\"]\"),buf.push(\">\")}return;case PROCESSING_INSTRUCTION_NODE:return buf.push(\"\");case ENTITY_REFERENCE_NODE:return buf.push(\"&\",node.nodeName,\";\");default:buf.push(\"??\",node.nodeName)}}function importNode(doc,node,deep){var node2;switch(node.nodeType){case ELEMENT_NODE:node2=node.cloneNode(!1),node2.ownerDocument=doc;case DOCUMENT_FRAGMENT_NODE:break;case ATTRIBUTE_NODE:deep=!0}if(node2||(node2=node.cloneNode(!1)),node2.ownerDocument=doc,node2.parentNode=null,deep)for(var child=node.firstChild;child;)node2.appendChild(importNode(doc,child,deep)),child=child.nextSibling;return node2}function cloneNode(doc,node,deep){var node2=new node.constructor;for(var n in node){var v=node[n];\"object\"!=typeof v&&v!=node2[n]&&(node2[n]=v)}switch(node.childNodes&&(node2.childNodes=new NodeList),node2.ownerDocument=doc,node2.nodeType){case ELEMENT_NODE:var attrs=node.attributes,attrs2=node2.attributes=new NamedNodeMap,len=attrs.length;attrs2._ownerElement=node2;for(var i=0;len>i;i++)node2.setAttributeNode(cloneNode(doc,attrs.item(i),!0));break;case ATTRIBUTE_NODE:deep=!0}if(deep)for(var child=node.firstChild;child;)node2.appendChild(cloneNode(doc,child,deep)),child=child.nextSibling;return node2}function __set__(object,key,value){object[key]=value}function getTextContent(node){switch(node.nodeType){case 1:case 11:var buf=[];for(node=node.firstChild;node;)7!==node.nodeType&&8!==node.nodeType&&buf.push(getTextContent(node)),node=node.nextSibling;return buf.join(\"\");default:return node.nodeValue}}var htmlns=\"http://www.w3.org/1999/xhtml\",NodeType={},ELEMENT_NODE=NodeType.ELEMENT_NODE=1,ATTRIBUTE_NODE=NodeType.ATTRIBUTE_NODE=2,TEXT_NODE=NodeType.TEXT_NODE=3,CDATA_SECTION_NODE=NodeType.CDATA_SECTION_NODE=4,ENTITY_REFERENCE_NODE=NodeType.ENTITY_REFERENCE_NODE=5,ENTITY_NODE=NodeType.ENTITY_NODE=6,PROCESSING_INSTRUCTION_NODE=NodeType.PROCESSING_INSTRUCTION_NODE=7,COMMENT_NODE=NodeType.COMMENT_NODE=8,DOCUMENT_NODE=NodeType.DOCUMENT_NODE=9,DOCUMENT_TYPE_NODE=NodeType.DOCUMENT_TYPE_NODE=10,DOCUMENT_FRAGMENT_NODE=NodeType.DOCUMENT_FRAGMENT_NODE=11,NOTATION_NODE=NodeType.NOTATION_NODE=12,ExceptionCode={},ExceptionMessage={};ExceptionCode.INDEX_SIZE_ERR=(ExceptionMessage[1]=\"Index size error\",1),ExceptionCode.DOMSTRING_SIZE_ERR=(ExceptionMessage[2]=\"DOMString size error\",2),ExceptionCode.HIERARCHY_REQUEST_ERR=(ExceptionMessage[3]=\"Hierarchy request error\",3),ExceptionCode.WRONG_DOCUMENT_ERR=(ExceptionMessage[4]=\"Wrong document\",4),ExceptionCode.INVALID_CHARACTER_ERR=(ExceptionMessage[5]=\"Invalid character\",5),ExceptionCode.NO_DATA_ALLOWED_ERR=(ExceptionMessage[6]=\"No data allowed\",6),ExceptionCode.NO_MODIFICATION_ALLOWED_ERR=(ExceptionMessage[7]=\"No modification allowed\",7);var NOT_FOUND_ERR=ExceptionCode.NOT_FOUND_ERR=(ExceptionMessage[8]=\"Not found\",8);ExceptionCode.NOT_SUPPORTED_ERR=(ExceptionMessage[9]=\"Not supported\",9);var INUSE_ATTRIBUTE_ERR=ExceptionCode.INUSE_ATTRIBUTE_ERR=(ExceptionMessage[10]=\"Attribute in use\",10);ExceptionCode.INVALID_STATE_ERR=(ExceptionMessage[11]=\"Invalid state\",11),ExceptionCode.SYNTAX_ERR=(ExceptionMessage[12]=\"Syntax error\",12),ExceptionCode.INVALID_MODIFICATION_ERR=(ExceptionMessage[13]=\"Invalid modification\",13),ExceptionCode.NAMESPACE_ERR=(ExceptionMessage[14]=\"Invalid namespace\",14),ExceptionCode.INVALID_ACCESS_ERR=(ExceptionMessage[15]=\"Invalid access\",15),DOMException.prototype=Error.prototype,copy(ExceptionCode,DOMException),NodeList.prototype={length:0,item:function(index){return this[index]||null}},LiveNodeList.prototype.item=function(i){return _updateLiveList(this),this[i]},_extends(LiveNodeList,NodeList),NamedNodeMap.prototype={length:0,item:NodeList.prototype.item,getNamedItem:function(key){for(var i=this.length;i--;){var attr=this[i];if(attr.nodeName==key)return attr}},setNamedItem:function(attr){var el=attr.ownerElement;if(el&&el!=this._ownerElement)throw new DOMException(INUSE_ATTRIBUTE_ERR);var oldAttr=this.getNamedItem(attr.nodeName);return _addNamedNode(this._ownerElement,this,attr,oldAttr),oldAttr},setNamedItemNS:function(attr){var oldAttr,el=attr.ownerElement;if(el&&el!=this._ownerElement)throw new DOMException(INUSE_ATTRIBUTE_ERR);return oldAttr=this.getNamedItemNS(attr.namespaceURI,attr.localName),_addNamedNode(this._ownerElement,this,attr,oldAttr),oldAttr},removeNamedItem:function(key){var attr=this.getNamedItem(key);return _removeNamedNode(this._ownerElement,this,attr),attr},removeNamedItemNS:function(namespaceURI,localName){var attr=this.getNamedItemNS(namespaceURI,localName);return _removeNamedNode(this._ownerElement,this,attr),attr},getNamedItemNS:function(namespaceURI,localName){for(var i=this.length;i--;){var node=this[i];if(node.localName==localName&&node.namespaceURI==namespaceURI)return node}return null}},DOMImplementation.prototype={hasFeature:function(feature,version){var versions=this._features[feature.toLowerCase()];return versions&&(!version||version in versions)?!0:!1},createDocument:function(namespaceURI,qualifiedName,doctype){var doc=new Document;if(doc.implementation=this,doc.childNodes=new NodeList,doc.doctype=doctype,doctype&&doc.appendChild(doctype),qualifiedName){var root=doc.createElementNS(namespaceURI,qualifiedName);doc.appendChild(root)}return doc},createDocumentType:function(qualifiedName,publicId,systemId){var node=new DocumentType;return node.name=qualifiedName,node.nodeName=qualifiedName,node.publicId=publicId,node.systemId=systemId,node}},Node.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,attributes:null,parentNode:null,childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,insertBefore:function(newChild,refChild){return _insertBefore(this,newChild,refChild)},replaceChild:function(newChild,oldChild){this.insertBefore(newChild,oldChild),oldChild&&this.removeChild(oldChild)},removeChild:function(oldChild){return _removeChild(this,oldChild)},appendChild:function(newChild){return this.insertBefore(newChild,null)},hasChildNodes:function(){return null!=this.firstChild},cloneNode:function(deep){return cloneNode(this.ownerDocument||this,this,deep)},normalize:function(){for(var child=this.firstChild;child;){var next=child.nextSibling;next&&next.nodeType==TEXT_NODE&&child.nodeType==TEXT_NODE?(this.removeChild(next),child.appendData(next.data)):(child.normalize(),child=next)}},isSupported:function(feature,version){return this.ownerDocument.implementation.hasFeature(feature,version)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(namespaceURI){for(var el=this;el;){var map=el._nsMap;if(map)for(var n in map)if(map[n]==namespaceURI)return n;el=2==el.nodeType?el.ownerDocument:el.parentNode}return null},lookupNamespaceURI:function(prefix){for(var el=this;el;){var map=el._nsMap;if(map&&prefix in map)return map[prefix];el=2==el.nodeType?el.ownerDocument:el.parentNode}return null},isDefaultNamespace:function(namespaceURI){var prefix=this.lookupPrefix(namespaceURI);return null==prefix}},copy(NodeType,Node),copy(NodeType,Node.prototype),Document.prototype={nodeName:\"#document\",nodeType:DOCUMENT_NODE,doctype:null,documentElement:null,_inc:1,insertBefore:function(newChild,refChild){if(newChild.nodeType==DOCUMENT_FRAGMENT_NODE){for(var child=newChild.firstChild;child;){var next=child.nextSibling;this.insertBefore(child,refChild),child=next}return newChild}return null==this.documentElement&&1==newChild.nodeType&&(this.documentElement=newChild),_insertBefore(this,newChild,refChild),newChild.ownerDocument=this,newChild},removeChild:function(oldChild){return this.documentElement==oldChild&&(this.documentElement=null),_removeChild(this,oldChild)},importNode:function(importedNode,deep){return importNode(this,importedNode,deep)},getElementById:function(id){var rtv=null;return _visitNode(this.documentElement,function(node){return 1==node.nodeType&&node.getAttribute(\"id\")==id?(rtv=node,!0):void 0}),rtv},createElement:function(tagName){var node=new Element;node.ownerDocument=this,node.nodeName=tagName,node.tagName=tagName,node.childNodes=new NodeList;var attrs=node.attributes=new NamedNodeMap;return attrs._ownerElement=node,node},createDocumentFragment:function(){var node=new DocumentFragment;return node.ownerDocument=this,node.childNodes=new NodeList,node},createTextNode:function(data){var node=new Text;return node.ownerDocument=this,node.appendData(data),node},createComment:function(data){var node=new Comment;return node.ownerDocument=this,node.appendData(data),node},createCDATASection:function(data){var node=new CDATASection;return node.ownerDocument=this,node.appendData(data),node},createProcessingInstruction:function(target,data){var node=new ProcessingInstruction;return node.ownerDocument=this,node.tagName=node.target=target,node.nodeValue=node.data=data,node},createAttribute:function(name){var node=new Attr;return node.ownerDocument=this,node.name=name,node.nodeName=name,node.localName=name,node.specified=!0,node},createEntityReference:function(name){var node=new EntityReference;return node.ownerDocument=this,node.nodeName=name,node},createElementNS:function(namespaceURI,qualifiedName){var node=new Element,pl=qualifiedName.split(\":\"),attrs=node.attributes=new NamedNodeMap;return node.childNodes=new NodeList,node.ownerDocument=this,node.nodeName=qualifiedName,node.tagName=qualifiedName,node.namespaceURI=namespaceURI,2==pl.length?(node.prefix=pl[0],node.localName=pl[1]):node.localName=qualifiedName,attrs._ownerElement=node,node},createAttributeNS:function(namespaceURI,qualifiedName){var node=new Attr,pl=qualifiedName.split(\":\");return node.ownerDocument=this,node.nodeName=qualifiedName,node.name=qualifiedName,node.namespaceURI=namespaceURI,node.specified=!0,2==pl.length?(node.prefix=pl[0],node.localName=pl[1]):node.localName=qualifiedName,node}},_extends(Document,Node),Element.prototype={nodeType:ELEMENT_NODE,hasAttribute:function(name){return null!=this.getAttributeNode(name)},getAttribute:function(name){var attr=this.getAttributeNode(name);return attr&&attr.value||\"\"},getAttributeNode:function(name){return this.attributes.getNamedItem(name)},setAttribute:function(name,value){var attr=this.ownerDocument.createAttribute(name);attr.value=attr.nodeValue=\"\"+value,this.setAttributeNode(attr)},removeAttribute:function(name){var attr=this.getAttributeNode(name);attr&&this.removeAttributeNode(attr)},appendChild:function(newChild){return newChild.nodeType===DOCUMENT_FRAGMENT_NODE?this.insertBefore(newChild,null):_appendSingleChild(this,newChild)},setAttributeNode:function(newAttr){return this.attributes.setNamedItem(newAttr)},setAttributeNodeNS:function(newAttr){return this.attributes.setNamedItemNS(newAttr)},removeAttributeNode:function(oldAttr){return this.attributes.removeNamedItem(oldAttr.nodeName)},removeAttributeNS:function(namespaceURI,localName){var old=this.getAttributeNodeNS(namespaceURI,localName);old&&this.removeAttributeNode(old)},hasAttributeNS:function(namespaceURI,localName){return null!=this.getAttributeNodeNS(namespaceURI,localName)},getAttributeNS:function(namespaceURI,localName){var attr=this.getAttributeNodeNS(namespaceURI,localName);return attr&&attr.value||\"\"},setAttributeNS:function(namespaceURI,qualifiedName,value){var attr=this.ownerDocument.createAttributeNS(namespaceURI,qualifiedName);attr.value=attr.nodeValue=\"\"+value,this.setAttributeNode(attr)},getAttributeNodeNS:function(namespaceURI,localName){return this.attributes.getNamedItemNS(namespaceURI,localName)},getElementsByTagName:function(tagName){return new LiveNodeList(this,function(base){var ls=[];return _visitNode(base,function(node){node===base||node.nodeType!=ELEMENT_NODE||\"*\"!==tagName&&node.tagName!=tagName||ls.push(node)}),ls})},getElementsByTagNameNS:function(namespaceURI,localName){return new LiveNodeList(this,function(base){var ls=[];return _visitNode(base,function(node){node===base||node.nodeType!==ELEMENT_NODE||\"*\"!==namespaceURI&&node.namespaceURI!==namespaceURI||\"*\"!==localName&&node.localName!=localName||ls.push(node)}),ls})}},Document.prototype.getElementsByTagName=Element.prototype.getElementsByTagName,Document.prototype.getElementsByTagNameNS=Element.prototype.getElementsByTagNameNS,_extends(Element,Node),Attr.prototype.nodeType=ATTRIBUTE_NODE,_extends(Attr,Node),CharacterData.prototype={data:\"\",substringData:function(offset,count){return this.data.substring(offset,offset+count)},appendData:function(text){text=this.data+text,this.nodeValue=this.data=text,this.length=text.length},insertData:function(offset,text){this.replaceData(offset,0,text)},appendChild:function(){throw Error(ExceptionMessage[3])},deleteData:function(offset,count){this.replaceData(offset,count,\"\")},replaceData:function(offset,count,text){var start=this.data.substring(0,offset),end=this.data.substring(offset+count);text=start+text+end,this.nodeValue=this.data=text,this.length=text.length}},_extends(CharacterData,Node),Text.prototype={nodeName:\"#text\",nodeType:TEXT_NODE,splitText:function(offset){var text=this.data,newText=text.substring(offset);text=text.substring(0,offset),this.data=this.nodeValue=text,this.length=text.length;var newNode=this.ownerDocument.createTextNode(newText);return this.parentNode&&this.parentNode.insertBefore(newNode,this.nextSibling),newNode}},_extends(Text,CharacterData),Comment.prototype={nodeName:\"#comment\",nodeType:COMMENT_NODE},_extends(Comment,CharacterData),CDATASection.prototype={nodeName:\"#cdata-section\",nodeType:CDATA_SECTION_NODE},_extends(CDATASection,CharacterData),DocumentType.prototype.nodeType=DOCUMENT_TYPE_NODE,_extends(DocumentType,Node),Notation.prototype.nodeType=NOTATION_NODE,_extends(Notation,Node),Entity.prototype.nodeType=ENTITY_NODE,_extends(Entity,Node),EntityReference.prototype.nodeType=ENTITY_REFERENCE_NODE,_extends(EntityReference,Node),DocumentFragment.prototype.nodeName=\"#document-fragment\",DocumentFragment.prototype.nodeType=DOCUMENT_FRAGMENT_NODE,_extends(DocumentFragment,Node),ProcessingInstruction.prototype.nodeType=PROCESSING_INSTRUCTION_NODE,_extends(ProcessingInstruction,Node),XMLSerializer.prototype.serializeToString=function(node){var buf=[];return serializeToString(node,buf),buf.join(\"\")},Node.prototype.toString=function(){return XMLSerializer.prototype.serializeToString(this)};try{Object.defineProperty&&(Object.defineProperty(LiveNodeList.prototype,\"length\",{get:function(){return _updateLiveList(this),this.$$length}}),Object.defineProperty(Node.prototype,\"textContent\",{get:function(){return getTextContent(this)},set:function(data){switch(this.nodeType){case 1:case 11:for(;this.firstChild;)this.removeChild(this.firstChild);(data||data+\"\")&&this.appendChild(this.ownerDocument.createTextNode(data));break;default:this.data=data,this.value=value,this.nodeValue=data}}}),__set__=function(object,key,value){object[\"$$\"+key]=value})}catch(e){}return DOMImplementation}),ace.define(\"ace/mode/xml/dom-parser\",[\"require\",\"exports\",\"module\",\"ace/mode/xml/sax\",\"ace/mode/xml/dom\"],function(acequire){\"use strict\";function DOMParser(options){this.options=options||{locator:{}}}function buildErrorHandler(errorImpl,domBuilder,locator){function build(key){var fn=errorImpl[key];if(!fn)if(isCallback)fn=2==errorImpl.length?function(msg){errorImpl(key,msg)}:errorImpl;else for(var i=arguments.length;--i&&!(fn=errorImpl[arguments[i]]););errorHandler[key]=fn&&function(msg){fn(msg+_locator(locator),msg,locator)}||function(){}}if(!errorImpl){if(domBuilder instanceof DOMHandler)return domBuilder;errorImpl=domBuilder}var errorHandler={},isCallback=errorImpl instanceof Function;return locator=locator||{},build(\"warning\",\"warn\"),build(\"error\",\"warn\",\"warning\"),build(\"fatalError\",\"warn\",\"warning\",\"error\"),errorHandler}function DOMHandler(){this.cdata=!1}function position(locator,node){node.lineNumber=locator.lineNumber,node.columnNumber=locator.columnNumber}function _locator(l){return l?\"\\n@\"+(l.systemId||\"\")+\"#[line:\"+l.lineNumber+\",col:\"+l.columnNumber+\"]\":void 0}function _toString(chars,start,length){return\"string\"==typeof chars?chars.substr(start,length):chars.length>=start+length||start?new java.lang.String(chars,start,length)+\"\":chars}function appendElement(hander,node){hander.currentElement?hander.currentElement.appendChild(node):hander.document.appendChild(node)}var XMLReader=acequire(\"./sax\"),DOMImplementation=acequire(\"./dom\");return DOMParser.prototype.parseFromString=function(source,mimeType){var options=this.options,sax=new XMLReader,domBuilder=options.domBuilder||new DOMHandler,errorHandler=options.errorHandler,locator=options.locator,defaultNSMap=options.xmlns||{},entityMap={lt:\"<\",gt:\">\",amp:\"&\",quot:'\"',apos:\"'\"};return locator&&domBuilder.setDocumentLocator(locator),sax.errorHandler=buildErrorHandler(errorHandler,domBuilder,locator),sax.domBuilder=options.domBuilder||domBuilder,/\\/x?html?$/.test(mimeType)&&(entityMap.nbsp=\" \",entityMap.copy=\"©\",defaultNSMap[\"\"]=\"http://www.w3.org/1999/xhtml\"),source?sax.parse(source,defaultNSMap,entityMap):sax.errorHandler.error(\"invalid document source\"),domBuilder.document},DOMHandler.prototype={startDocument:function(){this.document=(new DOMImplementation).createDocument(null,null,null),this.locator&&(this.document.documentURI=this.locator.systemId)},startElement:function(namespaceURI,localName,qName,attrs){var doc=this.document,el=doc.createElementNS(namespaceURI,qName||localName),len=attrs.length;appendElement(this,el),this.currentElement=el,this.locator&&position(this.locator,el);for(var i=0;len>i;i++){var namespaceURI=attrs.getURI(i),value=attrs.getValue(i),qName=attrs.getQName(i),attr=doc.createAttributeNS(namespaceURI,qName);attr.getOffset&&position(attr.getOffset(1),attr),attr.value=attr.nodeValue=value,el.setAttributeNode(attr)}},endElement:function(){var current=this.currentElement;current.tagName,this.currentElement=current.parentNode},startPrefixMapping:function(){},endPrefixMapping:function(){},processingInstruction:function(target,data){var ins=this.document.createProcessingInstruction(target,data);this.locator&&position(this.locator,ins),appendElement(this,ins)},ignorableWhitespace:function(){},characters:function(chars){if(chars=_toString.apply(this,arguments),this.currentElement&&chars){if(this.cdata){var charNode=this.document.createCDATASection(chars);this.currentElement.appendChild(charNode)}else{var charNode=this.document.createTextNode(chars);this.currentElement.appendChild(charNode)}this.locator&&position(this.locator,charNode)}},skippedEntity:function(){},endDocument:function(){this.document.normalize()},setDocumentLocator:function(locator){(this.locator=locator)&&(locator.lineNumber=0)},comment:function(chars){chars=_toString.apply(this,arguments);var comm=this.document.createComment(chars);this.locator&&position(this.locator,comm),appendElement(this,comm)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(name,publicId,systemId){var impl=this.document.implementation;if(impl&&impl.createDocumentType){var dt=impl.createDocumentType(name,publicId,systemId);this.locator&&position(this.locator,dt),appendElement(this,dt)}},warning:function(error){console.warn(error,_locator(this.locator))},error:function(error){console.error(error,_locator(this.locator))},fatalError:function(error){throw console.error(error,_locator(this.locator)),error}},\"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl\".replace(/\\w+/g,function(key){DOMHandler.prototype[key]=function(){return null}}),{DOMParser:DOMParser}}),ace.define(\"ace/mode/xml_worker\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/lib/lang\",\"ace/worker/mirror\",\"ace/mode/xml/dom-parser\"],function(acequire,exports){\"use strict\";var oop=acequire(\"../lib/oop\");acequire(\"../lib/lang\");var Mirror=acequire(\"../worker/mirror\").Mirror,DOMParser=acequire(\"./xml/dom-parser\").DOMParser,Worker=exports.Worker=function(sender){Mirror.call(this,sender),this.setTimeout(400),this.context=null};oop.inherits(Worker,Mirror),function(){this.setOptions=function(options){this.context=options.context},this.onUpdate=function(){var value=this.doc.getValue();if(value){var parser=new DOMParser,errors=[];parser.options.errorHandler={fatalError:function(fullMsg,errorMsg,locator){errors.push({row:locator.lineNumber,column:locator.columnNumber,text:errorMsg,type:\"error\"})},error:function(fullMsg,errorMsg,locator){errors.push({row:locator.lineNumber,column:locator.columnNumber,text:errorMsg,type:\"error\"})},warning:function(fullMsg,errorMsg,locator){errors.push({row:locator.lineNumber,column:locator.columnNumber,text:errorMsg,type:\"warning\"})}},parser.parseFromString(value),this.sender.emit(\"error\",errors)}}}.call(Worker.prototype)}),ace.define(\"ace/lib/es5-shim\",[\"require\",\"exports\",\"module\"],function(){function Empty(){}function doesDefinePropertyWork(object){try{return Object.defineProperty(object,\"sentinel\",{}),\"sentinel\"in object\n}catch(exception){}}function toInteger(n){return n=+n,n!==n?n=0:0!==n&&n!==1/0&&n!==-(1/0)&&(n=(n>0||-1)*Math.floor(Math.abs(n))),n}Function.prototype.bind||(Function.prototype.bind=function(that){var target=this;if(\"function\"!=typeof target)throw new TypeError(\"Function.prototype.bind called on incompatible \"+target);var args=slice.call(arguments,1),bound=function(){if(this instanceof bound){var result=target.apply(this,args.concat(slice.call(arguments)));return Object(result)===result?result:this}return target.apply(that,args.concat(slice.call(arguments)))};return target.prototype&&(Empty.prototype=target.prototype,bound.prototype=new Empty,Empty.prototype=null),bound});var defineGetter,defineSetter,lookupGetter,lookupSetter,supportsAccessors,call=Function.prototype.call,prototypeOfArray=Array.prototype,prototypeOfObject=Object.prototype,slice=prototypeOfArray.slice,_toString=call.bind(prototypeOfObject.toString),owns=call.bind(prototypeOfObject.hasOwnProperty);if((supportsAccessors=owns(prototypeOfObject,\"__defineGetter__\"))&&(defineGetter=call.bind(prototypeOfObject.__defineGetter__),defineSetter=call.bind(prototypeOfObject.__defineSetter__),lookupGetter=call.bind(prototypeOfObject.__lookupGetter__),lookupSetter=call.bind(prototypeOfObject.__lookupSetter__)),2!=[1,2].splice(0).length)if(function(){function makeArray(l){var a=Array(l+2);return a[0]=a[1]=0,a}var lengthBefore,array=[];return array.splice.apply(array,makeArray(20)),array.splice.apply(array,makeArray(26)),lengthBefore=array.length,array.splice(5,0,\"XXX\"),lengthBefore+1==array.length,lengthBefore+1==array.length?!0:void 0}()){var array_splice=Array.prototype.splice;Array.prototype.splice=function(start,deleteCount){return arguments.length?array_splice.apply(this,[void 0===start?0:start,void 0===deleteCount?this.length-start:deleteCount].concat(slice.call(arguments,2))):[]}}else Array.prototype.splice=function(pos,removeCount){var length=this.length;pos>0?pos>length&&(pos=length):void 0==pos?pos=0:0>pos&&(pos=Math.max(length+pos,0)),length>pos+removeCount||(removeCount=length-pos);var removed=this.slice(pos,pos+removeCount),insert=slice.call(arguments,2),add=insert.length;if(pos===length)add&&this.push.apply(this,insert);else{var remove=Math.min(removeCount,length-pos),tailOldPos=pos+remove,tailNewPos=tailOldPos+add-remove,tailCount=length-tailOldPos,lengthAfterRemove=length-remove;if(tailOldPos>tailNewPos)for(var i=0;tailCount>i;++i)this[tailNewPos+i]=this[tailOldPos+i];else if(tailNewPos>tailOldPos)for(i=tailCount;i--;)this[tailNewPos+i]=this[tailOldPos+i];if(add&&pos===lengthAfterRemove)this.length=lengthAfterRemove,this.push.apply(this,insert);else for(this.length=lengthAfterRemove+add,i=0;add>i;++i)this[pos+i]=insert[i]}return removed};Array.isArray||(Array.isArray=function(obj){return\"[object Array]\"==_toString(obj)});var boxedString=Object(\"a\"),splitString=\"a\"!=boxedString[0]||!(0 in boxedString);if(Array.prototype.forEach||(Array.prototype.forEach=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,thisp=arguments[1],i=-1,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError;for(;length>++i;)i in self&&fun.call(thisp,self[i],i,object)}),Array.prototype.map||(Array.prototype.map=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,result=Array(length),thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)i in self&&(result[i]=fun.call(thisp,self[i],i,object));return result}),Array.prototype.filter||(Array.prototype.filter=function(fun){var value,object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,result=[],thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)i in self&&(value=self[i],fun.call(thisp,value,i,object)&&result.push(value));return result}),Array.prototype.every||(Array.prototype.every=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)if(i in self&&!fun.call(thisp,self[i],i,object))return!1;return!0}),Array.prototype.some||(Array.prototype.some=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)if(i in self&&fun.call(thisp,self[i],i,object))return!0;return!1}),Array.prototype.reduce||(Array.prototype.reduce=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");if(!length&&1==arguments.length)throw new TypeError(\"reduce of empty array with no initial value\");var result,i=0;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i++];break}if(++i>=length)throw new TypeError(\"reduce of empty array with no initial value\")}for(;length>i;i++)i in self&&(result=fun.call(void 0,result,self[i],i,object));return result}),Array.prototype.reduceRight||(Array.prototype.reduceRight=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");if(!length&&1==arguments.length)throw new TypeError(\"reduceRight of empty array with no initial value\");var result,i=length-1;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i--];break}if(0>--i)throw new TypeError(\"reduceRight of empty array with no initial value\")}do i in this&&(result=fun.call(void 0,result,self[i],i,object));while(i--);return result}),Array.prototype.indexOf&&-1==[0,1].indexOf(1,2)||(Array.prototype.indexOf=function(sought){var self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):toObject(this),length=self.length>>>0;if(!length)return-1;var i=0;for(arguments.length>1&&(i=toInteger(arguments[1])),i=i>=0?i:Math.max(0,length+i);length>i;i++)if(i in self&&self[i]===sought)return i;return-1}),Array.prototype.lastIndexOf&&-1==[0,1].lastIndexOf(0,-3)||(Array.prototype.lastIndexOf=function(sought){var self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):toObject(this),length=self.length>>>0;if(!length)return-1;var i=length-1;for(arguments.length>1&&(i=Math.min(i,toInteger(arguments[1]))),i=i>=0?i:length-Math.abs(i);i>=0;i--)if(i in self&&sought===self[i])return i;return-1}),Object.getPrototypeOf||(Object.getPrototypeOf=function(object){return object.__proto__||(object.constructor?object.constructor.prototype:prototypeOfObject)}),!Object.getOwnPropertyDescriptor){var ERR_NON_OBJECT=\"Object.getOwnPropertyDescriptor called on a non-object: \";Object.getOwnPropertyDescriptor=function(object,property){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT+object);if(owns(object,property)){var descriptor,getter,setter;if(descriptor={enumerable:!0,configurable:!0},supportsAccessors){var prototype=object.__proto__;object.__proto__=prototypeOfObject;var getter=lookupGetter(object,property),setter=lookupSetter(object,property);if(object.__proto__=prototype,getter||setter)return getter&&(descriptor.get=getter),setter&&(descriptor.set=setter),descriptor}return descriptor.value=object[property],descriptor}}}if(Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(object){return Object.keys(object)}),!Object.create){var createEmpty;createEmpty=null===Object.prototype.__proto__?function(){return{__proto__:null}}:function(){var empty={};for(var i in empty)empty[i]=null;return empty.constructor=empty.hasOwnProperty=empty.propertyIsEnumerable=empty.isPrototypeOf=empty.toLocaleString=empty.toString=empty.valueOf=empty.__proto__=null,empty},Object.create=function(prototype,properties){var object;if(null===prototype)object=createEmpty();else{if(\"object\"!=typeof prototype)throw new TypeError(\"typeof prototype[\"+typeof prototype+\"] != 'object'\");var Type=function(){};Type.prototype=prototype,object=new Type,object.__proto__=prototype}return void 0!==properties&&Object.defineProperties(object,properties),object}}if(Object.defineProperty){var definePropertyWorksOnObject=doesDefinePropertyWork({}),definePropertyWorksOnDom=\"undefined\"==typeof document||doesDefinePropertyWork(document.createElement(\"div\"));if(!definePropertyWorksOnObject||!definePropertyWorksOnDom)var definePropertyFallback=Object.defineProperty}if(!Object.defineProperty||definePropertyFallback){var ERR_NON_OBJECT_DESCRIPTOR=\"Property description must be an object: \",ERR_NON_OBJECT_TARGET=\"Object.defineProperty called on non-object: \",ERR_ACCESSORS_NOT_SUPPORTED=\"getters & setters can not be defined on this javascript engine\";Object.defineProperty=function(object,property,descriptor){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT_TARGET+object);if(\"object\"!=typeof descriptor&&\"function\"!=typeof descriptor||null===descriptor)throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR+descriptor);if(definePropertyFallback)try{return definePropertyFallback.call(Object,object,property,descriptor)}catch(exception){}if(owns(descriptor,\"value\"))if(supportsAccessors&&(lookupGetter(object,property)||lookupSetter(object,property))){var prototype=object.__proto__;object.__proto__=prototypeOfObject,delete object[property],object[property]=descriptor.value,object.__proto__=prototype}else object[property]=descriptor.value;else{if(!supportsAccessors)throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);owns(descriptor,\"get\")&&defineGetter(object,property,descriptor.get),owns(descriptor,\"set\")&&defineSetter(object,property,descriptor.set)}return object}}Object.defineProperties||(Object.defineProperties=function(object,properties){for(var property in properties)owns(properties,property)&&Object.defineProperty(object,property,properties[property]);return object}),Object.seal||(Object.seal=function(object){return object}),Object.freeze||(Object.freeze=function(object){return object});try{Object.freeze(function(){})}catch(exception){Object.freeze=function(freezeObject){return function(object){return\"function\"==typeof object?object:freezeObject(object)}}(Object.freeze)}if(Object.preventExtensions||(Object.preventExtensions=function(object){return object}),Object.isSealed||(Object.isSealed=function(){return!1}),Object.isFrozen||(Object.isFrozen=function(){return!1}),Object.isExtensible||(Object.isExtensible=function(object){if(Object(object)===object)throw new TypeError;for(var name=\"\";owns(object,name);)name+=\"?\";object[name]=!0;var returnValue=owns(object,name);return delete object[name],returnValue}),!Object.keys){var hasDontEnumBug=!0,dontEnums=[\"toString\",\"toLocaleString\",\"valueOf\",\"hasOwnProperty\",\"isPrototypeOf\",\"propertyIsEnumerable\",\"constructor\"],dontEnumsLength=dontEnums.length;for(var key in{toString:null})hasDontEnumBug=!1;Object.keys=function(object){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(\"Object.keys called on a non-object\");var keys=[];for(var name in object)owns(object,name)&&keys.push(name);if(hasDontEnumBug)for(var i=0,ii=dontEnumsLength;ii>i;i++){var dontEnum=dontEnums[i];owns(object,dontEnum)&&keys.push(dontEnum)}return keys}}Date.now||(Date.now=function(){return(new Date).getTime()});var ws=\"\t\\n\u000b\\f\\r   ᠎              \\u2028\\u2029\";if(!String.prototype.trim||ws.trim()){ws=\"[\"+ws+\"]\";var trimBeginRegexp=RegExp(\"^\"+ws+ws+\"*\"),trimEndRegexp=RegExp(ws+ws+\"*$\");String.prototype.trim=function(){return(this+\"\").replace(trimBeginRegexp,\"\").replace(trimEndRegexp,\"\")}}var toObject=function(o){if(null==o)throw new TypeError(\"can't convert \"+o+\" to object\");return Object(o)}});"; \ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/partials/blank.html b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/partials/blank.html new file mode 100644 index 0000000..9e6eae6 --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/partials/blank.html @@ -0,0 +1,3 @@ +
+ +
diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/partials/editor_events.html b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/partials/editor_events.html new file mode 100644 index 0000000..a31f770 --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/partials/editor_events.html @@ -0,0 +1,24 @@ +
+
JavaScript Code: onHandleMetric(ctrl, htmlnode)
+
    +
  • This code is executed upon every refresh
  • +
  • @param {MetricsPanelCtrl} ctrl Instance of current grafana panel object.
  • +
  • @param {HTMLElement} htmlnode Html DOM node containi html data.
  • +
+
+ + +
+ +
+

+

JavaScript Code: onInit(ctrl, htmlnode)
+
    +
  • This code is executed once, right after the first initialization of the SVG
  • +
  • @param {MetricsPanelCtrl} ctrl Instance of current grafana panel object.
  • +
  • @param {HTMLElement} htmlnode Html DOM node containing html data.
  • +
+
Type in a word like "will" below and press ctrl+space or alt+space to get "rhyme completion"
+ + +
diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/partials/editor_html.html b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/partials/editor_html.html new file mode 100644 index 0000000..0a04211 --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/partials/editor_html.html @@ -0,0 +1,20 @@ +
+
CSS
+
    +
  • This is the CSS that will be used to render the panel.
  • +
  • The content here will be placed inside scoped style tags and will only be available to this panel
  • + +
    + +
+ +
+
HTML
+
    +
  • This is the HTML that will be used to render the panel.
  • + +
    + +
+

diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/plugin.json b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/plugin.json new file mode 100644 index 0000000..e495a68 --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/plugin.json @@ -0,0 +1,37 @@ +{ + "type": "panel", + "name": "HTML", + "id": "aidanmountford-html-panel", + "info": { + "description": "HTML panel for grafana", + "author": { + "name": "aidan@mountford.org", + "url": "https://github.com/aidanmountford/grafana-aidanmountford-html-panel" + }, + "keywords": [ + "html", + "panel" + ], + "logos": { + "small": "img/html-panel-logo-small.png", + "large": "img/html-panel-logo-large.png" + }, + "links": [ + { + "name": "MIT License", + "url": "https://github.com/MarcusCalidus/aidanmountford-html-panel/LICENSE" + }, + { + "name": "Project", + "url": "https://github.com/AidanMountford/aidanmountford-html-panel" + } + ], + "screenshots": [], + "version": "0.0.2", + "updated": "2019-12-27" + }, + "dependencies": { + "grafanaVersion": "3.x.x", + "plugins": [] + } +} \ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/polyfills.js b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/polyfills.js new file mode 100644 index 0000000..c247cfb --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/polyfills.js @@ -0,0 +1,36 @@ +'use strict'; + +System.register([], function (_export, _context) { + "use strict"; + + return { + setters: [], + execute: function () { + // Source: https://github.com/jserz/js_piece/blob/master/DOM/ParentNode/append()/append().md + (function (arr) { + arr.forEach(function (item) { + if (item.hasOwnProperty('append')) { + return; + } + Object.defineProperty(item, 'append', { + configurable: true, + enumerable: true, + writable: true, + value: function append() { + var argArr = Array.prototype.slice.call(arguments), + docFrag = document.createDocumentFragment(); + + argArr.forEach(function (argItem) { + var isNode = argItem instanceof Node; + docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem))); + }); + + this.appendChild(docFrag); + } + }); + }); + })([Element.prototype, Document.prototype, DocumentFragment.prototype]); + } + }; +}); +//# sourceMappingURL=polyfills.js.map diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/polyfills.js.map b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/polyfills.js.map new file mode 100644 index 0000000..67f19f3 --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/polyfills.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/polyfills.js"],"names":["arr","forEach","item","hasOwnProperty","Object","defineProperty","configurable","enumerable","writable","value","append","argArr","Array","prototype","slice","call","arguments","docFrag","document","createDocumentFragment","argItem","isNode","Node","appendChild","createTextNode","String","Element","Document","DocumentFragment"],"mappings":";;;;;;;;AAAA;AACA,aAAC,UAASA,GAAT,EAAc;AACXA,oBAAIC,OAAJ,CAAY,UAASC,IAAT,EAAe;AACvB,wBAAIA,KAAKC,cAAL,CAAoB,QAApB,CAAJ,EAAmC;AAC/B;AACH;AACDC,2BAAOC,cAAP,CAAsBH,IAAtB,EAA4B,QAA5B,EAAsC;AAClCI,sCAAc,IADoB;AAElCC,oCAAY,IAFsB;AAGlCC,kCAAU,IAHwB;AAIlCC,+BAAO,SAASC,MAAT,GAAkB;AACrB,gCAAIC,SAASC,MAAMC,SAAN,CAAgBC,KAAhB,CAAsBC,IAAtB,CAA2BC,SAA3B,CAAb;AAAA,gCACIC,UAAUC,SAASC,sBAAT,EADd;;AAGAR,mCAAOV,OAAP,CAAe,UAASmB,OAAT,EAAkB;AAC7B,oCAAIC,SAASD,mBAAmBE,IAAhC;AACAL,wCAAQM,WAAR,CAAoBF,SAASD,OAAT,GAAmBF,SAASM,cAAT,CAAwBC,OAAOL,OAAP,CAAxB,CAAvC;AACH,6BAHD;;AAKA,iCAAKG,WAAL,CAAiBN,OAAjB;AACH;AAdiC,qBAAtC;AAgBH,iBApBD;AAqBH,aAtBD,EAsBG,CAACS,QAAQb,SAAT,EAAoBc,SAASd,SAA7B,EAAwCe,iBAAiBf,SAAzD,CAtBH","file":"polyfills.js","sourcesContent":["// Source: https://github.com/jserz/js_piece/blob/master/DOM/ParentNode/append()/append().md\n(function(arr) {\n arr.forEach(function(item) {\n if (item.hasOwnProperty('append')) {\n return;\n }\n Object.defineProperty(item, 'append', {\n configurable: true,\n enumerable: true,\n writable: true,\n value: function append() {\n var argArr = Array.prototype.slice.call(arguments),\n docFrag = document.createDocumentFragment();\n\n argArr.forEach(function(argItem) {\n var isNode = argItem instanceof Node;\n docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem)));\n });\n\n this.appendChild(docFrag);\n }\n });\n });\n})([Element.prototype, Document.prototype, DocumentFragment.prototype]);"]} \ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/rendering.js b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/rendering.js new file mode 100644 index 0000000..e73bada --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/rendering.js @@ -0,0 +1,107 @@ +'use strict'; + +System.register(['lodash', 'jquery', 'jquery.flot', 'jquery.flot.pie'], function (_export, _context) { + "use strict"; + + var _, $; + + function link(scope, elem, attrs, ctrl) { + var panel; + var htmlelem = elem[0].getElementsByClassName('html-object')[0]; + elem = elem.find('.html-panel'); + var plotCanvas = elem.find('.plot-canvas'); + var htmlnode; + var htmlShadow; + + ctrl.events.on('render', function () { + render(); + ctrl.renderingCompleted(); + }); + + function setElementHeight() { + try { + var height = ctrl.height || panel.height || ctrl.row.height; + if (_.isString(height)) { + height = parseInt(height.replace('px', ''), 10); + } + + height -= 5; // padding + height -= panel.title ? 24 : 9; // subtract panel title bar + + elem.css('height', height + 'px'); + + return true; + } catch (e) { + // IE throws errors sometimes + return false; + } + } + + function formatter(label, slice) { + return "
" + label + "
" + Math.round(slice.percent) + "%
"; + } + + function addHTML() { + if (!htmlnode.shadowRoot) { + htmlnode.attachShadow({ mode: 'open' }); + } + htmlnode.shadowRoot.innerHTML = "" + panel.html_data; + } + + function resizePlotCanvas() { + var width = elem.width(); + var height = elem.height(); + + var size = Math.min(width, height); + + var plotCss = { + top: '10px', + margin: 'auto', + position: 'relative', + height: size + 'px' + }; + plotCanvas.css(plotCss); + } + + function render() { + panel = ctrl.panel; + + if (setElementHeight()) { + if (htmlelem) { + htmlnode = htmlelem; + + if (htmlnode.getAttribute("name") == 'isInitial') { + htmlnode.removeAttribute("name"); + ctrl.initialized = 0; + } + + resizePlotCanvas(); + + if (!ctrl.initialized) { + addHTML(); + panel.doInit(ctrl, htmlnode.shadowRoot); + ctrl.initialized = 1; + } + + panel.handleMetric(ctrl, htmlnode.shadowRoot); + + htmlnode = null; + } else { + ctrl.initialized = 0; + } + } + } + } + + _export('default', link); + + return { + setters: [function (_lodash) { + _ = _lodash.default; + }, function (_jquery) { + $ = _jquery.default; + }, function (_jqueryFlot) {}, function (_jqueryFlotPie) {}], + execute: function () {} + }; +}); +//# sourceMappingURL=rendering.js.map diff --git a/srv/docker/grafana/data/plugins/aidanmountford-html-panel/rendering.js.map b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/rendering.js.map new file mode 100644 index 0000000..d0dbe98 --- /dev/null +++ b/srv/docker/grafana/data/plugins/aidanmountford-html-panel/rendering.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/rendering.js"],"names":["link","scope","elem","attrs","ctrl","panel","htmlelem","getElementsByClassName","find","plotCanvas","htmlnode","htmlShadow","events","on","render","renderingCompleted","setElementHeight","height","row","_","isString","parseInt","replace","title","css","e","formatter","label","slice","fontSize","color","Math","round","percent","addHTML","shadowRoot","attachShadow","mode","innerHTML","css_data","html_data","resizePlotCanvas","width","size","min","plotCss","top","margin","position","getAttribute","removeAttribute","initialized","doInit","handleMetric","$"],"mappings":";;;;;;;AAKe,WAASA,IAAT,CAAcC,KAAd,EAAqBC,IAArB,EAA2BC,KAA3B,EAAkCC,IAAlC,EAAwC;AACrD,QAAIC,KAAJ;AACA,QAAIC,WAAWJ,KAAK,CAAL,EAAQK,sBAAR,CAA+B,aAA/B,EAA8C,CAA9C,CAAf;AACAL,WAAOA,KAAKM,IAAL,CAAU,aAAV,CAAP;AACA,QAAIC,aAAaP,KAAKM,IAAL,CAAU,cAAV,CAAjB;AACA,QAAIE,QAAJ;AACA,QAAIC,UAAJ;;AAEAP,SAAKQ,MAAL,CAAYC,EAAZ,CAAe,QAAf,EAAyB,YAAW;AAClCC;AACAV,WAAKW,kBAAL;AACD,KAHD;;AAKA,aAASC,gBAAT,GAA4B;AAC1B,UAAI;AACF,YAAIC,SAASb,KAAKa,MAAL,IAAeZ,MAAMY,MAArB,IAA+Bb,KAAKc,GAAL,CAASD,MAArD;AACA,YAAIE,EAAEC,QAAF,CAAWH,MAAX,CAAJ,EAAwB;AACtBA,mBAASI,SAASJ,OAAOK,OAAP,CAAe,IAAf,EAAqB,EAArB,CAAT,EAAmC,EAAnC,CAAT;AACD;;AAEDL,kBAAU,CAAV,CANE,CAMW;AACbA,kBAAUZ,MAAMkB,KAAN,GAAc,EAAd,GAAmB,CAA7B,CAPE,CAO8B;;AAEhCrB,aAAKsB,GAAL,CAAS,QAAT,EAAmBP,SAAS,IAA5B;;AAEA,eAAO,IAAP;AACD,OAZD,CAYE,OAAMQ,CAAN,EAAS;AAAE;AACX,eAAO,KAAP;AACD;AACF;;AAED,aAASC,SAAT,CAAmBC,KAAnB,EAA0BC,KAA1B,EAAiC;AAC/B,aAAO,2BAA2BxB,KAAKC,KAAL,CAAWwB,QAAtC,GAAiD,uCAAjD,GAA2FD,MAAME,KAAjG,GAAyG,KAAzG,GAAiHH,KAAjH,GAAyH,OAAzH,GAAmII,KAAKC,KAAL,CAAWJ,MAAMK,OAAjB,CAAnI,GAA+J,SAAtK;AACD;;AAED,aAASC,OAAT,GAAmB;AACjB,UAAI,CAAExB,SAASyB,UAAf,EAA2B;AACxBzB,iBAAS0B,YAAT,CAAsB,EAAEC,MAAM,MAAR,EAAtB;AACF;AACD3B,eAASyB,UAAT,CAAoBG,SAApB,GAAgC,YAAYjC,MAAMkC,QAAlB,GAA4B,UAA5B,GAAyClC,MAAMmC,SAA/E;AACD;;AAID,aAASC,gBAAT,GAA4B;AAC1B,UAAIC,QAAQxC,KAAKwC,KAAL,EAAZ;AACA,UAAIzB,SAASf,KAAKe,MAAL,EAAb;;AAEA,UAAI0B,OAAOZ,KAAKa,GAAL,CAASF,KAAT,EAAgBzB,MAAhB,CAAX;;AAEA,UAAI4B,UAAU;AACZC,aAAK,MADO;AAEZC,gBAAQ,MAFI;AAGZC,kBAAU,UAHE;AAIZ/B,gBAAS0B,IAAD,GAAS;AAJL,OAAd;AAMAlC,iBAAWe,GAAX,CAAeqB,OAAf;AACD;;AAGD,aAAS/B,MAAT,GAAkB;AAChBT,cAAQD,KAAKC,KAAb;;AAEA,UAAIW,kBAAJ,EAAwB;AACtB,YAAIV,QAAJ,EAAc;AACZI,qBAAWJ,QAAX;;AAEA,cAAII,SAASuC,YAAT,CAAsB,MAAtB,KAAiC,WAArC,EAAkD;AAChDvC,qBAASwC,eAAT,CAAyB,MAAzB;AACA9C,iBAAK+C,WAAL,GAAmB,CAAnB;AACD;;AAEDV;;AAEA,cAAI,CAACrC,KAAK+C,WAAV,EAAuB;AACfjB;AACA7B,kBAAM+C,MAAN,CAAahD,IAAb,EAAmBM,SAASyB,UAA5B;AACA/B,iBAAK+C,WAAL,GAAmB,CAAnB;AACP;;AAED9C,gBAAMgD,YAAN,CAAmBjD,IAAnB,EAAyBM,SAASyB,UAAlC;;AAEAzB,qBAAW,IAAX;AACD,SAnBD,MAoBS;AACPN,eAAK+C,WAAL,GAAmB,CAAnB;AACD;AACF;AACF;AACF;;qBAzFuBnD,I;;;;AALjBmB,O;;AACAmC,O","file":"rendering.js","sourcesContent":["import _ from 'lodash';\nimport $ from 'jquery';\nimport 'jquery.flot';\nimport 'jquery.flot.pie';\n\nexport default function link(scope, elem, attrs, ctrl) {\n var panel;\n var htmlelem = elem[0].getElementsByClassName('html-object')[0];\n elem = elem.find('.html-panel');\n var plotCanvas = elem.find('.plot-canvas');\n var htmlnode;\n var htmlShadow;\n\n ctrl.events.on('render', function() {\n render();\n ctrl.renderingCompleted();\n });\n\n function setElementHeight() {\n try {\n var height = ctrl.height || panel.height || ctrl.row.height;\n if (_.isString(height)) {\n height = parseInt(height.replace('px', ''), 10);\n }\n\n height -= 5; // padding\n height -= panel.title ? 24 : 9; // subtract panel title bar\n\n elem.css('height', height + 'px');\n\n return true;\n } catch(e) { // IE throws errors sometimes\n return false;\n }\n }\n\n function formatter(label, slice) {\n return \"
\" + label + \"
\" + Math.round(slice.percent) + \"%
\";\n }\n\n function addHTML() {\n if (! htmlnode.shadowRoot) {\n htmlnode.attachShadow({ mode: 'open'});\n }\n htmlnode.shadowRoot.innerHTML = \"\" + panel.html_data;\n }\n\n\n\n function resizePlotCanvas() {\n var width = elem.width();\n var height = elem.height();\n\n var size = Math.min(width, height);\n\n var plotCss = {\n top: '10px',\n margin: 'auto',\n position: 'relative',\n height: (size) + 'px'\n };\n plotCanvas.css(plotCss);\n }\n\n\n function render() {\n panel = ctrl.panel;\n\n if (setElementHeight()) {\n if (htmlelem) {\n htmlnode = htmlelem;\n\n if (htmlnode.getAttribute(\"name\") == 'isInitial') {\n htmlnode.removeAttribute(\"name\");\n ctrl.initialized = 0;\n }\n\n resizePlotCanvas();\n\n if (!ctrl.initialized) {\n addHTML();\n panel.doInit(ctrl, htmlnode.shadowRoot);\n ctrl.initialized = 1;\n }\n\n panel.handleMetric(ctrl, htmlnode.shadowRoot);\n\n htmlnode = null;\n }\n else {\n ctrl.initialized = 0;\n }\n }\n }\n}\n\n"]} \ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/MANIFEST.txt b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/MANIFEST.txt new file mode 100644 index 0000000..9deefba --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/MANIFEST.txt @@ -0,0 +1,50 @@ + +-----BEGIN PGP SIGNED MESSAGE----- +Hash: SHA512 + +{ + "manifestVersion": "2.0.0", + "signatureType": "community", + "signedByOrg": "grafana", + "signedByOrgName": "Grafana Labs", + "plugin": "savantly-heatmap-panel", + "version": "0.2.1", + "time": 1622741066287, + "keyId": "7e4d0c6a708866e7", + "files": { + "heatmapEditor.html": "80c1afb1c21b11b22eeadbf68062a3507707fae8bea85efa8a52341f25b569a6", + "displayEditor.html": "c8929259acfee43228cdbb1e61bc2a84bb4fa8fef30141ac4d5bc2c89902cdda", + "properties.js.map": "7d5d976495f563f4cb85ca4770d2da534a97b9b9a70c8da621c3b94d83bba2cf", + "css/heatmap.css": "3c4418e6b56f675f2004a687cc0f9594240f30851dbeb926e74ded6435b085e0", + "css/heatmap.css.map": "6961f3953262b183ef13278b0dc4d871fafb67c4ea4477f73f52b06e2242c0dc", + "module.html": "964b4e25a8a48d47b4b90fb85d7cca816cd042f3337621ad5d10f0a0fb34c79e", + "properties.js": "0939804110c3dfb12a9649fec6001a8c403b9a9a99043f8b224d1b8de46b3920", + "module.js.map": "e50ce84751c196e9710211d8c28327f581ee2cdfef882fe9052fb85a1fb5c501", + "plugin.json": "7dd0dbe6415501b7a7ba8233a0689e57e6f72764551532132fee90d85d4bc6de", + "libs/d3plus/d3plus.min.js": "c381e5bcfe540caa9267e946f4bb7c300f1e8f2d04453e248cf4f48a201cad7a", + "libs/d3plus/d3plus.js": "563ce3c83439cf43a0a98292cfe7774117aee7dbafff65c098a99a31bce7b8c7", + "libs/d3plus/d3plus.full.js": "892243f96b249ca8b11834820d60a03f0f8471ae15cddea4d202c1c4e8a49f5d", + "libs/d3plus/d3plus.full.min.js": "a1fa18301def3cf11f1e69d4547a9943b4b636ccac0cba3881184b8f258cd20b", + "libs/d3/d3.min.js": "a762ca217f7dc1d7eace1d35a067389856810b70e23487082f08bc01f54cdbd4", + "libs/d3/d3.js": "ae9eabdd39bc4eb53905ba27d2b6a3ea56e165147681d9895c712d6d14326478", + "README.md": "d7033e99aa8af059d927de8ca1e46e2969ac7d509a42e71c5b1c986a98866b1c", + "img/timestamp_data.PNG": "f32d5e3c3525c46bdd6ebedb7eaf3035eff2b735851ec1305d7b6e2305a5a22c", + "img/icn-heatmap-panel.svg": "f60466aae62bab47677f610ee2d3f26064b0da36d9769ca3be72b68c9246408f", + "img/heatmap.PNG": "edb73677190e9e806606ab5774ca34c0a30bbdae81c3ce065562c18f5e279a1d", + "module.js": "62068116ddde618e22a98a415ab9ff9c6f9b068ddb461ce147fe5e18ba16a88b", + "heatmapControl.js": "0902a5705ebdd2d0346fbd555a7d904fae32afcf751c099e69567c65a0c4e693", + "series_overrides_heatmap_ctrl.js": "b440b496d2db5e49d7dba0c4c999742bd94e6fcb0d80c85ee0664042ee25b24f", + "heatmapControl.js.map": "50cb635ab209e24ce1064092384146218850365315cbf3434b5d7f8817e041a6", + "series_overrides_heatmap_ctrl.js.map": "d9f57bfc99a551760c28c92d32fac4182cc301496d76dfb444d2c4a311012cb6" + } +} +-----BEGIN PGP SIGNATURE----- +Version: OpenPGP.js v4.10.1 +Comment: https://openpgpjs.org + +wqEEARMKAAYFAmC5EEoACgkQfk0ManCIZud0ogIHdc07O8OH6oP+AEbMzuUn +7GeNGGuPrwR+tVnOqxvEtGpnedOStN7p+LvCfpGF9ZjyIsrIm3aHx07HY66A +8Y8XWq0CCQHxrNcyWr6wB93aucj79Glsho3gSc2Yam7Jk2h+vpve2noKpHFP +WKVU0AsuROf/5+cmm27rkCorB2jLq5UqjDihjQ== +=x7EU +-----END PGP SIGNATURE----- diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/README.md b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/README.md new file mode 100644 index 0000000..71222a6 --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/README.md @@ -0,0 +1,10 @@ +# grafana-heatmap +[![Build Status](https://travis-ci.org/savantly-net/grafana-heatmap.svg?branch=master)](https://travis-ci.org/savantly-net/grafana-heatmap) + +Heatmap Panel Plugin for Grafana + +Example +![Heatmap](https://raw.githubusercontent.com/savantly-net/grafana-heatmap/master/src/img/heatmap.PNG?raw=true) + +Color By Value grouped by timestamp +![Timestamp Data](https://raw.githubusercontent.com/savantly-net/grafana-heatmap/master/src/img/timestamp_data.PNG?raw=true) \ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/css/heatmap.css b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/css/heatmap.css new file mode 100644 index 0000000..3a71113 --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/css/heatmap.css @@ -0,0 +1,386 @@ +.diagram { + overflow: auto; } + +.gradient-values-container .gradient-value-max { + float: right; } + +.diagram g.label div { + color: #333; } + +.diagram div p { + text-align: center; } + +.diagram svg { + margin: auto; + display: block; } + +g.node > * { + fill: white; } + +svg > g { + overflow: visible; + display: block; } + +.diagram-value { + background-color: white; + padding: 3px; + margin-top: 8px; } + +/** LEGEND **/ +div.graph-legend-wrapper .graph-legend-table { + display: inline-table; } + +/* Flowchart variables */ +/* Sequence Diagram variables */ +/* Gantt chart variables */ +.mermaid .label { + font-family: 'trebuchet ms', verdana, arial; + color: #333; } + +.node rect, +.node circle, +.node ellipse, +.node polygon { + fill: #cde498; + stroke: #13540c; + stroke-width: 1px; } + +.edgePath .path { + stroke: green; + stroke-width: 1.5px; } + +.edgeLabel { + background-color: #e8e8e8; } + +.cluster rect { + fill: #cdffb2 !important; + rx: 4 !important; + stroke: #6eaa49 !important; + stroke-width: 1px !important; } + +.cluster text { + fill: #333; } + +.actor { + stroke: #13540c; + fill: #cde498; } + +text.actor { + fill: black; + stroke: none; } + +.actor-line { + stroke: grey; } + +.messageLine0 { + stroke-width: 1.5; + stroke-dasharray: "2 2"; + marker-end: "url(#arrowhead)"; + stroke: green; } + +.messageLine1 { + stroke-width: 1.5; + stroke-dasharray: "2 2"; + stroke: green; } + +#arrowhead { + fill: green; } + +#crosshead path { + fill: green !important; + stroke: green !important; } + +.messageText { + fill: #D8D9DA; + stroke: none; } + +.labelBox { + stroke: #326932; + fill: #cde498; } + +.labelText { + fill: black; + stroke: none; } + +.loopText { + fill: #D8D9DA; + stroke: none; } + +.loopLine { + stroke-width: 2; + stroke-dasharray: "2 2"; + marker-end: "url(#arrowhead)"; + stroke: #326932; } + +.note { + stroke: #6eaa49; + fill: #fff5ad; } + +.noteText { + fill: black; + stroke: none; + font-family: 'trebuchet ms', verdana, arial; + font-size: 14px; } + +/** Section styling */ +.diagram .section { + stroke: none; + opacity: 0.2; } + +.section0 { + fill: #6eaa49; } + +.section2 { + fill: #6eaa49; } + +.section1, +.section3 { + fill: white; + opacity: 0.2; } + +.sectionTitle0 { + fill: #333; } + +.sectionTitle1 { + fill: #333; } + +.sectionTitle2 { + fill: #333; } + +.sectionTitle3 { + fill: #333; } + +.sectionTitle { + text-anchor: start; + font-size: 11px; + text-height: 14px; } + +/* Grid and axis */ +.grid .tick { + stroke: lightgrey; + opacity: 0.3; + shape-rendering: crispEdges; } + +.grid path { + stroke-width: 0; } + +/* Today line */ +.today { + fill: none; + stroke: red; + stroke-width: 2px; } + +/* Task styling */ +/* Default task */ +.task { + stroke-width: 2; } + +.taskText { + text-anchor: middle; + font-size: 11px; } + +.taskTextOutsideRight { + fill: black; + text-anchor: start; + font-size: 11px; } + +.taskTextOutsideLeft { + fill: black; + text-anchor: end; + font-size: 11px; } + +/* Specific task settings for the sections*/ +.taskText0, +.taskText1, +.taskText2, +.taskText3 { + fill: white; } + +.task0, +.task1, +.task2, +.task3 { + fill: #487e3a; + stroke: #13540c; } + +.taskTextOutside0, +.taskTextOutside2 { + fill: black; } + +.taskTextOutside1, +.taskTextOutside3 { + fill: black; } + +/* Active task */ +.active0, +.active1, +.active2, +.active3 { + fill: #cde498; + stroke: #13540c; } + +.activeText0, +.activeText1, +.activeText2, +.activeText3 { + fill: black !important; } + +/* Completed task */ +.done0, +.done1, +.done2, +.done3 { + stroke: grey; + fill: lightgrey; + stroke-width: 2; } + +.doneText0, +.doneText1, +.doneText2, +.doneText3 { + fill: black !important; } + +/* Tasks on the critical line */ +.crit0, +.crit1, +.crit2, +.crit3 { + stroke: #ff8888; + fill: red; + stroke-width: 2; } + +.activeCrit0, +.activeCrit1, +.activeCrit2, +.activeCrit3 { + stroke: #ff8888; + fill: #cde498; + stroke-width: 2; } + +.doneCrit0, +.doneCrit1, +.doneCrit2, +.doneCrit3 { + stroke: #ff8888; + fill: lightgrey; + stroke-width: 2; + cursor: pointer; + shape-rendering: crispEdges; } + +.doneCritText0, +.doneCritText1, +.doneCritText2, +.doneCritText3 { + fill: black !important; } + +.activeCritText0, +.activeCritText1, +.activeCritText2, +.activeCritText3 { + fill: black !important; } + +.titleText { + text-anchor: middle; + font-size: 18px; + fill: black; } + +/* + + +*/ +g.classGroup text { + fill: #13540c; + stroke: none; + font-family: 'trebuchet ms', verdana, arial; + font-size: 14px; } + +g.classGroup rect { + fill: #cde498; + stroke: #13540c; } + +g.classGroup line { + stroke: #13540c; + stroke-width: 1; } + +svg .classLabel .box { + stroke: none; + stroke-width: 0; + fill: #cde498; + opacity: 0.5; } + +svg .classLabel .label { + fill: #13540c; } + +.relation { + stroke: #13540c; + stroke-width: 1; + fill: none; } + +.composition { + fill: #13540c; + stroke: #13540c; + stroke-width: 1; } + +#compositionStart { + fill: #13540c; + stroke: #13540c; + stroke-width: 1; } + +#compositionEnd { + fill: #13540c; + stroke: #13540c; + stroke-width: 1; } + +.aggregation { + fill: #cde498; + stroke: #13540c; + stroke-width: 1; } + +#aggregationStart { + fill: #cde498; + stroke: #13540c; + stroke-width: 1; } + +#aggregationEnd { + fill: #cde498; + stroke: #13540c; + stroke-width: 1; } + +#dependencyStart { + fill: #13540c; + stroke: #13540c; + stroke-width: 1; } + +#dependencyEnd { + fill: #13540c; + stroke: #13540c; + stroke-width: 1; } + +#extensionStart { + fill: #13540c; + stroke: #13540c; + stroke-width: 1; } + +#extensionEnd { + fill: #13540c; + stroke: #13540c; + stroke-width: 1; } + +.node text { + font-family: 'trebuchet ms', verdana, arial; + font-size: 14px; } + +div.mermaidTooltip { + position: absolute; + text-align: center; + max-width: 200px; + padding: 2px; + font-family: 'trebuchet ms', verdana, arial; + font-size: 12px; + background: #cdffb2; + border: 1px solid #6eaa49; + border-radius: 2px; + pointer-events: none; + z-index: 100; } + +/*# sourceMappingURL=heatmap.css.map */ \ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/css/heatmap.css.map b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/css/heatmap.css.map new file mode 100644 index 0000000..267363a --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/css/heatmap.css.map @@ -0,0 +1,9 @@ +{ + "version": 3, + "file": "heatmap.css", + "sources": [ + "../../src/css/heatmap.scss" + ], + "mappings": "AAYA,AAAA,QAAQ,CAAC;EACR,QAAQ,EAAE,IAAK,GACf;;AAED,AAA2B,0BAAD,CAAC,mBAAmB,CAAC;EAC9C,KAAK,EAAE,KAAM,GACb;;AAED,AAAiB,QAAT,CAAC,CAAC,AAAA,MAAM,CAAC,GAAG,CAAC;EACpB,KAAK,EAlBO,IAAI,GAmBhB;;AAED,AAAa,QAAL,CAAC,GAAG,CAAC,CAAC,CAAC;EACd,UAAU,EAAE,MAAO,GACnB;;AAED,AAAS,QAAD,CAAC,GAAG,CAAC;EACZ,MAAM,EAAE,IAAK;EACb,OAAO,EAAE,KAAM,GACf;;AAED,AAAS,CAAR,AAAA,KAAK,GAAG,CAAC,CAAC;EACV,IAAI,EAAE,KAAM,GACZ;;AAED,AAAM,GAAH,GAAG,CAAC,CAAC;EACP,QAAQ,EAAE,OAAQ;EAClB,OAAO,EAAE,KAAM,GACf;;AAED,AAAA,cAAc,CAAC;EACd,gBAAgB,EAAE,KAAM;EACxB,OAAO,EAAE,GAAI;EACb,UAAU,EAAE,GAAI,GAChB;;AAED,cAAc;AACd,AAAyB,GAAtB,AAAA,qBAAqB,CAAC,mBAAmB,CAAC;EAC5C,OAAO,EAAE,YAAa,GACtB;;AAID,yBAAyB;AACzB,gCAAgC;AAChC,2BAA2B;AAC3B,AAAS,QAAD,CAAC,MAAM,CAAC;EACd,WAAW,EAAE,8BAA+B;EAC5C,KAAK,EAzDM,IAAI,GA0DhB;;AACD,AAAM,KAAD,CAAC,IAAI;AACV,AAAM,KAAD,CAAC,MAAM;AACZ,AAAM,KAAD,CAAC,OAAO;AACb,AAAM,KAAD,CAAC,OAAO,CAAC;EACZ,IAAI,EAlES,OAAO;EAmEpB,MAAM,EAjES,OAAO;EAkEtB,YAAY,EAAE,GAAI,GACnB;;AACD,AAAU,SAAD,CAAC,KAAK,CAAC;EACd,MAAM,EAAE,KAAM;EACd,YAAY,EAAE,KAAM,GACrB;;AACD,AAAA,UAAU,CAAC;EACT,gBAAgB,EAtED,OAAO,GAuEvB;;AACD,AAAS,QAAD,CAAC,IAAI,CAAC;EACZ,IAAI,EAxES,OAAO,CAwEA,UAAU;EAC9B,EAAE,EAAE,aAAc;EAClB,MAAM,EAzES,OAAO,CAyEE,UAAU;EAClC,YAAY,EAAE,cAAe,GAC9B;;AACD,AAAS,QAAD,CAAC,IAAI,CAAC;EACZ,IAAI,EAjFO,IAAI,GAkFhB;;AACD,AAAA,MAAM,CAAC;EACL,MAAM,EArFS,OAAO;EAsFtB,IAAI,EAxFS,OAAO,GAyFrB;;AACD,AAAI,IAAA,AAAA,MAAM,CAAC;EACT,IAAI,EAAE,KAAM;EACZ,MAAM,EAAE,IAAK,GACd;;AACD,AAAA,WAAW,CAAC;EACV,MAAM,EAAE,IAAK,GACd;;AACD,AAAA,aAAa,CAAC;EACZ,YAAY,EAAE,GAAI;EAClB,gBAAgB,EAAE,KAAM;EACxB,UAAU,EAAE,iBAAkB;EAC9B,MAAM,EApGO,KAAK,GAqGnB;;AACD,AAAA,aAAa,CAAC;EACZ,YAAY,EAAE,GAAI;EAClB,gBAAgB,EAAE,KAAM;EACxB,MAAM,EAzGO,KAAK,GA0GnB;;AACD,AAAA,UAAU,CAAC;EACT,IAAI,EA5GS,KAAK,GA6GnB;;AACD,AAAW,UAAD,CAAC,IAAI,CAAC;EACd,IAAI,EA/GS,KAAK,CA+GE,UAAU;EAC9B,MAAM,EAhHO,KAAK,CAgHI,UAAU,GACjC;;AACD,AAAA,YAAY,CAAC;EACX,IAAI,EA3GS,OAAO;EA4GpB,MAAM,EAAE,IAAK,GACd;;AACD,AAAA,SAAS,CAAC;EACR,MAAM,EAAE,OAAQ;EAChB,IAAI,EAzHS,OAAO,GA0HrB;;AACD,AAAA,UAAU,CAAC;EACT,IAAI,EAAE,KAAM;EACZ,MAAM,EAAE,IAAK,GACd;;AACD,AAAA,SAAS,CAAC;EACR,IAAI,EAvHS,OAAO;EAwHpB,MAAM,EAAE,IAAK,GACd;;AACD,AAAA,SAAS,CAAC;EACR,YAAY,EAAE,CAAE;EAChB,gBAAgB,EAAE,KAAM;EACxB,UAAU,EAAE,iBAAkB;EAC9B,MAAM,EAAE,OAAQ,GACjB;;AACD,AAAA,KAAK,CAAC;EACJ,MAAM,EAnIS,OAAO;EAoItB,IAAI,EAAE,OAAQ,GACf;;AACD,AAAA,SAAS,CAAC;EACR,IAAI,EAAE,KAAM;EACZ,MAAM,EAAE,IAAK;EACb,WAAW,EAAE,8BAA+B;EAC5C,SAAS,EAAE,IAAK,GACjB;;AACD,sBAAsB;AACtB,AAAS,QAAD,CAAC,QAAQ,CAAC;EAChB,MAAM,EAAE,IAAK;EACb,OAAO,EAAE,GAAI,GACd;;AACD,AAAA,SAAS,CAAC;EACR,IAAI,EAlJW,OAAO,GAmJvB;;AACD,AAAA,SAAS,CAAC;EACR,IAAI,EArJW,OAAO,GAsJvB;;AACD,AAAA,SAAS;AACT,AAAA,SAAS,CAAC;EACR,IAAI,EAAE,KAAM;EACZ,OAAO,EAAE,GAAI,GACd;;AACD,AAAA,cAAc,CAAC;EACb,IAAI,EAjKO,IAAI,GAkKhB;;AACD,AAAA,cAAc,CAAC;EACb,IAAI,EApKO,IAAI,GAqKhB;;AACD,AAAA,cAAc,CAAC;EACb,IAAI,EAvKO,IAAI,GAwKhB;;AACD,AAAA,cAAc,CAAC;EACb,IAAI,EA1KO,IAAI,GA2KhB;;AACD,AAAA,aAAa,CAAC;EACZ,WAAW,EAAE,KAAM;EACnB,SAAS,EAAE,IAAK;EAChB,WAAW,EAAE,IAAK,GACnB;;AACD,mBAAmB;AACnB,AAAM,KAAD,CAAC,KAAK,CAAC;EACV,MAAM,EAAE,SAAU;EAClB,OAAO,EAAE,GAAI;EACb,eAAe,EAAE,UAAW,GAC7B;;AACD,AAAM,KAAD,CAAC,IAAI,CAAC;EACT,YAAY,EAAE,CAAE,GACjB;;AACD,gBAAgB;AAChB,AAAA,MAAM,CAAC;EACL,IAAI,EAAE,IAAK;EACX,MAAM,EAAE,GAAI;EACZ,YAAY,EAAE,GAAI,GACnB;;AACD,kBAAkB;AAClB,kBAAkB;AAClB,AAAA,KAAK,CAAC;EACJ,YAAY,EAAE,CAAE,GACjB;;AACD,AAAA,SAAS,CAAC;EACR,WAAW,EAAE,MAAO;EACpB,SAAS,EAAE,IAAK,GACjB;;AACD,AAAA,qBAAqB,CAAC;EACpB,IAAI,EAAE,KAAM;EACZ,WAAW,EAAE,KAAM;EACnB,SAAS,EAAE,IAAK,GACjB;;AACD,AAAA,oBAAoB,CAAC;EACnB,IAAI,EAAE,KAAM;EACZ,WAAW,EAAE,GAAI;EACjB,SAAS,EAAE,IAAK,GACjB;;AACD,4CAA4C;AAC5C,AAAA,UAAU;AACV,AAAA,UAAU;AACV,AAAA,UAAU;AACV,AAAA,UAAU,CAAC;EACT,IAAI,EAAE,KAAM,GACb;;AACD,AAAA,MAAM;AACN,AAAA,MAAM;AACN,AAAA,MAAM;AACN,AAAA,MAAM,CAAC;EACL,IAAI,EAvNM,OAAO;EAwNjB,MAAM,EAhOS,OAAO,GAiOvB;;AACD,AAAA,iBAAiB;AACjB,AAAA,iBAAiB,CAAC;EAChB,IAAI,EAAE,KAAM,GACb;;AACD,AAAA,iBAAiB;AACjB,AAAA,iBAAiB,CAAC;EAChB,IAAI,EAAE,KAAM,GACb;;AACD,iBAAiB;AACjB,AAAA,QAAQ;AACR,AAAA,QAAQ;AACR,AAAA,QAAQ;AACR,AAAA,QAAQ,CAAC;EACP,IAAI,EAjPS,OAAO;EAkPpB,MAAM,EAhPS,OAAO,GAiPvB;;AACD,AAAA,YAAY;AACZ,AAAA,YAAY;AACZ,AAAA,YAAY;AACZ,AAAA,YAAY,CAAC;EACX,IAAI,EAAE,gBAAiB,GACxB;;AACD,oBAAoB;AACpB,AAAA,MAAM;AACN,AAAA,MAAM;AACN,AAAA,MAAM;AACN,AAAA,MAAM,CAAC;EACL,MAAM,EAAE,IAAK;EACb,IAAI,EAAE,SAAU;EAChB,YAAY,EAAE,CAAE,GACjB;;AACD,AAAA,UAAU;AACV,AAAA,UAAU;AACV,AAAA,UAAU;AACV,AAAA,UAAU,CAAC;EACT,IAAI,EAAE,gBAAiB,GACxB;;AACD,gCAAgC;AAChC,AAAA,MAAM;AACN,AAAA,MAAM;AACN,AAAA,MAAM;AACN,AAAA,MAAM,CAAC;EACL,MAAM,EAAE,OAAQ;EAChB,IAAI,EAAE,GAAI;EACV,YAAY,EAAE,CAAE,GACjB;;AACD,AAAA,YAAY;AACZ,AAAA,YAAY;AACZ,AAAA,YAAY;AACZ,AAAA,YAAY,CAAC;EACX,MAAM,EAAE,OAAQ;EAChB,IAAI,EAvRS,OAAO;EAwRpB,YAAY,EAAE,CAAE,GACjB;;AACD,AAAA,UAAU;AACV,AAAA,UAAU;AACV,AAAA,UAAU;AACV,AAAA,UAAU,CAAC;EACT,MAAM,EAAE,OAAQ;EAChB,IAAI,EAAE,SAAU;EAChB,YAAY,EAAE,CAAE;EAChB,MAAM,EAAE,OAAQ;EAChB,eAAe,EAAE,UAAW,GAC7B;;AACD,AAAA,cAAc;AACd,AAAA,cAAc;AACd,AAAA,cAAc;AACd,AAAA,cAAc,CAAC;EACb,IAAI,EAAE,gBAAiB,GACxB;;AACD,AAAA,gBAAgB;AAChB,AAAA,gBAAgB;AAChB,AAAA,gBAAgB;AAChB,AAAA,gBAAgB,CAAC;EACf,IAAI,EAAE,gBAAiB,GACxB;;AACD,AAAA,UAAU,CAAC;EACT,WAAW,EAAE,MAAO;EACpB,SAAS,EAAE,IAAK;EAChB,IAAI,EAAE,KAAM,GACb;;AACD;;;EAGE;AACF,AAAa,CAAZ,AAAA,WAAW,CAAC,IAAI,CAAC;EAChB,IAAI,EAxTW,OAAO;EAyTtB,MAAM,EAAE,IAAK;EACb,WAAW,EAAE,8BAA+B;EAC5C,SAAS,EAAE,IAAK,GACjB;;AACD,AAAa,CAAZ,AAAA,WAAW,CAAC,IAAI,CAAC;EAChB,IAAI,EAhUS,OAAO;EAiUpB,MAAM,EA/TS,OAAO,GAgUvB;;AACD,AAAa,CAAZ,AAAA,WAAW,CAAC,IAAI,CAAC;EAChB,MAAM,EAlUS,OAAO;EAmUtB,YAAY,EAAE,CAAE,GACjB;;AACD,AAAgB,GAAb,CAAC,WAAW,CAAC,IAAI,CAAC;EACnB,MAAM,EAAE,IAAK;EACb,YAAY,EAAE,CAAE;EAChB,IAAI,EA1US,OAAO;EA2UpB,OAAO,EAAE,GAAI,GACd;;AACD,AAAgB,GAAb,CAAC,WAAW,CAAC,MAAM,CAAC;EACrB,IAAI,EA5UW,OAAO,GA6UvB;;AACD,AAAA,SAAS,CAAC;EACR,MAAM,EA/US,OAAO;EAgVtB,YAAY,EAAE,CAAE;EAChB,IAAI,EAAE,IAAK,GACZ;;AACD,AAAA,YAAY,CAAC;EACX,IAAI,EApVW,OAAO;EAqVtB,MAAM,EArVS,OAAO;EAsVtB,YAAY,EAAE,CAAE,GACjB;;AACD,AAAA,iBAAiB,CAAC;EAChB,IAAI,EAzVW,OAAO;EA0VtB,MAAM,EA1VS,OAAO;EA2VtB,YAAY,EAAE,CAAE,GACjB;;AACD,AAAA,eAAe,CAAC;EACd,IAAI,EA9VW,OAAO;EA+VtB,MAAM,EA/VS,OAAO;EAgWtB,YAAY,EAAE,CAAE,GACjB;;AACD,AAAA,YAAY,CAAC;EACX,IAAI,EArWS,OAAO;EAsWpB,MAAM,EApWS,OAAO;EAqWtB,YAAY,EAAE,CAAE,GACjB;;AACD,AAAA,iBAAiB,CAAC;EAChB,IAAI,EA1WS,OAAO;EA2WpB,MAAM,EAzWS,OAAO;EA0WtB,YAAY,EAAE,CAAE,GACjB;;AACD,AAAA,eAAe,CAAC;EACd,IAAI,EA/WS,OAAO;EAgXpB,MAAM,EA9WS,OAAO;EA+WtB,YAAY,EAAE,CAAE,GACjB;;AACD,AAAA,gBAAgB,CAAC;EACf,IAAI,EAlXW,OAAO;EAmXtB,MAAM,EAnXS,OAAO;EAoXtB,YAAY,EAAE,CAAE,GACjB;;AACD,AAAA,cAAc,CAAC;EACb,IAAI,EAvXW,OAAO;EAwXtB,MAAM,EAxXS,OAAO;EAyXtB,YAAY,EAAE,CAAE,GACjB;;AACD,AAAA,eAAe,CAAC;EACd,IAAI,EA5XW,OAAO;EA6XtB,MAAM,EA7XS,OAAO;EA8XtB,YAAY,EAAE,CAAE,GACjB;;AACD,AAAA,aAAa,CAAC;EACZ,IAAI,EAjYW,OAAO;EAkYtB,MAAM,EAlYS,OAAO;EAmYtB,YAAY,EAAE,CAAE,GACjB;;AACD,AAAM,KAAD,CAAC,IAAI,CAAC;EACT,WAAW,EAAE,8BAA+B;EAC5C,SAAS,EAAE,IAAK,GACjB;;AACD,AAAG,GAAA,AAAA,eAAe,CAAC;EACjB,QAAQ,EAAE,QAAS;EACnB,UAAU,EAAE,MAAO;EACnB,SAAS,EAAE,KAAM;EACjB,OAAO,EAAE,GAAI;EACb,WAAW,EAAE,8BAA+B;EAC5C,SAAS,EAAE,IAAK;EAChB,UAAU,EA5YG,OAAO;EA6YpB,MAAM,EAAE,GAAG,CAAC,KAAK,CA5YF,OAAO;EA6YtB,aAAa,EAAE,GAAI;EACnB,cAAc,EAAE,IAAK;EACrB,OAAO,EAAE,GAAI,GACd", + "names": [] +} \ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/displayEditor.html b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/displayEditor.html new file mode 100644 index 0000000..c8a7606 --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/displayEditor.html @@ -0,0 +1,122 @@ +
+
Legend
+
+ +
+ + + + + +
+
+
+ +
+
+ +
+
Options
+
+ + +
+ +
+ + +
+
+ +
+ +
+ + +   + + + + + Invert + + +
+
+ + +
+
+ + +
+
+ +
+
+
+
Series specific overrides Regex match example: /server[0-3]/i
+
+
+ +
+
+ +
+
+ +
+ +
+ + +
+ +
+
+
+ +
+ +
+
+
+ + +
+
\ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/heatmapControl.js b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/heatmapControl.js new file mode 100644 index 0000000..5b065ed --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/heatmapControl.js @@ -0,0 +1,527 @@ +'use strict'; + +System.register(['./libs/d3/d3', 'app/core/time_series2', 'app/core/utils/kbn', 'app/plugins/sdk', './properties', 'lodash', 'moment', './series_overrides_heatmap_ctrl', './css/heatmap.css!'], function (_export, _context) { + "use strict"; + + var TimeSeries, kbn, MetricsPanelCtrl, heatmapEditor, displayEditor, pluginName, _, moment, _createClass, panelOptions, panelDefaults, HeatmapCtrl; + + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + + function ensureArrayContains(array, value) { + if (array.indexOf(value) == -1) { + array.push(value); + } + } + + function colorToHex(color) { + if (color.substr(0, 1) === '#') { + return color; + } + var digits = color.replace(/[rgba\(\)\ ]/g, '').split(','); + while (digits.length < 3) { + digits.push(255); + } + + var red = parseInt(digits[0]); + var green = parseInt(digits[1]); + var blue = parseInt(digits[2]); + + var rgba = blue | green << 8 | red << 16; + return '#' + rgba.toString(16); + } + + function getColorByXPercentage(canvas, xPercent) { + var x = canvas.width * xPercent || 0; + var context = canvas.getContext("2d"); + var p = context.getImageData(x, 1, 1, 1).data; + var color = 'rgba(' + [p[0] + ',' + p[1] + ',' + p[2] + ',' + p[3]] + ')'; + return color; + } + + return { + setters: [function (_libsD3D) {}, function (_appCoreTime_series) { + TimeSeries = _appCoreTime_series.default; + }, function (_appCoreUtilsKbn) { + kbn = _appCoreUtilsKbn.default; + }, function (_appPluginsSdk) { + MetricsPanelCtrl = _appPluginsSdk.MetricsPanelCtrl; + }, function (_properties) { + heatmapEditor = _properties.heatmapEditor; + displayEditor = _properties.displayEditor; + pluginName = _properties.pluginName; + }, function (_lodash) { + _ = _lodash.default; + }, function (_moment) { + moment = _moment.default; + }, function (_series_overrides_heatmap_ctrl) {}, function (_cssHeatmapCss) {}], + execute: function () { + _createClass = function () { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + return function (Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps); + if (staticProps) defineProperties(Constructor, staticProps); + return Constructor; + }; + }(); + + panelOptions = { + aggregationFunctions: ['avg', 'min', 'max', 'total', 'current', 'count'], + treeMap: { + modes: ['squarify', 'slice', 'dice', 'slice-dice'], + aggregationFunctions: ['sum', 'min', 'max', 'extent', 'mean', 'median', 'quantile', 'variance', 'deviation'], + timestampFormats: ['YYYY-MM-DDTHH', 'YYYY-MM-DDTHH:mm', 'YYYY-MM-DDTHH:mm:ss', 'YYYY-MM-DDTHH:mm:ss.sssZ'] + } + }; + panelDefaults = { + // other style overrides + seriesOverrides: [], + thresholds: '0,10', + colors: ['rgba(50, 172, 45, 1)', 'rgba(241, 255, 0, 1)', 'rgba(245, 54, 54, 1)'], + legend: { + show: true, + min: true, + max: true, + avg: true, + current: true, + total: true + }, + maxDataPoints: 100, + mappingType: 1, + nullPointMode: 'connected', + format: 'none', + valueMaps: [{ value: 'null', op: '=', text: 'N/A' }], + treeMap: { + mode: 'squarify', + groups: [{ key: 'server', value: '/^.*\./g' }], + colorByFunction: 'max', + sizeByFunction: 'constant', + enableTimeBlocks: false, + enableGrouping: true, + debug: false, + depth: 0, + ids: ['alias'], + nodeSizeProperty: "value" + } + }; + + _export('MetricsPanelCtrl', _export('HeatmapCtrl', HeatmapCtrl = function (_MetricsPanelCtrl) { + _inherits(HeatmapCtrl, _MetricsPanelCtrl); + + function HeatmapCtrl($scope, $injector, $sce) { + _classCallCheck(this, HeatmapCtrl); + + var _this2 = _possibleConstructorReturn(this, (HeatmapCtrl.__proto__ || Object.getPrototypeOf(HeatmapCtrl)).call(this, $scope, $injector)); + + _.defaults(_this2.panel, panelDefaults); + + _this2.options = panelOptions; + _this2.panel.chartId = 'chart_' + _this2.panel.id; + _this2.containerDivId = 'container_' + _this2.panel.chartId; + _this2.$sce = $sce; + _this2.events.on('init-edit-mode', _this2.onInitEditMode.bind(_this2)); + _this2.events.on('data-received', _this2.onDataReceived.bind(_this2)); + _this2.events.on('data-snapshot-load', _this2.onDataReceived.bind(_this2)); + _this2.initializePanel(); + return _this2; + } + + _createClass(HeatmapCtrl, [{ + key: 'initializePanel', + value: function initializePanel() { + var d3plusPath = 'plugins/' + pluginName + '/libs/d3plus/d3plus.full.js'; + var _this = this; + var meta = {}; + meta[d3plusPath] = { + format: 'global' + }; + + SystemJS.config({ + meta: meta + }); + + SystemJS.import(d3plusPath).then(function d3plusLoaded() { + console.log('d3plus is loaded'); + _this.events.emit('data-received'); + }); + } + }, { + key: 'handleError', + value: function handleError(err) { + this.getPanelContainer().html('

Error:

' + err + '
'); + } + }, { + key: 'onInitEditMode', + value: function onInitEditMode() { + this.addEditorTab('Heatmap', heatmapEditor, 2); + this.addEditorTab('Display', displayEditor, 3); + } + }, { + key: 'getPanelContainer', + value: function getPanelContainer() { + return $(document.getElementById(this.containerDivId)); + } + }, { + key: 'onDataReceived', + value: function onDataReceived(dataList) { + console.info('received data'); + console.debug(dataList); + if (undefined != dataList) { + this.series = dataList.map(this.seriesHandler.bind(this)); + console.info('mapped dataList to series'); + } + + var preparedData = this.d3plusDataProcessor(this.series); + this.render(preparedData); + } + }, { + key: 'getGroupKeys', + value: function getGroupKeys() { + return this.panel.treeMap.groups.map(function (group) { + return group.key; + }); + } + }, { + key: 'd3plusDataProcessor', + value: function d3plusDataProcessor(dataArray) { + var resultArray = []; + var hasGroups = this.panel.treeMap.groups.length > 0; + + if (!hasGroups) { + // just add the original items since there are no groups + for (var dataIndex = 0; dataIndex < dataArray.length; dataIndex++) { + var newDataItem = Object.assign({}, dataArray[dataIndex], dataArray[dataIndex].stats); + resultArray.push(newDataItem); + } + } else { + // Process Groups + var groupArray = []; + for (var groupIndex = 0; groupIndex < this.panel.treeMap.groups.length; groupIndex++) { + groupArray.push({ + key: this.panel.treeMap.groups[groupIndex].key, + regex: kbn.stringToJsRegex(this.panel.treeMap.groups[groupIndex].value) + }); + } + for (var dataIndex = 0; dataIndex < dataArray.length; dataIndex++) { + var newDataItem = Object.assign({}, dataArray[dataIndex]); + // only add the stats if we arent using granular timeblock data + if (!this.panel.treeMap.enableTimeBlocks) { + Object.assign(newDataItem, dataArray[dataIndex].stats); + } + delete newDataItem.stats; + + for (var groupIndex = 0; groupIndex < groupArray.length; groupIndex++) { + var key = groupArray[groupIndex].key; + var regex = groupArray[groupIndex].regex; + var matches = newDataItem.alias.match(regex); + if (matches && matches.length > 0) { + newDataItem[key] = matches[0]; + } else { + newDataItem[key] = 'NA'; + } + } + resultArray.push(newDataItem); + } + } + + // If we're using timeBlocks mode + // replace the aggregated series with individual records + if (this.panel.treeMap.enableTimeBlocks) { + console.info('creating timeblock records'); + var timeBlockArray = []; + for (var dataIndex = 0; dataIndex < resultArray.length; dataIndex++) { + console.debug('dataIndex:' + dataIndex + ', alias:' + resultArray[dataIndex].alias); + var dataSeries = resultArray[dataIndex]; + for (var dataPointIndex = 0; dataPointIndex < dataSeries.flotpairs.length; dataPointIndex++) { + var dataSeriesCopy = Object.assign({}, dataSeries); + delete dataSeriesCopy.datapoints; + delete dataSeriesCopy.flotpairs; + dataSeriesCopy.count = 1; + dataSeriesCopy.timestamp = dataSeries.flotpairs[dataPointIndex][0]; + dataSeriesCopy.value = dataSeries.flotpairs[dataPointIndex][1]; + timeBlockArray.push(dataSeriesCopy); + } + } + resultArray = timeBlockArray; + } + + return resultArray; + } + }, { + key: 'seriesHandler', + value: function seriesHandler(seriesData) { + var series = new TimeSeries({ + datapoints: seriesData.datapoints, + alias: seriesData.target.replace(/"|,|;|=|:|{|}/g, '_') + }); + series.flotpairs = series.getFlotPairs(this.panel.nullPointMode); + return series; + } + }, { + key: 'addSeriesOverride', + value: function addSeriesOverride(override) { + this.panel.seriesOverrides.push(override || {}); + } + }, { + key: 'addTreeMapGroup', + value: function addTreeMapGroup(group) { + this.panel.treeMap.groups.push(group || {}); + } + }, { + key: 'removeSeriesOverride', + value: function removeSeriesOverride(override) { + this.panel.seriesOverrides = _.without(this.panel.seriesOverrides, override); + this.render(); + } + }, { + key: 'removeTreeMapGroup', + value: function removeTreeMapGroup(group) { + this.panel.treeMap.groups = _.without(this.panel.treeMap.groups, group); + this.render(); + } + }, { + key: 'updateThresholds', + value: function updateThresholds() { + var thresholdCount = this.panel.thresholds.length; + var colorCount = this.panel.colors.length; + this.refresh(); + } + }, { + key: 'changeColor', + value: function changeColor(colorIndex, color) { + this.panel.colors[colorIndex] = color; + } + }, { + key: 'removeColor', + value: function removeColor(colorIndex) { + this.panel.colors.splice(colorIndex, 1); + } + }, { + key: 'addColor', + value: function addColor() { + this.panel.colors.push('rgba(255, 255, 255, 1)'); + } + }, { + key: 'getGradientForValue', + value: function getGradientForValue(data, value) { + var min = Math.min.apply(Math, data.thresholds); + var max = Math.max.apply(Math, data.thresholds); + var absoluteDistance = max - min; + var valueDistanceFromMin = value - min; + var xPercent = valueDistanceFromMin / absoluteDistance; + // Get the smaller number to clamp at 0.99 max + xPercent = Math.min(0.99, xPercent); + // Get the larger number to clamp at 0.01 min + xPercent = Math.max(0.01, xPercent); + + return getColorByXPercentage(this.canvas, xPercent); + } + }, { + key: 'applyOverrides', + value: function applyOverrides(seriesItemAlias) { + var seriesItem = {}, + colorData = {}, + overrides = {}; + console.info('applying overrides for seriesItem'); + console.debug(seriesItemAlias); + console.debug(this.panel.seriesOverrides); + for (var i = 0; i <= this.panel.seriesOverrides.length; i++) { + console.debug('comparing:'); + console.debug(this.panel.seriesOverrides[i]); + if (this.panel.seriesOverrides[i] && this.panel.seriesOverrides[i].alias == seriesItemAlias) { + overrides = this.panel.seriesOverrides[i]; + } + } + colorData.thresholds = (overrides.thresholds || this.panel.thresholds).split(',').map(function (strVale) { + return Number(strVale.trim()); + }); + colorData.colorMap = this.panel.colors; + seriesItem.colorData = colorData; + + seriesItem.valueName = overrides.valueName || this.panel.valueName; + + return seriesItem; + } + }, { + key: 'invertColorOrder', + value: function invertColorOrder() { + this.panel.colors.reverse(); + this.refresh(); + } + }, { + key: 'addTreeMapId', + value: function addTreeMapId() { + this.panel.treeMap.ids.push(''); + this.refresh(); + } + }, { + key: 'removeTreeMapId', + value: function removeTreeMapId(pos) { + this.panel.treeMap.ids.splice(pos, 1); + this.refresh(); + } + }, { + key: 'changeTreeMapId', + value: function changeTreeMapId(idString, pos) { + this.panel.treeMap.ids[pos] = idString; + } + }, { + key: 'link', + value: function link(scope, elem, attrs, ctrl) { + var chartElement = elem.find('.heatmap'); + chartElement.append('
'); + var chartContainer = $(document.getElementById(ctrl.containerDivId)); + console.debug('found chartContainer'); + console.debug(chartContainer); + elem.css('height', ctrl.height + 'px'); + + var canvas = elem.find('.canvas')[0]; + ctrl.canvas = canvas; + var gradientValueMax = elem.find('.gradient-value-max')[0]; + var gradientValueMin = elem.find('.gradient-value-min')[0]; + + var visFormat = { + "text": function text(_text, opts) { + if (opts.key == 'timestamp') { + var timestamp = moment(Number(_text)); + return timestamp.format(ctrl.panel.treeMap.timestampFormat); + } else if (ctrl.getGroupKeys().indexOf(opts.key) > -1) { + return _text; + } else { + return d3plus.string.title(_text, opts); + } + } + }; + + function render(data) { + updateSize(); + updateCanvasStyle(); + updateChart(data); + } + + function updateCanvasStyle() { + canvas.width = Math.max(chartElement[0].clientWidth, 100); + var canvasContext = canvas.getContext("2d"); + canvasContext.clearRect(0, 0, canvas.width, canvas.height); + + var grd = canvasContext.createLinearGradient(0, 0, canvas.width, 0); + var colorWidth = 1 / Math.max(ctrl.panel.colors.length, 1); + for (var i = 0; i < ctrl.panel.colors.length; i++) { + var currentColor = ctrl.panel.colors[i]; + grd.addColorStop(Math.min(colorWidth * i, 1), currentColor); + } + canvasContext.fillStyle = grd; + canvasContext.fillRect(0, 0, canvas.width, 3); + ctrl.canvasContext = canvasContext; + + gradientValueMax.innerText = Math.max.apply(Math, ctrl.panel.thresholds.split(',')); + gradientValueMin.innerText = Math.min.apply(Math, ctrl.panel.thresholds.split(',')); + } + + function updateSize() { + elem.css('height', ctrl.height + 'px'); + } + + function getVisSize(dataPoint) { + if (ctrl.panel.treeMap.sizeByFunction == 'constant') return 1;else { + return dataPoint[ctrl.panel.treeMap.sizeByFunction] || dataPoint.value; + } + } + + function getVisColor(dataPoint) { + var value = dataPoint[ctrl.panel.treeMap.colorByFunction] || dataPoint.value; + var rgbColor = ctrl.getGradientForValue({ thresholds: ctrl.panel.thresholds.split(',') }, value); + var hexColor = colorToHex(rgbColor); + return hexColor; + } + + function updateChart(data) { + d3.select("#" + ctrl.containerDivId).selectAll('*').remove(); + + // Make sure the necessary IDs are added + var idKeys = Array.from(ctrl.panel.treeMap.ids); + if (idKeys.length == 0) { + ensureArrayContains(idKeys, 'alias'); + } + if (ctrl.panel.treeMap.enableTimeBlocks) { + ensureArrayContains(idKeys, 'timestamp'); + } + + // Setup Aggregations + var aggs = {}; + aggs.value = ctrl.panel.treeMap.aggregationFunction; + aggs.current = ctrl.panel.treeMap.aggregationFunction; + aggs.count = 'sum'; + aggs.total = 'sum'; + aggs.avg = 'mean'; + aggs.min = 'min'; + aggs.max = 'max'; + + d3plus.viz().dev(ctrl.panel.treeMap.debug).aggs(aggs).container("#" + ctrl.containerDivId).legend(ctrl.panel.treeMap.showLegend).data(data) + //.type("tree_map") + .type({ "mode": ctrl.panel.treeMap.mode }) // sets the mode of visualization display based on type + .id({ + "value": _.uniq(idKeys), + "grouping": ctrl.panel.treeMap.enableGrouping + }).depth(Number(ctrl.panel.treeMap.depth)).size(getVisSize).height(ctrl.height).width(ctrl.width).color(getVisColor).format(visFormat).draw(); + } + + this.events.on('render', function onRender(data) { + if (typeof d3plus !== 'undefined' && data) { + render(data); + ctrl.renderingCompleted(); + } else { + console.info('d3plus is not loaded yet'); + } + }); + } + }]); + + return HeatmapCtrl; + }(MetricsPanelCtrl))); + + ;HeatmapCtrl.templateUrl = 'module.html'; + + _export('HeatmapCtrl', HeatmapCtrl); + + _export('MetricsPanelCtrl', HeatmapCtrl); + } + }; +}); +//# sourceMappingURL=heatmapControl.js.map diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/heatmapControl.js.map b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/heatmapControl.js.map new file mode 100644 index 0000000..8be5c8e --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/heatmapControl.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/heatmapControl.js"],"names":["ensureArrayContains","array","value","indexOf","push","colorToHex","color","substr","digits","replace","split","length","red","parseInt","green","blue","rgba","toString","getColorByXPercentage","canvas","xPercent","x","width","context","getContext","p","getImageData","data","TimeSeries","kbn","MetricsPanelCtrl","heatmapEditor","displayEditor","pluginName","_","moment","panelOptions","aggregationFunctions","treeMap","modes","timestampFormats","panelDefaults","seriesOverrides","thresholds","colors","legend","show","min","max","avg","current","total","maxDataPoints","mappingType","nullPointMode","format","valueMaps","op","text","mode","groups","key","colorByFunction","sizeByFunction","enableTimeBlocks","enableGrouping","debug","depth","ids","nodeSizeProperty","HeatmapCtrl","$scope","$injector","$sce","defaults","panel","options","chartId","id","containerDivId","events","on","onInitEditMode","bind","onDataReceived","initializePanel","d3plusPath","_this","meta","SystemJS","config","import","then","d3plusLoaded","console","log","emit","err","getPanelContainer","html","addEditorTab","$","document","getElementById","dataList","info","undefined","series","map","seriesHandler","preparedData","d3plusDataProcessor","render","group","dataArray","resultArray","hasGroups","dataIndex","newDataItem","Object","assign","stats","groupArray","groupIndex","regex","stringToJsRegex","matches","alias","match","timeBlockArray","dataSeries","dataPointIndex","flotpairs","dataSeriesCopy","datapoints","count","timestamp","seriesData","target","getFlotPairs","override","without","thresholdCount","colorCount","refresh","colorIndex","splice","Math","apply","absoluteDistance","valueDistanceFromMin","seriesItemAlias","seriesItem","colorData","overrides","i","strVale","Number","trim","colorMap","valueName","reverse","pos","idString","scope","elem","attrs","ctrl","chartElement","find","append","chartContainer","css","height","gradientValueMax","gradientValueMin","visFormat","opts","timestampFormat","getGroupKeys","d3plus","string","title","updateSize","updateCanvasStyle","updateChart","clientWidth","canvasContext","clearRect","grd","createLinearGradient","colorWidth","currentColor","addColorStop","fillStyle","fillRect","innerText","getVisSize","dataPoint","getVisColor","rgbColor","getGradientForValue","hexColor","d3","select","selectAll","remove","idKeys","Array","from","aggs","aggregationFunction","viz","dev","container","showLegend","type","uniq","size","draw","onRender","renderingCompleted","templateUrl"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0aA,UAASA,mBAAT,CAA6BC,KAA7B,EAAoCC,KAApC,EAA2C;AAC1C,MAAID,MAAME,OAAN,CAAcD,KAAd,KAAwB,CAAC,CAA7B,EAAgC;AAC/BD,SAAMG,IAAN,CAAWF,KAAX;AACA;AACD;;AAED,UAASG,UAAT,CAAoBC,KAApB,EAA2B;AACvB,MAAIA,MAAMC,MAAN,CAAa,CAAb,EAAgB,CAAhB,MAAuB,GAA3B,EAAgC;AAC5B,UAAOD,KAAP;AACH;AACD,MAAIE,SAASF,MAAMG,OAAN,CAAc,eAAd,EAA8B,EAA9B,EAAkCC,KAAlC,CAAwC,GAAxC,CAAb;AACA,SAAMF,OAAOG,MAAP,GAAgB,CAAtB,EAAwB;AACvBH,UAAOJ,IAAP,CAAY,GAAZ;AACA;;AAED,MAAIQ,MAAMC,SAASL,OAAO,CAAP,CAAT,CAAV;AACA,MAAIM,QAAQD,SAASL,OAAO,CAAP,CAAT,CAAZ;AACA,MAAIO,OAAOF,SAASL,OAAO,CAAP,CAAT,CAAX;;AAEA,MAAIQ,OAAOD,OAAQD,SAAS,CAAjB,GAAuBF,OAAO,EAAzC;AACA,SAAO,MAAMI,KAAKC,QAAL,CAAc,EAAd,CAAb;AACH;;AAED,UAASC,qBAAT,CAA+BC,MAA/B,EAAuCC,QAAvC,EAAgD;AAC/C,MAAIC,IAAIF,OAAOG,KAAP,GAAeF,QAAf,IAA2B,CAAnC;AACA,MAAIG,UAAUJ,OAAOK,UAAP,CAAkB,IAAlB,CAAd;AACG,MAAIC,IAAIF,QAAQG,YAAR,CAAqBL,CAArB,EAAwB,CAAxB,EAA2B,CAA3B,EAA8B,CAA9B,EAAiCM,IAAzC;AACA,MAAIrB,QAAQ,UAAQ,CAACmB,EAAE,CAAF,IAAM,GAAN,GAAWA,EAAE,CAAF,CAAX,GAAiB,GAAjB,GAAsBA,EAAE,CAAF,CAAtB,GAA4B,GAA5B,GAAiCA,EAAE,CAAF,CAAlC,CAAR,GAAgD,GAA5D;AACA,SAAOnB,KAAP;AACH;;;;AAtcMsB,a;;AACAC,M;;AACCC,mB,kBAAAA,gB;;AACAC,gB,eAAAA,a;AAAeC,gB,eAAAA,a;AAAeC,a,eAAAA,U;;AAC/BC,I;;AACAC,S;;;;;;;;;;;;;;;;;;;;;AAIDC,e,GAAe;AACpBC,0BAAsB,CAAC,KAAD,EAAQ,KAAR,EAAe,KAAf,EAAsB,OAAtB,EAA+B,SAA/B,EAA0C,OAA1C,CADF;AAEpBC,aAAQ;AACJC,YAAO,CAAC,UAAD,EAAa,OAAb,EAAsB,MAAtB,EAA8B,YAA9B,CADH;AAEJF,2BAAsB,CAAC,KAAD,EAAQ,KAAR,EAAe,KAAf,EAAsB,QAAtB,EAAgC,MAAhC,EAAwC,QAAxC,EAAkD,UAAlD,EAA8D,UAA9D,EAA0E,WAA1E,CAFlB;AAGJG,uBAAkB,CAAC,eAAD,EAAkB,kBAAlB,EAAsC,qBAAtC,EAA6D,0BAA7D;AAHd;AAFY,I;AASfC,gB,GAAgB;AACrB;AACGC,qBAAiB,EAFC;AAGrBC,gBAAY,MAHS;AAIrBC,YAAQ,CAAC,sBAAD,EAAyB,sBAAzB,EAAiD,sBAAjD,CAJa;AAKrBC,YAAQ;AACPC,WAAM,IADC;AAEPC,UAAK,IAFE;AAGPC,UAAK,IAHE;AAIPC,UAAK,IAJE;AAKPC,cAAS,IALF;AAMPC,YAAO;AANA,KALa;AAarBC,mBAAe,GAbM;AAcrBC,iBAAa,CAdQ;AAerBC,mBAAe,WAfM;AAgBrBC,YAAQ,MAhBa;AAiBlBC,eAAW,CACT,EAAEtD,OAAO,MAAT,EAAiBuD,IAAI,GAArB,EAA0BC,MAAM,KAAhC,EADS,CAjBO;AAoBlBpB,aAAS;AACRqB,WAAM,UADE;AAERC,aAAQ,CAAC,EAACC,KAAI,QAAL,EAAe3D,OAAO,UAAtB,EAAD,CAFA;AAGR4D,sBAAiB,KAHT;AAIRC,qBAAgB,UAJR;AAKRC,uBAAkB,KALV;AAMRC,qBAAgB,IANR;AAORC,YAAO,KAPC;AAQRC,YAAO,CARC;AASRC,UAAK,CAAC,OAAD,CATG;AAURC,uBAAkB;AAVV;AApBS,I;;sDAkChBC,W;;;AACL,yBAAYC,MAAZ,EAAoBC,SAApB,EAA+BC,IAA/B,EAAqC;AAAA;;AAAA,4HAC9BF,MAD8B,EACtBC,SADsB;;AAEpCtC,OAAEwC,QAAF,CAAW,OAAKC,KAAhB,EAAuBlC,aAAvB;;AAEA,YAAKmC,OAAL,GAAexC,YAAf;AACA,YAAKuC,KAAL,CAAWE,OAAX,GAAqB,WAAW,OAAKF,KAAL,CAAWG,EAA3C;AACA,YAAKC,cAAL,GAAsB,eAAa,OAAKJ,KAAL,CAAWE,OAA9C;AACA,YAAKJ,IAAL,GAAYA,IAAZ;AACA,YAAKO,MAAL,CAAYC,EAAZ,CAAe,gBAAf,EAAiC,OAAKC,cAAL,CAAoBC,IAApB,QAAjC;AACA,YAAKH,MAAL,CAAYC,EAAZ,CAAe,eAAf,EAAgC,OAAKG,cAAL,CAAoBD,IAApB,QAAhC;AACA,YAAKH,MAAL,CAAYC,EAAZ,CAAe,oBAAf,EAAqC,OAAKG,cAAL,CAAoBD,IAApB,QAArC;AACA,YAAKE,eAAL;AAXoC;AAYpC;;;;uCAEgB;AAChB,UAAIC,aAAa,aAAWrD,UAAX,GAAsB,6BAAvC;AACA,UAAIsD,QAAQ,IAAZ;AACA,UAAIC,OAAO,EAAX;AACAA,WAAKF,UAAL,IAAmB;AACZ/B,eAAQ;AADI,OAAnB;;AAIAkC,eAASC,MAAT,CAAgB;AACbF,aAAMA;AADO,OAAhB;;AAIAC,eAASE,MAAT,CAAgBL,UAAhB,EAA4BM,IAA5B,CAAiC,SAASC,YAAT,GAAuB;AACvDC,eAAQC,GAAR,CAAY,kBAAZ;AACAR,aAAMP,MAAN,CAAagB,IAAb,CAAkB,eAAlB;AACA,OAHD;AAIA;;;iCAEWC,G,EAAI;AACf,WAAKC,iBAAL,GAAyBC,IAAzB,CAA8B,uBAAuBF,GAAvB,GAA6B,QAA3D;AACA;;;sCAEgB;AAChB,WAAKG,YAAL,CAAkB,SAAlB,EAA6BrE,aAA7B,EAA4C,CAA5C;AACA,WAAKqE,YAAL,CAAkB,SAAlB,EAA6BpE,aAA7B,EAA4C,CAA5C;AACA;;;yCAEkB;AAClB,aAAOqE,EAAEC,SAASC,cAAT,CAAwB,KAAKxB,cAA7B,CAAF,CAAP;AACA;;;oCAEcyB,Q,EAAS;AACvBV,cAAQW,IAAR,CAAa,eAAb;AACAX,cAAQ5B,KAAR,CAAcsC,QAAd;AACA,UAAGE,aAAaF,QAAhB,EAA0B;AACzB,YAAKG,MAAL,GAAcH,SAASI,GAAT,CAAa,KAAKC,aAAL,CAAmB1B,IAAnB,CAAwB,IAAxB,CAAb,CAAd;AACAW,eAAQW,IAAR,CAAa,2BAAb;AACA;;AAED,UAAIK,eAAe,KAAKC,mBAAL,CAAyB,KAAKJ,MAA9B,CAAnB;AACA,WAAKK,MAAL,CAAYF,YAAZ;AACA;;;oCAEa;AACb,aAAO,KAAKnC,KAAL,CAAWrC,OAAX,CAAmBsB,MAAnB,CAA0BgD,GAA1B,CAA8B,UAASK,KAAT,EAAe;AACnD,cAAOA,MAAMpD,GAAb;AACA,OAFM,CAAP;AAGA;;;yCAKmBqD,S,EAAU;AAC7B,UAAIC,cAAc,EAAlB;AACA,UAAIC,YAAa,KAAKzC,KAAL,CAAWrC,OAAX,CAAmBsB,MAAnB,CAA0BjD,MAA1B,GAAmC,CAApD;;AAEA,UAAG,CAACyG,SAAJ,EAAc;AACb;AACA,YAAK,IAAIC,YAAU,CAAnB,EAAsBA,YAAYH,UAAUvG,MAA5C,EAAoD0G,WAApD,EAAgE;AAC/D,YAAIC,cAAcC,OAAOC,MAAP,CAAc,EAAd,EAAkBN,UAAUG,SAAV,CAAlB,EAAwCH,UAAUG,SAAV,EAAqBI,KAA7D,CAAlB;AACAN,oBAAY/G,IAAZ,CAAiBkH,WAAjB;AACA;AACD,OAND,MAMO;AACN;AACA,WAAII,aAAa,EAAjB;AACA,YAAI,IAAIC,aAAW,CAAnB,EAAsBA,aAAW,KAAKhD,KAAL,CAAWrC,OAAX,CAAmBsB,MAAnB,CAA0BjD,MAA3D,EAAmEgH,YAAnE,EAAgF;AAC/ED,mBAAWtH,IAAX,CAAgB;AACfyD,cAAK,KAAKc,KAAL,CAAWrC,OAAX,CAAmBsB,MAAnB,CAA0B+D,UAA1B,EAAsC9D,GAD5B;AAEf+D,gBAAO/F,IAAIgG,eAAJ,CAAoB,KAAKlD,KAAL,CAAWrC,OAAX,CAAmBsB,MAAnB,CAA0B+D,UAA1B,EAAsCzH,KAA1D;AAFQ,SAAhB;AAIA;AACD,YAAK,IAAImH,YAAU,CAAnB,EAAsBA,YAAYH,UAAUvG,MAA5C,EAAoD0G,WAApD,EAAgE;AAC/D,YAAIC,cAAcC,OAAOC,MAAP,CAAc,EAAd,EAAkBN,UAAUG,SAAV,CAAlB,CAAlB;AACA;AACA,YAAG,CAAC,KAAK1C,KAAL,CAAWrC,OAAX,CAAmB0B,gBAAvB,EAAwC;AACvCuD,gBAAOC,MAAP,CAAcF,WAAd,EAA2BJ,UAAUG,SAAV,EAAqBI,KAAhD;AACA;AACD,eAAOH,YAAYG,KAAnB;;AAEA,aAAI,IAAIE,aAAW,CAAnB,EAAsBA,aAAaD,WAAW/G,MAA9C,EAAsDgH,YAAtD,EAAmE;AAClE,aAAI9D,MAAM6D,WAAWC,UAAX,EAAuB9D,GAAjC;AACA,aAAI+D,QAAQF,WAAWC,UAAX,EAAuBC,KAAnC;AACA,aAAIE,UAAUR,YAAYS,KAAZ,CAAkBC,KAAlB,CAAwBJ,KAAxB,CAAd;AACA,aAAIE,WAAWA,QAAQnH,MAAR,GAAiB,CAAhC,EAAkC;AACjC2G,sBAAYzD,GAAZ,IAAmBiE,QAAQ,CAAR,CAAnB;AACA,UAFD,MAEO;AACNR,sBAAYzD,GAAZ,IAAmB,IAAnB;AACA;AACD;AACDsD,oBAAY/G,IAAZ,CAAiBkH,WAAjB;AACA;AACD;;AAGD;AACA;AACA,UAAG,KAAK3C,KAAL,CAAWrC,OAAX,CAAmB0B,gBAAtB,EAAuC;AACtC8B,eAAQW,IAAR,CAAa,4BAAb;AACA,WAAIwB,iBAAiB,EAArB;AACA,YAAK,IAAIZ,YAAU,CAAnB,EAAsBA,YAAYF,YAAYxG,MAA9C,EAAsD0G,WAAtD,EAAkE;AACjEvB,gBAAQ5B,KAAR,CAAc,eAAamD,SAAb,GAAuB,UAAvB,GAAkCF,YAAYE,SAAZ,EAAuBU,KAAvE;AACA,YAAIG,aAAaf,YAAYE,SAAZ,CAAjB;AACA,aAAI,IAAIc,iBAAe,CAAvB,EAA0BA,iBAAiBD,WAAWE,SAAX,CAAqBzH,MAAhE,EAAwEwH,gBAAxE,EAAyF;AACxF,aAAIE,iBAAiBd,OAAOC,MAAP,CAAc,EAAd,EAAkBU,UAAlB,CAArB;AACA,gBAAOG,eAAeC,UAAtB;AACA,gBAAOD,eAAeD,SAAtB;AACAC,wBAAeE,KAAf,GAAuB,CAAvB;AACAF,wBAAeG,SAAf,GAA2BN,WAAWE,SAAX,CAAqBD,cAArB,EAAqC,CAArC,CAA3B;AACAE,wBAAenI,KAAf,GAAuBgI,WAAWE,SAAX,CAAqBD,cAArB,EAAqC,CAArC,CAAvB;AACAF,wBAAe7H,IAAf,CAAoBiI,cAApB;AACA;AACD;AACDlB,qBAAcc,cAAd;AACA;;AAED,aAAOd,WAAP;AACA;;;mCAKasB,U,EAAY;AACzB,UAAI9B,SAAS,IAAI/E,UAAJ,CAAe;AAC3B0G,mBAAYG,WAAWH,UADI;AAE3BP,cAAOU,WAAWC,MAAX,CAAkBjI,OAAlB,CAA0B,gBAA1B,EAA4C,GAA5C;AAFoB,OAAf,CAAb;AAIGkG,aAAOyB,SAAP,GAAmBzB,OAAOgC,YAAP,CAAoB,KAAKhE,KAAL,CAAWrB,aAA/B,CAAnB;AACA,aAAOqD,MAAP;AACH;;;uCAEiBiC,Q,EAAU;AAC3B,WAAKjE,KAAL,CAAWjC,eAAX,CAA2BtC,IAA3B,CAAgCwI,YAAY,EAA5C;AACA;;;qCAEe3B,K,EAAO;AACtB,WAAKtC,KAAL,CAAWrC,OAAX,CAAmBsB,MAAnB,CAA0BxD,IAA1B,CAA+B6G,SAAS,EAAxC;AACA;;;0CAEoB2B,Q,EAAU;AAC9B,WAAKjE,KAAL,CAAWjC,eAAX,GAA6BR,EAAE2G,OAAF,CAAU,KAAKlE,KAAL,CAAWjC,eAArB,EAAsCkG,QAAtC,CAA7B;AACG,WAAK5B,MAAL;AACH;;;wCAEkBC,K,EAAO;AACzB,WAAKtC,KAAL,CAAWrC,OAAX,CAAmBsB,MAAnB,GAA4B1B,EAAE2G,OAAF,CAAU,KAAKlE,KAAL,CAAWrC,OAAX,CAAmBsB,MAA7B,EAAqCqD,KAArC,CAA5B;AACG,WAAKD,MAAL;AACH;;;wCAEiB;AACjB,UAAI8B,iBAAiB,KAAKnE,KAAL,CAAWhC,UAAX,CAAsBhC,MAA3C;AACA,UAAIoI,aAAa,KAAKpE,KAAL,CAAW/B,MAAX,CAAkBjC,MAAnC;AACA,WAAKqI,OAAL;AACA;;;iCAEWC,U,EAAY3I,K,EAAM;AAC7B,WAAKqE,KAAL,CAAW/B,MAAX,CAAkBqG,UAAlB,IAAgC3I,KAAhC;AACA;;;iCAEW2I,U,EAAW;AACtB,WAAKtE,KAAL,CAAW/B,MAAX,CAAkBsG,MAAlB,CAAyBD,UAAzB,EAAoC,CAApC;AACA;;;gCAES;AACT,WAAKtE,KAAL,CAAW/B,MAAX,CAAkBxC,IAAlB,CAAuB,wBAAvB;AACA;;;yCAEmBuB,I,EAAMzB,K,EAAM;AAC/B,UAAI6C,MAAMoG,KAAKpG,GAAL,CAASqG,KAAT,CAAeD,IAAf,EAAqBxH,KAAKgB,UAA1B,CAAV;AACA,UAAIK,MAAMmG,KAAKnG,GAAL,CAASoG,KAAT,CAAeD,IAAf,EAAqBxH,KAAKgB,UAA1B,CAAV;AACA,UAAI0G,mBAAmBrG,MAAMD,GAA7B;AACA,UAAIuG,uBAAuBpJ,QAAQ6C,GAAnC;AACA,UAAI3B,WAAWkI,uBAAqBD,gBAApC;AACA;AACAjI,iBAAW+H,KAAKpG,GAAL,CAAS,IAAT,EAAe3B,QAAf,CAAX;AACA;AACAA,iBAAW+H,KAAKnG,GAAL,CAAS,IAAT,EAAe5B,QAAf,CAAX;;AAEA,aAAOF,sBAAsB,KAAKC,MAA3B,EAAmCC,QAAnC,CAAP;AACA;;;oCAEcmI,e,EAAgB;AAC9B,UAAIC,aAAa,EAAjB;AAAA,UAAqBC,YAAY,EAAjC;AAAA,UAAqCC,YAAY,EAAjD;AACA5D,cAAQW,IAAR,CAAa,mCAAb;AACAX,cAAQ5B,KAAR,CAAcqF,eAAd;AACAzD,cAAQ5B,KAAR,CAAc,KAAKS,KAAL,CAAWjC,eAAzB;AACA,WAAI,IAAIiH,IAAE,CAAV,EAAaA,KAAG,KAAKhF,KAAL,CAAWjC,eAAX,CAA2B/B,MAA3C,EAAmDgJ,GAAnD,EAAuD;AACtD7D,eAAQ5B,KAAR,CAAc,YAAd;AACA4B,eAAQ5B,KAAR,CAAc,KAAKS,KAAL,CAAWjC,eAAX,CAA2BiH,CAA3B,CAAd;AACA,WAAI,KAAKhF,KAAL,CAAWjC,eAAX,CAA2BiH,CAA3B,KAAiC,KAAKhF,KAAL,CAAWjC,eAAX,CAA2BiH,CAA3B,EAA8B5B,KAA9B,IAAuCwB,eAA5E,EAA4F;AAC3FG,oBAAY,KAAK/E,KAAL,CAAWjC,eAAX,CAA2BiH,CAA3B,CAAZ;AACA;AACD;AACDF,gBAAU9G,UAAV,GAAuB,CAAC+G,UAAU/G,UAAV,IAAwB,KAAKgC,KAAL,CAAWhC,UAApC,EAAgDjC,KAAhD,CAAsD,GAAtD,EAA2DkG,GAA3D,CAA+D,UAASgD,OAAT,EAAkB;AACvG,cAAOC,OAAOD,QAAQE,IAAR,EAAP,CAAP;AACA,OAFsB,CAAvB;AAGAL,gBAAUM,QAAV,GAAqB,KAAKpF,KAAL,CAAW/B,MAAhC;AACA4G,iBAAWC,SAAX,GAAuBA,SAAvB;;AAEAD,iBAAWQ,SAAX,GAAuBN,UAAUM,SAAV,IAAuB,KAAKrF,KAAL,CAAWqF,SAAzD;;AAEA,aAAOR,UAAP;AACA;;;wCAEkB;AACf,WAAK7E,KAAL,CAAW/B,MAAX,CAAkBqH,OAAlB;AACA,WAAKjB,OAAL;AACH;;;oCAEa;AACb,WAAKrE,KAAL,CAAWrC,OAAX,CAAmB8B,GAAnB,CAAuBhE,IAAvB,CAA4B,EAA5B;AACA,WAAK4I,OAAL;AACA;;;qCAEekB,G,EAAI;AACnB,WAAKvF,KAAL,CAAWrC,OAAX,CAAmB8B,GAAnB,CAAuB8E,MAAvB,CAA8BgB,GAA9B,EAAkC,CAAlC;AACA,WAAKlB,OAAL;AACA;;;qCAEemB,Q,EAAUD,G,EAAI;AAC7B,WAAKvF,KAAL,CAAWrC,OAAX,CAAmB8B,GAAnB,CAAuB8F,GAAvB,IAA8BC,QAA9B;AACA;;;0BAMIC,K,EAAOC,I,EAAMC,K,EAAOC,I,EAAM;AAC9B,UAAIC,eAAeH,KAAKI,IAAL,CAAU,UAAV,CAAnB;AACAD,mBAAaE,MAAb,CAAoB,cAAYH,KAAKxF,cAAjB,GAAgC,UAApD;AACG,UAAI4F,iBAAiBtE,EAAEC,SAASC,cAAT,CAAwBgE,KAAKxF,cAA7B,CAAF,CAArB;AACAe,cAAQ5B,KAAR,CAAc,sBAAd;AACA4B,cAAQ5B,KAAR,CAAcyG,cAAd;AACAN,WAAKO,GAAL,CAAS,QAAT,EAAmBL,KAAKM,MAAL,GAAc,IAAjC;;AAEA,UAAI1J,SAASkJ,KAAKI,IAAL,CAAU,SAAV,EAAqB,CAArB,CAAb;AACAF,WAAKpJ,MAAL,GAAcA,MAAd;AACA,UAAI2J,mBAAmBT,KAAKI,IAAL,CAAU,qBAAV,EAAiC,CAAjC,CAAvB;AACA,UAAIM,mBAAmBV,KAAKI,IAAL,CAAU,qBAAV,EAAiC,CAAjC,CAAvB;;AAGA,UAAIO,YACP;AACC,eAAS,cAAStH,KAAT,EAAeuH,IAAf,EAAqB;AAC7B,YAAGA,KAAKpH,GAAL,IAAY,WAAf,EAA2B;AAC1B,aAAI2E,YAAYrG,OAAO0H,OAAOnG,KAAP,CAAP,CAAhB;AACA,gBAAO8E,UAAUjF,MAAV,CAAiBgH,KAAK5F,KAAL,CAAWrC,OAAX,CAAmB4I,eAApC,CAAP;AACA,SAHD,MAIK,IAAGX,KAAKY,YAAL,GAAoBhL,OAApB,CAA4B8K,KAAKpH,GAAjC,IAAsC,CAAC,CAA1C,EAA6C;AACjD,gBAAOH,KAAP;AACA,SAFI,MAGD;AACH,gBAAO0H,OAAOC,MAAP,CAAcC,KAAd,CAAoB5H,KAApB,EAA0BuH,IAA1B,CAAP;AACA;AACD;AAZF,OADG;;AAiBA,eAASjE,MAAT,CAAgBrF,IAAhB,EAAqB;AACpB4J;AACAC;AACAC,mBAAY9J,IAAZ;AACA;;AAED,eAAS6J,iBAAT,GAA4B;AAC3BrK,cAAOG,KAAP,GAAe6H,KAAKnG,GAAL,CAASwH,aAAa,CAAb,EAAgBkB,WAAzB,EAAsC,GAAtC,CAAf;AACH,WAAIC,gBAAgBxK,OAAOK,UAAP,CAAkB,IAAlB,CAApB;AACAmK,qBAAcC,SAAd,CAAwB,CAAxB,EAA2B,CAA3B,EAA8BzK,OAAOG,KAArC,EAA4CH,OAAO0J,MAAnD;;AAEA,WAAIgB,MAAMF,cAAcG,oBAAd,CAAmC,CAAnC,EAAsC,CAAtC,EAAyC3K,OAAOG,KAAhD,EAAuD,CAAvD,CAAV;AACA,WAAIyK,aAAa,IAAI5C,KAAKnG,GAAL,CAASuH,KAAK5F,KAAL,CAAW/B,MAAX,CAAkBjC,MAA3B,EAAmC,CAAnC,CAArB;AACA,YAAI,IAAIgJ,IAAE,CAAV,EAAaA,IAAEY,KAAK5F,KAAL,CAAW/B,MAAX,CAAkBjC,MAAjC,EAAyCgJ,GAAzC,EAA6C;AAC5C,YAAIqC,eAAezB,KAAK5F,KAAL,CAAW/B,MAAX,CAAkB+G,CAAlB,CAAnB;AACAkC,YAAII,YAAJ,CAAiB9C,KAAKpG,GAAL,CAASgJ,aAAWpC,CAApB,EAAsB,CAAtB,CAAjB,EAA2CqC,YAA3C;AACA;AACDL,qBAAcO,SAAd,GAA0BL,GAA1B;AACAF,qBAAcQ,QAAd,CAAuB,CAAvB,EAA0B,CAA1B,EAA6BhL,OAAOG,KAApC,EAA2C,CAA3C;AACGiJ,YAAKoB,aAAL,GAAqBA,aAArB;;AAEHb,wBAAiBsB,SAAjB,GAA6BjD,KAAKnG,GAAL,CAASoG,KAAT,CAAeD,IAAf,EAAqBoB,KAAK5F,KAAL,CAAWhC,UAAX,CAAsBjC,KAAtB,CAA4B,GAA5B,CAArB,CAA7B;AACAqK,wBAAiBqB,SAAjB,GAA6BjD,KAAKpG,GAAL,CAASqG,KAAT,CAAeD,IAAf,EAAqBoB,KAAK5F,KAAL,CAAWhC,UAAX,CAAsBjC,KAAtB,CAA4B,GAA5B,CAArB,CAA7B;AACG;;AAED,eAAS6K,UAAT,GAAqB;AACpBlB,YAAKO,GAAL,CAAS,QAAT,EAAmBL,KAAKM,MAAL,GAAc,IAAjC;AACA;;AAED,eAASwB,UAAT,CAAoBC,SAApB,EAA8B;AAC7B,WAAG/B,KAAK5F,KAAL,CAAWrC,OAAX,CAAmByB,cAAnB,IAAqC,UAAxC,EAAoD,OAAO,CAAP,CAApD,KACK;AACD,eAAOuI,UAAU/B,KAAK5F,KAAL,CAAWrC,OAAX,CAAmByB,cAA7B,KAAgDuI,UAAUpM,KAAjE;AACH;AACD;;AAED,eAASqM,WAAT,CAAqBD,SAArB,EAA+B;AAC9B,WAAIpM,QAAQoM,UAAU/B,KAAK5F,KAAL,CAAWrC,OAAX,CAAmBwB,eAA7B,KAAiDwI,UAAUpM,KAAvE;AACA,WAAIsM,WAAWjC,KAAKkC,mBAAL,CAAyB,EAAC9J,YAAY4H,KAAK5F,KAAL,CAAWhC,UAAX,CAAsBjC,KAAtB,CAA4B,GAA5B,CAAb,EAAzB,EAAyER,KAAzE,CAAf;AACH,WAAIwM,WAAWrM,WAAWmM,QAAX,CAAf;AACA,cAAOE,QAAP;AACG;;AAGD,eAASjB,WAAT,CAAqB9J,IAArB,EAA0B;AACzBgL,UAAGC,MAAH,CAAU,MAAIrC,KAAKxF,cAAnB,EAAmC8H,SAAnC,CAA6C,GAA7C,EAAkDC,MAAlD;;AAEA;AACA,WAAIC,SAASC,MAAMC,IAAN,CAAW1C,KAAK5F,KAAL,CAAWrC,OAAX,CAAmB8B,GAA9B,CAAb;AACA,WAAG2I,OAAOpM,MAAP,IAAiB,CAApB,EAAsB;AACrBX,4BAAoB+M,MAApB,EAA4B,OAA5B;AACA;AACD,WAAGxC,KAAK5F,KAAL,CAAWrC,OAAX,CAAmB0B,gBAAtB,EAAuC;AACtChE,4BAAoB+M,MAApB,EAA4B,WAA5B;AACA;;AAED;AACA,WAAIG,OAAO,EAAX;AACAA,YAAKhN,KAAL,GAAaqK,KAAK5F,KAAL,CAAWrC,OAAX,CAAmB6K,mBAAhC;AACAD,YAAKhK,OAAL,GAAeqH,KAAK5F,KAAL,CAAWrC,OAAX,CAAmB6K,mBAAlC;AACAD,YAAK3E,KAAL,GAAa,KAAb;AACA2E,YAAK/J,KAAL,GAAa,KAAb;AACA+J,YAAKjK,GAAL,GAAW,MAAX;AACAiK,YAAKnK,GAAL,GAAW,KAAX;AACAmK,YAAKlK,GAAL,GAAW,KAAX;;AAEAoI,cAAOgC,GAAP,GACDC,GADC,CACG9C,KAAK5F,KAAL,CAAWrC,OAAX,CAAmB4B,KADtB,EAEEgJ,IAFF,CAEOA,IAFP,EAGEI,SAHF,CAGY,MAAI/C,KAAKxF,cAHrB,EAIElC,MAJF,CAIS0H,KAAK5F,KAAL,CAAWrC,OAAX,CAAmBiL,UAJ5B,EAKE5L,IALF,CAKOA,IALP;AAMC;AAND,QAOE6L,IAPF,CAOO,EAAC,QAAQjD,KAAK5F,KAAL,CAAWrC,OAAX,CAAmBqB,IAA5B,EAPP,EAO6C;AAP7C,QAQEmB,EARF,CAQK;AACH,iBAAS5C,EAAEuL,IAAF,CAAOV,MAAP,CADN;AAEH,oBAAYxC,KAAK5F,KAAL,CAAWrC,OAAX,CAAmB2B;AAF5B,QARL,EAYEE,KAZF,CAYQ0F,OAAOU,KAAK5F,KAAL,CAAWrC,OAAX,CAAmB6B,KAA1B,CAZR,EAaEuJ,IAbF,CAaOrB,UAbP,EAcExB,MAdF,CAcSN,KAAKM,MAdd,EAeEvJ,KAfF,CAeQiJ,KAAKjJ,KAfb,EAgBEhB,KAhBF,CAgBQiM,WAhBR,EAiBEhJ,MAjBF,CAiBSyH,SAjBT,EAkBE2C,IAlBF;AAmBA;;AAGD,WAAK3I,MAAL,CAAYC,EAAZ,CAAe,QAAf,EAAyB,SAAS2I,QAAT,CAAkBjM,IAAlB,EAAwB;AAChD,WAAG,OAAOyJ,MAAP,KAAkB,WAAlB,IAAiCzJ,IAApC,EAAyC;AACxCqF,eAAOrF,IAAP;AACA4I,aAAKsD,kBAAL;AACA,QAHD,MAGO;AACN/H,gBAAQW,IAAR,CAAa,0BAAb;AACA;AACD,OAPD;AASH;;;;KAjXwB3E,gB;;AA0YzB,IAUDwC,YAAYwJ,WAAZ,GAA0B,aAA1B;;0BAGCxJ,W;;+BACAA,W","file":"heatmapControl.js","sourcesContent":["import './libs/d3/d3'; \r\nimport TimeSeries from 'app/core/time_series2';\r\nimport kbn from 'app/core/utils/kbn';\r\nimport {MetricsPanelCtrl} from 'app/plugins/sdk';\r\nimport {heatmapEditor, displayEditor, pluginName} from './properties';\r\nimport _ from 'lodash';\r\nimport moment from 'moment';\r\nimport './series_overrides_heatmap_ctrl';\r\nimport './css/heatmap.css!';\r\n\r\nconst panelOptions = {\r\n\taggregationFunctions: ['avg', 'min', 'max', 'total', 'current', 'count'],\r\n\ttreeMap:{\r\n \tmodes: ['squarify', 'slice', 'dice', 'slice-dice'],\r\n \taggregationFunctions: ['sum', 'min', 'max', 'extent', 'mean', 'median', 'quantile', 'variance', 'deviation'],\r\n \ttimestampFormats: ['YYYY-MM-DDTHH', 'YYYY-MM-DDTHH:mm', 'YYYY-MM-DDTHH:mm:ss', 'YYYY-MM-DDTHH:mm:ss.sssZ']\r\n\t}\r\n};\r\n\r\nconst panelDefaults = {\r\n\t// other style overrides\r\n seriesOverrides: [],\r\n\tthresholds: '0,10',\r\n\tcolors: ['rgba(50, 172, 45, 1)', 'rgba(241, 255, 0, 1)', 'rgba(245, 54, 54, 1)'],\r\n\tlegend: {\r\n\t\tshow: true,\r\n\t\tmin: true,\r\n\t\tmax: true,\r\n\t\tavg: true,\r\n\t\tcurrent: true,\r\n\t\ttotal: true\r\n\t},\r\n\tmaxDataPoints: 100,\r\n\tmappingType: 1,\r\n\tnullPointMode: 'connected',\r\n\tformat: 'none',\r\n valueMaps: [\r\n { value: 'null', op: '=', text: 'N/A' }\r\n ],\r\n treeMap: {\r\n \tmode: 'squarify',\r\n \tgroups: [{key:'server', value: '/^.*\\./g'}],\r\n \tcolorByFunction: 'max',\r\n \tsizeByFunction: 'constant',\r\n \tenableTimeBlocks: false,\r\n \tenableGrouping: true,\r\n \tdebug: false,\r\n \tdepth: 0,\r\n \tids: ['alias'],\r\n \tnodeSizeProperty: \"value\"\r\n }\r\n};\r\n\r\nclass HeatmapCtrl extends MetricsPanelCtrl {\r\n\tconstructor($scope, $injector, $sce) {\r\n\t\tsuper($scope, $injector);\r\n\t\t_.defaults(this.panel, panelDefaults);\r\n\t\t\r\n\t\tthis.options = panelOptions;\r\n\t\tthis.panel.chartId = 'chart_' + this.panel.id;\r\n\t\tthis.containerDivId = 'container_'+this.panel.chartId;\r\n\t\tthis.$sce = $sce;\r\n\t\tthis.events.on('init-edit-mode', this.onInitEditMode.bind(this));\r\n\t\tthis.events.on('data-received', this.onDataReceived.bind(this));\r\n\t\tthis.events.on('data-snapshot-load', this.onDataReceived.bind(this));\r\n\t\tthis.initializePanel();\r\n\t}\r\n\t\r\n\tinitializePanel(){\r\n\t\tvar d3plusPath = 'plugins/'+pluginName+'/libs/d3plus/d3plus.full.js';\r\n\t\tvar _this = this;\r\n\t\tvar meta = {};\r\n\t\tmeta[d3plusPath] = {\r\n\t\t\t format: 'global'\r\n\t };\r\n\t\t\r\n\t\tSystemJS.config({\r\n\t\t\t meta: meta\r\n\t\t\t});\r\n\r\n\t\tSystemJS.import(d3plusPath).then(function d3plusLoaded(){\r\n\t\t\tconsole.log('d3plus is loaded');\r\n\t\t\t_this.events.emit('data-received');\r\n\t\t});\r\n\t}\r\n\t\r\n\thandleError(err){\r\n\t\tthis.getPanelContainer().html('

Error:

' + err + '
');\r\n\t}\r\n\t\r\n\tonInitEditMode() {\r\n\t\tthis.addEditorTab('Heatmap', heatmapEditor, 2);\r\n\t\tthis.addEditorTab('Display', displayEditor, 3);\r\n\t}\r\n\t\r\n\tgetPanelContainer(){\r\n\t\treturn $(document.getElementById(this.containerDivId));\r\n\t}\r\n\t\r\n\tonDataReceived(dataList){\r\n\t\tconsole.info('received data');\r\n\t\tconsole.debug(dataList);\r\n\t\tif(undefined != dataList) {\r\n\t\t\tthis.series = dataList.map(this.seriesHandler.bind(this));\r\n\t\t\tconsole.info('mapped dataList to series');\r\n\t\t}\r\n\r\n\t\tvar preparedData = this.d3plusDataProcessor(this.series);\r\n\t\tthis.render(preparedData);\r\n\t}\r\n\t\r\n\tgetGroupKeys(){\r\n\t\treturn this.panel.treeMap.groups.map(function(group){\r\n\t\t\treturn group.key;\r\n\t\t});\r\n\t}\r\n\t\r\n\t/**\r\n\t * Prepare data for d3plus\r\n\t */\r\n\td3plusDataProcessor(dataArray){\r\n\t\tvar resultArray = [];\r\n\t\tvar hasGroups = (this.panel.treeMap.groups.length > 0)\r\n\t\t\r\n\t\tif(!hasGroups){\r\n\t\t\t// just add the original items since there are no groups\r\n\t\t\tfor (var dataIndex=0; dataIndex < dataArray.length; dataIndex++){\r\n\t\t\t\tvar newDataItem = Object.assign({}, dataArray[dataIndex], dataArray[dataIndex].stats);\r\n\t\t\t\tresultArray.push(newDataItem);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\t// Process Groups\r\n\t\t\tvar groupArray = [];\r\n\t\t\tfor(var groupIndex=0; groupIndex 0){\r\n\t\t\t\t\t\tnewDataItem[key] = matches[0];\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tnewDataItem[key] = 'NA';\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tresultArray.push(newDataItem);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\r\n\t\t// If we're using timeBlocks mode\r\n\t\t// replace the aggregated series with individual records\r\n\t\tif(this.panel.treeMap.enableTimeBlocks){\r\n\t\t\tconsole.info('creating timeblock records')\r\n\t\t\tvar timeBlockArray = [];\r\n\t\t\tfor (var dataIndex=0; dataIndex < resultArray.length; dataIndex++){\r\n\t\t\t\tconsole.debug('dataIndex:'+dataIndex+', alias:'+resultArray[dataIndex].alias);\r\n\t\t\t\tvar dataSeries = resultArray[dataIndex];\r\n\t\t\t\tfor(var dataPointIndex=0; dataPointIndex < dataSeries.flotpairs.length; dataPointIndex++){\r\n\t\t\t\t\tvar dataSeriesCopy = Object.assign({}, dataSeries);\r\n\t\t\t\t\tdelete dataSeriesCopy.datapoints;\r\n\t\t\t\t\tdelete dataSeriesCopy.flotpairs;\r\n\t\t\t\t\tdataSeriesCopy.count = 1;\r\n\t\t\t\t\tdataSeriesCopy.timestamp = dataSeries.flotpairs[dataPointIndex][0];\r\n\t\t\t\t\tdataSeriesCopy.value = dataSeries.flotpairs[dataPointIndex][1];\r\n\t\t\t\t\ttimeBlockArray.push(dataSeriesCopy);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tresultArray = timeBlockArray;\r\n\t\t} \r\n\t\t\r\n\t\treturn resultArray;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Series Handler\r\n\t */\r\n\tseriesHandler(seriesData) {\r\n\t\tvar series = new TimeSeries({\r\n\t\t\tdatapoints: seriesData.datapoints,\r\n\t\t\talias: seriesData.target.replace(/\"|,|;|=|:|{|}/g, '_')\r\n\t\t});\r\n\t series.flotpairs = series.getFlotPairs(this.panel.nullPointMode);\r\n\t return series;\r\n\t} // End seriesHandler()\r\n\t\r\n\taddSeriesOverride(override) {\r\n\t\tthis.panel.seriesOverrides.push(override || {});\r\n\t}\r\n\t\r\n\taddTreeMapGroup(group) {\r\n\t\tthis.panel.treeMap.groups.push(group || {});\r\n\t}\r\n\r\n\tremoveSeriesOverride(override) {\r\n\t\tthis.panel.seriesOverrides = _.without(this.panel.seriesOverrides, override);\r\n\t this.render();\r\n\t}\r\n\t\r\n\tremoveTreeMapGroup(group) {\r\n\t\tthis.panel.treeMap.groups = _.without(this.panel.treeMap.groups, group);\r\n\t this.render();\r\n\t}\r\n\t\r\n\tupdateThresholds(){\r\n\t\tvar thresholdCount = this.panel.thresholds.length;\r\n\t\tvar colorCount = this.panel.colors.length;\r\n\t\tthis.refresh();\r\n\t}\r\n\t\r\n\tchangeColor(colorIndex, color){\r\n\t\tthis.panel.colors[colorIndex] = color;\r\n\t}\r\n\t\r\n\tremoveColor(colorIndex){\r\n\t\tthis.panel.colors.splice(colorIndex,1);\r\n\t}\r\n\t\r\n\taddColor(){\r\n\t\tthis.panel.colors.push('rgba(255, 255, 255, 1)');\r\n\t}\r\n\t\r\n\tgetGradientForValue(data, value){\r\n\t\tvar min = Math.min.apply(Math, data.thresholds);\r\n\t\tvar max = Math.max.apply(Math, data.thresholds);\r\n\t\tvar absoluteDistance = max - min;\r\n\t\tvar valueDistanceFromMin = value - min;\r\n\t\tvar xPercent = valueDistanceFromMin/absoluteDistance;\r\n\t\t// Get the smaller number to clamp at 0.99 max\r\n\t\txPercent = Math.min(0.99, xPercent);\r\n\t\t// Get the larger number to clamp at 0.01 min\r\n\t\txPercent = Math.max(0.01, xPercent);\r\n\t\t\r\n\t\treturn getColorByXPercentage(this.canvas, xPercent);\r\n\t}\r\n\t\r\n\tapplyOverrides(seriesItemAlias){\r\n\t\tvar seriesItem = {}, colorData = {}, overrides = {};\r\n\t\tconsole.info('applying overrides for seriesItem');\r\n\t\tconsole.debug(seriesItemAlias);\r\n\t\tconsole.debug(this.panel.seriesOverrides);\r\n\t\tfor(var i=0; i<=this.panel.seriesOverrides.length; i++){\r\n\t\t\tconsole.debug('comparing:');\r\n\t\t\tconsole.debug(this.panel.seriesOverrides[i]);\r\n\t\t\tif (this.panel.seriesOverrides[i] && this.panel.seriesOverrides[i].alias == seriesItemAlias){\r\n\t\t\t\toverrides = this.panel.seriesOverrides[i];\r\n\t\t\t}\r\n\t\t}\r\n\t\tcolorData.thresholds = (overrides.thresholds || this.panel.thresholds).split(',').map(function(strVale) {\r\n\t\t\treturn Number(strVale.trim());\r\n\t\t});\r\n\t\tcolorData.colorMap = this.panel.colors;\r\n\t\tseriesItem.colorData = colorData;\r\n\t\t\r\n\t\tseriesItem.valueName = overrides.valueName || this.panel.valueName;\r\n\t\t\r\n\t\treturn seriesItem;\r\n\t}\r\n\t\r\n\tinvertColorOrder() {\r\n\t this.panel.colors.reverse();\r\n\t this.refresh();\r\n\t}\r\n\t\r\n\taddTreeMapId(){\r\n\t\tthis.panel.treeMap.ids.push('');\r\n\t\tthis.refresh();\r\n\t}\r\n\t\r\n\tremoveTreeMapId(pos){\r\n\t\tthis.panel.treeMap.ids.splice(pos,1);\r\n\t\tthis.refresh();\r\n\t}\r\n\t\r\n\tchangeTreeMapId(idString, pos){\r\n\t\tthis.panel.treeMap.ids[pos] = idString;\r\n\t}\r\n\t\r\n\t// #############################################\r\n\t// link \r\n\t// #############################################\r\n\r\n\tlink(scope, elem, attrs, ctrl) {\r\n\t\tvar chartElement = elem.find('.heatmap');\r\n\t\tchartElement.append('
');\r\n\t var chartContainer = $(document.getElementById(ctrl.containerDivId));\r\n \tconsole.debug('found chartContainer');\r\n \tconsole.debug(chartContainer);\r\n \telem.css('height', ctrl.height + 'px');\r\n \t\r\n \tvar canvas = elem.find('.canvas')[0];\r\n\t ctrl.canvas = canvas;\r\n\t var gradientValueMax = elem.find('.gradient-value-max')[0];\r\n\t var gradientValueMin = elem.find('.gradient-value-min')[0];\r\n\t \r\n\r\n \tvar visFormat =\r\n\t\t{ \r\n\t\t\t\"text\" : function(text, opts) {\r\n\t\t\t\tif(opts.key == 'timestamp'){\r\n\t\t\t\t\tvar timestamp = moment(Number(text));\r\n\t\t\t\t\treturn timestamp.format(ctrl.panel.treeMap.timestampFormat);\r\n\t\t\t\t} \r\n\t\t\t\telse if(ctrl.getGroupKeys().indexOf(opts.key)>-1) {\r\n\t\t\t\t\treturn text;\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\treturn d3plus.string.title(text, opts);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t};\r\n \t\r\n\r\n \tfunction render(data){\r\n \t\tupdateSize();\r\n \t\tupdateCanvasStyle();\r\n \t\tupdateChart(data);\r\n \t}\r\n \t\r\n \tfunction updateCanvasStyle(){\r\n\t \tcanvas.width = Math.max(chartElement[0].clientWidth, 100);\r\n\t\t\tvar canvasContext = canvas.getContext(\"2d\");\r\n\t\t\tcanvasContext.clearRect(0, 0, canvas.width, canvas.height);\r\n\t\t\t\r\n\t\t\tvar grd = canvasContext.createLinearGradient(0, 0, canvas.width, 0);\r\n\t\t\tvar colorWidth = 1 / Math.max(ctrl.panel.colors.length, 1);\r\n\t\t\tfor(var i=0; i +
Development
+
+ + +
+
+
+
Group Options
+ +
+ + +
+
+ + +
+
+ + +
+
+ + + + +
+ +
+ +
+ + +
+
+ +
+
+
+ +
+
+
+
Grouping Regex match example: /server[0-3]/i
+ +
+
+ +
+
+ +
+ +
+ +
+
+ +
+ +
+ +
+
+
+ + +
+
\ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/img/heatmap.PNG b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/img/heatmap.PNG new file mode 100644 index 0000000..d48eec5 Binary files /dev/null and b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/img/heatmap.PNG differ diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/img/icn-heatmap-panel.svg b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/img/icn-heatmap-panel.svg new file mode 100644 index 0000000..b6e0997 --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/img/icn-heatmap-panel.svg @@ -0,0 +1,241 @@ + + + +image/svg+xml \ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/img/timestamp_data.PNG b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/img/timestamp_data.PNG new file mode 100644 index 0000000..7a222bc Binary files /dev/null and b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/img/timestamp_data.PNG differ diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/libs/d3/d3.js b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/libs/d3/d3.js new file mode 100644 index 0000000..f48f1e7 --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/libs/d3/d3.js @@ -0,0 +1,9554 @@ +!function() { + var d3 = { + version: "3.5.17" + }; + 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.transpose = function(matrix) { + if (!(n = matrix.length)) return []; + for (var i = -1, m = d3.min(matrix, d3_transposeLength), transpose = new Array(m); ++i < m; ) { + for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n; ) { + row[j] = matrix[j][i]; + } + } + return transpose; + }; + function d3_transposeLength(d) { + return d.length; + } + d3.zip = function() { + return d3.transpose(arguments); + }; + 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_nsXhtml = "http://www.w3.org/1999/xhtml"; + var d3_nsPrefix = { + svg: "http://www.w3.org/2000/svg", + xhtml: d3_nsXhtml, + 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)) !== "xmlns") 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 === d3_nsXhtml && document.documentElement.namespaceURI === d3_nsXhtml ? document.createElement(name) : document.createElementNS(namespace, 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 (node = group[i]) { + if (nodeByKeyValue.has(keyValue = key.call(node, 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 (i in keyValues && 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 = d3_array(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.correspondingElement || 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); + 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], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S; + if (d2 < ε2) { + S = Math.log(w1 / w0) / ρ; + i = function(t) { + return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * t * S) ]; + }; + } else { + var 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); + S = (r1 - r0) / ρ; + i = function(t) { + var s = t * S, 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) ]; + }; + } + i.duration = S * 1e3; + return i; + }; + 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: null + }; + scaleTo(+_); + 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, 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); + 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 d3_selection_interrupt.call(this), + translate0 = location(center0 = center || d3.mouse(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]+)\((.*)\)/.exec(format = format.toLowerCase()); + 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)) { + 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_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) { + setTimeout(callback, 17); + }; + d3.timer = function() { + d3_timer.apply(this, arguments); + }; + function d3_timer(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, + 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); + } + return timer; + } + 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(), timer = d3_timer_queueHead; + while (timer) { + if (now >= timer.t && timer.c(now - timer.t)) timer.c = null; + timer = timer.n; + } + return now; + } + function d3_timer_sweep() { + var t0, t1 = d3_timer_queueHead, time = Infinity; + while (t1) { + if (t1.c) { + if (t1.t < time) time = t1.t; + t1 = (t0 = t1).n; + } else { + t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = 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 = +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 || "U" in d) { + if (!("w" in d)) d.w = "W" in d ? 1 : 0; + 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 < -ε) ^ 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.toLowerCase()) || /^(#|rgb\(|hsl\()/i.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_interpolateTransformPop(s) { + return s.length ? s.pop() + "," : ""; + } + function d3_interpolateTranslate(ta, tb, s, q) { + if (ta[0] !== tb[0] || ta[1] !== tb[1]) { + var i = s.push("translate(", null, ",", null, ")"); + q.push({ + i: i - 4, + x: d3_interpolateNumber(ta[0], tb[0]) + }, { + i: i - 2, + x: d3_interpolateNumber(ta[1], tb[1]) + }); + } else if (tb[0] || tb[1]) { + s.push("translate(" + tb + ")"); + } + } + function d3_interpolateRotate(ra, rb, s, q) { + if (ra !== rb) { + if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360; + q.push({ + i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2, + x: d3_interpolateNumber(ra, rb) + }); + } else if (rb) { + s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")"); + } + } + function d3_interpolateSkew(wa, wb, s, q) { + if (wa !== wb) { + q.push({ + i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2, + x: d3_interpolateNumber(wa, wb) + }); + } else if (wb) { + s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")"); + } + } + function d3_interpolateScale(ka, kb, s, q) { + if (ka[0] !== kb[0] || ka[1] !== kb[1]) { + var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")"); + q.push({ + i: i - 4, + x: d3_interpolateNumber(ka[0], kb[0]) + }, { + i: i - 2, + x: d3_interpolateNumber(ka[1], kb[1]) + }); + } else if (kb[0] !== 1 || kb[1] !== 1) { + s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")"); + } + } + function d3_interpolateTransform(a, b) { + var s = [], q = []; + a = d3.transform(a), b = d3.transform(b); + d3_interpolateTranslate(a.translate, b.translate, s, q); + d3_interpolateRotate(a.rotate, b.rotate, s, q); + d3_interpolateSkew(a.skew, b.skew, s, q); + d3_interpolateScale(a.scale, b.scale, s, q); + a = b = null; + return function(t) { + var i = -1, n = q.length, 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: groupSums[di] + }; + 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"), timer, 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) { + timer = null; + 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 / (s.weight + t.weight) : .5); + 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 { + timer.c = null, timer.t = NaN, timer = null; + event.end({ + type: "end", + alpha: alpha = 0 + }); + } + } else if (x > 0) { + event.start({ + type: "start", + alpha: alpha = x + }); + timer = 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), sum = d3.sum(values), k = sum ? (da - n * pa) / sum : 0, 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 = root.y = 0; + if (root.value) root.dx = size[0], root.dy = size[1]; else root.dx = root.dy = 0; + 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) { + d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); + d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); + return domain; + } + 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, base * n / scale.ticks().length); + return function(d) { + var i = d / pow(Math.round(log(d))); + if (i * base < base - .5) i *= base; + return i <= 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 (da > ε && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) { + cr = r0 < r1 ^ cw ? 0 : 1; + var rc1 = rc, rc0 = rc; + if (da < π) { + 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]); + rc0 = Math.min(rc, (r0 - lc) / (kc - 1)); + rc1 = Math.min(rc, (r1 - lc) / (kc + 1)); + } + if (x1 != null) { + var 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 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(Math.max(0, 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.length > 1 ? points.join("L") : points + "Z"; + } + function d3_svg_lineLinearClosed(points) { + return points.join("L") + "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_lineLinearClosed(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, activeId, active; + if ((lock = this[ns]) && (active = lock[activeId = lock.active])) { + active.timer.c = null; + active.timer.t = NaN; + if (--lock.count) delete lock[activeId]; 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], time, timer, duration, ease, tweens; + function schedule(elapsed) { + var delay = transition.delay; + timer.t = delay + time; + if (delay <= elapsed) return start(elapsed - delay); + timer.c = start; + } + function start(elapsed) { + var activeId = lock.active, active = lock[activeId]; + if (active) { + active.timer.c = null; + active.timer.t = NaN; + --lock.count; + delete lock[activeId]; + active.event && active.event.interrupt.call(node, node.__data__, active.index); + } + for (var cancelId in lock) { + if (+cancelId < id) { + var cancel = lock[cancelId]; + cancel.timer.c = null; + cancel.timer.t = NaN; + --lock.count; + delete lock[cancelId]; + } + } + timer.c = tick; + d3_timer(function() { + if (timer.c && tick(elapsed || 1)) { + timer.c = null; + timer.t = NaN; + } + return 1; + }, 0, time); + lock.active = id; + transition.event && transition.event.start.call(node, node.__data__, i); + tweens = []; + transition.tween.forEach(function(key, value) { + if (value = value.call(node, node.__data__, i)) { + tweens.push(value); + } + }); + ease = transition.ease; + duration = transition.duration; + } + function tick(elapsed) { + var t = elapsed / duration, e = ease(t), n = tweens.length; + while (n > 0) { + tweens[--n].call(node, e); + } + if (t >= 1) { + transition.event && transition.event.end.call(node, node.__data__, i); + if (--lock.count) delete lock[id]; else delete node[ns]; + return 1; + } + } + if (!transition) { + time = inherit.time; + timer = d3_timer(schedule, 0, time); + transition = lock[id] = { + tween: new d3_Map(), + time: time, + timer: timer, + delay: inherit.delay, + duration: inherit.duration, + ease: inherit.ease, + index: i + }; + inherit = null; + ++lock.count; + } + } + 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_ = d3_array(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) this.d3 = d3, define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; else this.d3 = d3; +}(); \ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/libs/d3/d3.min.js b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/libs/d3/d3.min.js new file mode 100644 index 0000000..e4670a7 --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/libs/d3/d3.min.js @@ -0,0 +1,5 @@ +!function(){function n(n){return n&&(n.ownerDocument||n.document||n).documentElement}function t(n){return n&&(n.ownerDocument&&n.ownerDocument.defaultView||n.document&&n||n.defaultView)}function e(n,t){return t>n?-1:n>t?1:n>=t?0:NaN}function r(n){return null===n?NaN:+n}function i(n){return!isNaN(n)}function u(n){return{left:function(t,e,r,i){for(arguments.length<3&&(r=0),arguments.length<4&&(i=t.length);i>r;){var u=r+i>>>1;n(t[u],e)<0?r=u+1:i=u}return r},right:function(t,e,r,i){for(arguments.length<3&&(r=0),arguments.length<4&&(i=t.length);i>r;){var u=r+i>>>1;n(t[u],e)>0?i=u:r=u+1}return r}}}function o(n){return n.length}function a(n){for(var t=1;n*t%1;)t*=10;return t}function l(n,t){for(var e in t)Object.defineProperty(n.prototype,e,{value:t[e],enumerable:!1})}function c(){this._=Object.create(null)}function f(n){return(n+="")===bo||n[0]===_o?_o+n:n}function s(n){return(n+="")[0]===_o?n.slice(1):n}function h(n){return f(n)in this._}function p(n){return(n=f(n))in this._&&delete this._[n]}function g(){var n=[];for(var t in this._)n.push(s(t));return n}function v(){var n=0;for(var t in this._)++n;return n}function d(){for(var n in this._)return!1;return!0}function y(){this._=Object.create(null)}function m(n){return n}function M(n,t,e){return function(){var r=e.apply(t,arguments);return r===t?n:r}}function x(n,t){if(t in n)return t;t=t.charAt(0).toUpperCase()+t.slice(1);for(var e=0,r=wo.length;r>e;++e){var i=wo[e]+t;if(i in n)return i}}function b(){}function _(){}function w(n){function t(){for(var t,r=e,i=-1,u=r.length;++ie;e++)for(var i,u=n[e],o=0,a=u.length;a>o;o++)(i=u[o])&&t(i,o,e);return n}function Z(n){return ko(n,qo),n}function V(n){var t,e;return function(r,i,u){var o,a=n[u].update,l=a.length;for(u!=e&&(e=u,t=0),i>=t&&(t=i+1);!(o=a[t])&&++t0&&(n=n.slice(0,a));var c=To.get(n);return c&&(n=c,l=B),a?t?i:r:t?b:u}function $(n,t){return function(e){var r=ao.event;ao.event=e,t[0]=this.__data__;try{n.apply(this,t)}finally{ao.event=r}}}function B(n,t){var e=$(n,t);return function(n){var t=this,r=n.relatedTarget;r&&(r===t||8&r.compareDocumentPosition(t))||e.call(t,n)}}function W(e){var r=".dragsuppress-"+ ++Do,i="click"+r,u=ao.select(t(e)).on("touchmove"+r,S).on("dragstart"+r,S).on("selectstart"+r,S);if(null==Ro&&(Ro="onselectstart"in e?!1:x(e.style,"userSelect")),Ro){var o=n(e).style,a=o[Ro];o[Ro]="none"}return function(n){if(u.on(r,null),Ro&&(o[Ro]=a),n){var t=function(){u.on(i,null)};u.on(i,function(){S(),t()},!0),setTimeout(t,0)}}}function J(n,e){e.changedTouches&&(e=e.changedTouches[0]);var r=n.ownerSVGElement||n;if(r.createSVGPoint){var i=r.createSVGPoint();if(0>Po){var u=t(n);if(u.scrollX||u.scrollY){r=ao.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var o=r[0][0].getScreenCTM();Po=!(o.f||o.e),r.remove()}}return Po?(i.x=e.pageX,i.y=e.pageY):(i.x=e.clientX,i.y=e.clientY),i=i.matrixTransform(n.getScreenCTM().inverse()),[i.x,i.y]}var a=n.getBoundingClientRect();return[e.clientX-a.left-n.clientLeft,e.clientY-a.top-n.clientTop]}function G(){return ao.event.changedTouches[0].identifier}function K(n){return n>0?1:0>n?-1:0}function Q(n,t,e){return(t[0]-n[0])*(e[1]-n[1])-(t[1]-n[1])*(e[0]-n[0])}function nn(n){return n>1?0:-1>n?Fo:Math.acos(n)}function tn(n){return n>1?Io:-1>n?-Io:Math.asin(n)}function en(n){return((n=Math.exp(n))-1/n)/2}function rn(n){return((n=Math.exp(n))+1/n)/2}function un(n){return((n=Math.exp(2*n))-1)/(n+1)}function on(n){return(n=Math.sin(n/2))*n}function an(){}function ln(n,t,e){return this instanceof ln?(this.h=+n,this.s=+t,void(this.l=+e)):arguments.length<2?n instanceof ln?new ln(n.h,n.s,n.l):_n(""+n,wn,ln):new ln(n,t,e)}function cn(n,t,e){function r(n){return n>360?n-=360:0>n&&(n+=360),60>n?u+(o-u)*n/60:180>n?o:240>n?u+(o-u)*(240-n)/60:u}function i(n){return Math.round(255*r(n))}var u,o;return n=isNaN(n)?0:(n%=360)<0?n+360:n,t=isNaN(t)?0:0>t?0:t>1?1:t,e=0>e?0:e>1?1:e,o=.5>=e?e*(1+t):e+t-e*t,u=2*e-o,new mn(i(n+120),i(n),i(n-120))}function fn(n,t,e){return this instanceof fn?(this.h=+n,this.c=+t,void(this.l=+e)):arguments.length<2?n instanceof fn?new fn(n.h,n.c,n.l):n instanceof hn?gn(n.l,n.a,n.b):gn((n=Sn((n=ao.rgb(n)).r,n.g,n.b)).l,n.a,n.b):new fn(n,t,e)}function sn(n,t,e){return isNaN(n)&&(n=0),isNaN(t)&&(t=0),new hn(e,Math.cos(n*=Yo)*t,Math.sin(n)*t)}function hn(n,t,e){return this instanceof hn?(this.l=+n,this.a=+t,void(this.b=+e)):arguments.length<2?n instanceof hn?new hn(n.l,n.a,n.b):n instanceof fn?sn(n.h,n.c,n.l):Sn((n=mn(n)).r,n.g,n.b):new hn(n,t,e)}function pn(n,t,e){var r=(n+16)/116,i=r+t/500,u=r-e/200;return i=vn(i)*na,r=vn(r)*ta,u=vn(u)*ea,new mn(yn(3.2404542*i-1.5371385*r-.4985314*u),yn(-.969266*i+1.8760108*r+.041556*u),yn(.0556434*i-.2040259*r+1.0572252*u))}function gn(n,t,e){return n>0?new fn(Math.atan2(e,t)*Zo,Math.sqrt(t*t+e*e),n):new fn(NaN,NaN,n)}function vn(n){return n>.206893034?n*n*n:(n-4/29)/7.787037}function dn(n){return n>.008856?Math.pow(n,1/3):7.787037*n+4/29}function yn(n){return Math.round(255*(.00304>=n?12.92*n:1.055*Math.pow(n,1/2.4)-.055))}function mn(n,t,e){return this instanceof mn?(this.r=~~n,this.g=~~t,void(this.b=~~e)):arguments.length<2?n instanceof mn?new mn(n.r,n.g,n.b):_n(""+n,mn,cn):new mn(n,t,e)}function Mn(n){return new mn(n>>16,n>>8&255,255&n)}function xn(n){return Mn(n)+""}function bn(n){return 16>n?"0"+Math.max(0,n).toString(16):Math.min(255,n).toString(16)}function _n(n,t,e){var r,i,u,o=0,a=0,l=0;if(r=/([a-z]+)\((.*)\)/.exec(n=n.toLowerCase()))switch(i=r[2].split(","),r[1]){case"hsl":return e(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return t(Nn(i[0]),Nn(i[1]),Nn(i[2]))}return(u=ua.get(n))?t(u.r,u.g,u.b):(null==n||"#"!==n.charAt(0)||isNaN(u=parseInt(n.slice(1),16))||(4===n.length?(o=(3840&u)>>4,o=o>>4|o,a=240&u,a=a>>4|a,l=15&u,l=l<<4|l):7===n.length&&(o=(16711680&u)>>16,a=(65280&u)>>8,l=255&u)),t(o,a,l))}function wn(n,t,e){var r,i,u=Math.min(n/=255,t/=255,e/=255),o=Math.max(n,t,e),a=o-u,l=(o+u)/2;return a?(i=.5>l?a/(o+u):a/(2-o-u),r=n==o?(t-e)/a+(e>t?6:0):t==o?(e-n)/a+2:(n-t)/a+4,r*=60):(r=NaN,i=l>0&&1>l?0:r),new ln(r,i,l)}function Sn(n,t,e){n=kn(n),t=kn(t),e=kn(e);var r=dn((.4124564*n+.3575761*t+.1804375*e)/na),i=dn((.2126729*n+.7151522*t+.072175*e)/ta),u=dn((.0193339*n+.119192*t+.9503041*e)/ea);return hn(116*i-16,500*(r-i),200*(i-u))}function kn(n){return(n/=255)<=.04045?n/12.92:Math.pow((n+.055)/1.055,2.4)}function Nn(n){var t=parseFloat(n);return"%"===n.charAt(n.length-1)?Math.round(2.55*t):t}function En(n){return"function"==typeof n?n:function(){return n}}function An(n){return function(t,e,r){return 2===arguments.length&&"function"==typeof e&&(r=e,e=null),Cn(t,e,n,r)}}function Cn(n,t,e,r){function i(){var n,t=l.status;if(!t&&Ln(l)||t>=200&&300>t||304===t){try{n=e.call(u,l)}catch(r){return void o.error.call(u,r)}o.load.call(u,n)}else o.error.call(u,l)}var u={},o=ao.dispatch("beforesend","progress","load","error"),a={},l=new XMLHttpRequest,c=null;return!this.XDomainRequest||"withCredentials"in l||!/^(http(s)?:)?\/\//.test(n)||(l=new XDomainRequest),"onload"in l?l.onload=l.onerror=i:l.onreadystatechange=function(){l.readyState>3&&i()},l.onprogress=function(n){var t=ao.event;ao.event=n;try{o.progress.call(u,l)}finally{ao.event=t}},u.header=function(n,t){return n=(n+"").toLowerCase(),arguments.length<2?a[n]:(null==t?delete a[n]:a[n]=t+"",u)},u.mimeType=function(n){return arguments.length?(t=null==n?null:n+"",u):t},u.responseType=function(n){return arguments.length?(c=n,u):c},u.response=function(n){return e=n,u},["get","post"].forEach(function(n){u[n]=function(){return u.send.apply(u,[n].concat(co(arguments)))}}),u.send=function(e,r,i){if(2===arguments.length&&"function"==typeof r&&(i=r,r=null),l.open(e,n,!0),null==t||"accept"in a||(a.accept=t+",*/*"),l.setRequestHeader)for(var f in a)l.setRequestHeader(f,a[f]);return null!=t&&l.overrideMimeType&&l.overrideMimeType(t),null!=c&&(l.responseType=c),null!=i&&u.on("error",i).on("load",function(n){i(null,n)}),o.beforesend.call(u,l),l.send(null==r?null:r),u},u.abort=function(){return l.abort(),u},ao.rebind(u,o,"on"),null==r?u:u.get(zn(r))}function zn(n){return 1===n.length?function(t,e){n(null==t?e:null)}:n}function Ln(n){var t=n.responseType;return t&&"text"!==t?n.response:n.responseText}function qn(n,t,e){var r=arguments.length;2>r&&(t=0),3>r&&(e=Date.now());var i=e+t,u={c:n,t:i,n:null};return aa?aa.n=u:oa=u,aa=u,la||(ca=clearTimeout(ca),la=1,fa(Tn)),u}function Tn(){var n=Rn(),t=Dn()-n;t>24?(isFinite(t)&&(clearTimeout(ca),ca=setTimeout(Tn,t)),la=0):(la=1,fa(Tn))}function Rn(){for(var n=Date.now(),t=oa;t;)n>=t.t&&t.c(n-t.t)&&(t.c=null),t=t.n;return n}function Dn(){for(var n,t=oa,e=1/0;t;)t.c?(t.t8?function(n){return n/e}:function(n){return n*e},symbol:n}}function jn(n){var t=n.decimal,e=n.thousands,r=n.grouping,i=n.currency,u=r&&e?function(n,t){for(var i=n.length,u=[],o=0,a=r[0],l=0;i>0&&a>0&&(l+a+1>t&&(a=Math.max(1,t-l)),u.push(n.substring(i-=a,i+a)),!((l+=a+1)>t));)a=r[o=(o+1)%r.length];return u.reverse().join(e)}:m;return function(n){var e=ha.exec(n),r=e[1]||" ",o=e[2]||">",a=e[3]||"-",l=e[4]||"",c=e[5],f=+e[6],s=e[7],h=e[8],p=e[9],g=1,v="",d="",y=!1,m=!0;switch(h&&(h=+h.substring(1)),(c||"0"===r&&"="===o)&&(c=r="0",o="="),p){case"n":s=!0,p="g";break;case"%":g=100,d="%",p="f";break;case"p":g=100,d="%",p="r";break;case"b":case"o":case"x":case"X":"#"===l&&(v="0"+p.toLowerCase());case"c":m=!1;case"d":y=!0,h=0;break;case"s":g=-1,p="r"}"$"===l&&(v=i[0],d=i[1]),"r"!=p||h||(p="g"),null!=h&&("g"==p?h=Math.max(1,Math.min(21,h)):"e"!=p&&"f"!=p||(h=Math.max(0,Math.min(20,h)))),p=pa.get(p)||Fn;var M=c&&s;return function(n){var e=d;if(y&&n%1)return"";var i=0>n||0===n&&0>1/n?(n=-n,"-"):"-"===a?"":a;if(0>g){var l=ao.formatPrefix(n,h);n=l.scale(n),e=l.symbol+d}else n*=g;n=p(n,h);var x,b,_=n.lastIndexOf(".");if(0>_){var w=m?n.lastIndexOf("e"):-1;0>w?(x=n,b=""):(x=n.substring(0,w),b=n.substring(w))}else x=n.substring(0,_),b=t+n.substring(_+1);!c&&s&&(x=u(x,1/0));var S=v.length+x.length+b.length+(M?0:i.length),k=f>S?new Array(S=f-S+1).join(r):"";return M&&(x=u(k+x,k.length?f-b.length:1/0)),i+=v,n=x+b,("<"===o?i+n+k:">"===o?k+i+n:"^"===o?k.substring(0,S>>=1)+i+n+k.substring(S):i+(M?n:k+n))+e}}}function Fn(n){return n+""}function Hn(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function On(n,t,e){function r(t){var e=n(t),r=u(e,1);return r-t>t-e?e:r}function i(e){return t(e=n(new va(e-1)),1),e}function u(n,e){return t(n=new va(+n),e),n}function o(n,r,u){var o=i(n),a=[];if(u>1)for(;r>o;)e(o)%u||a.push(new Date(+o)),t(o,1);else for(;r>o;)a.push(new Date(+o)),t(o,1);return a}function a(n,t,e){try{va=Hn;var r=new Hn;return r._=n,o(r,t,e)}finally{va=Date}}n.floor=n,n.round=r,n.ceil=i,n.offset=u,n.range=o;var l=n.utc=In(n);return l.floor=l,l.round=In(r),l.ceil=In(i),l.offset=In(u),l.range=a,n}function In(n){return function(t,e){try{va=Hn;var r=new Hn;return r._=t,n(r,e)._}finally{va=Date}}}function Yn(n){function t(n){function t(t){for(var e,i,u,o=[],a=-1,l=0;++aa;){if(r>=c)return-1;if(i=t.charCodeAt(a++),37===i){if(o=t.charAt(a++),u=C[o in ya?t.charAt(a++):o],!u||(r=u(n,e,r))<0)return-1}else if(i!=e.charCodeAt(r++))return-1}return r}function r(n,t,e){_.lastIndex=0;var r=_.exec(t.slice(e));return r?(n.w=w.get(r[0].toLowerCase()),e+r[0].length):-1}function i(n,t,e){x.lastIndex=0;var r=x.exec(t.slice(e));return r?(n.w=b.get(r[0].toLowerCase()),e+r[0].length):-1}function u(n,t,e){N.lastIndex=0;var r=N.exec(t.slice(e));return r?(n.m=E.get(r[0].toLowerCase()),e+r[0].length):-1}function o(n,t,e){S.lastIndex=0;var r=S.exec(t.slice(e));return r?(n.m=k.get(r[0].toLowerCase()),e+r[0].length):-1}function a(n,t,r){return e(n,A.c.toString(),t,r)}function l(n,t,r){return e(n,A.x.toString(),t,r)}function c(n,t,r){return e(n,A.X.toString(),t,r)}function f(n,t,e){var r=M.get(t.slice(e,e+=2).toLowerCase());return null==r?-1:(n.p=r,e)}var s=n.dateTime,h=n.date,p=n.time,g=n.periods,v=n.days,d=n.shortDays,y=n.months,m=n.shortMonths;t.utc=function(n){function e(n){try{va=Hn;var t=new va;return t._=n,r(t)}finally{va=Date}}var r=t(n);return e.parse=function(n){try{va=Hn;var t=r.parse(n);return t&&t._}finally{va=Date}},e.toString=r.toString,e},t.multi=t.utc.multi=ct;var M=ao.map(),x=Vn(v),b=Xn(v),_=Vn(d),w=Xn(d),S=Vn(y),k=Xn(y),N=Vn(m),E=Xn(m);g.forEach(function(n,t){M.set(n.toLowerCase(),t)});var A={a:function(n){return d[n.getDay()]},A:function(n){return v[n.getDay()]},b:function(n){return m[n.getMonth()]},B:function(n){return y[n.getMonth()]},c:t(s),d:function(n,t){return Zn(n.getDate(),t,2)},e:function(n,t){return Zn(n.getDate(),t,2)},H:function(n,t){return Zn(n.getHours(),t,2)},I:function(n,t){return Zn(n.getHours()%12||12,t,2)},j:function(n,t){return Zn(1+ga.dayOfYear(n),t,3)},L:function(n,t){return Zn(n.getMilliseconds(),t,3)},m:function(n,t){return Zn(n.getMonth()+1,t,2)},M:function(n,t){return Zn(n.getMinutes(),t,2)},p:function(n){return g[+(n.getHours()>=12)]},S:function(n,t){return Zn(n.getSeconds(),t,2)},U:function(n,t){return Zn(ga.sundayOfYear(n),t,2)},w:function(n){return n.getDay()},W:function(n,t){return Zn(ga.mondayOfYear(n),t,2)},x:t(h),X:t(p),y:function(n,t){return Zn(n.getFullYear()%100,t,2)},Y:function(n,t){return Zn(n.getFullYear()%1e4,t,4)},Z:at,"%":function(){return"%"}},C={a:r,A:i,b:u,B:o,c:a,d:tt,e:tt,H:rt,I:rt,j:et,L:ot,m:nt,M:it,p:f,S:ut,U:Bn,w:$n,W:Wn,x:l,X:c,y:Gn,Y:Jn,Z:Kn,"%":lt};return t}function Zn(n,t,e){var r=0>n?"-":"",i=(r?-n:n)+"",u=i.length;return r+(e>u?new Array(e-u+1).join(t)+i:i)}function Vn(n){return new RegExp("^(?:"+n.map(ao.requote).join("|")+")","i")}function Xn(n){for(var t=new c,e=-1,r=n.length;++e68?1900:2e3)}function nt(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+2));return r?(n.m=r[0]-1,e+r[0].length):-1}function tt(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+2));return r?(n.d=+r[0],e+r[0].length):-1}function et(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+3));return r?(n.j=+r[0],e+r[0].length):-1}function rt(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+2));return r?(n.H=+r[0],e+r[0].length):-1}function it(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+2));return r?(n.M=+r[0],e+r[0].length):-1}function ut(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+2));return r?(n.S=+r[0],e+r[0].length):-1}function ot(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+3));return r?(n.L=+r[0],e+r[0].length):-1}function at(n){var t=n.getTimezoneOffset(),e=t>0?"-":"+",r=xo(t)/60|0,i=xo(t)%60;return e+Zn(r,"0",2)+Zn(i,"0",2)}function lt(n,t,e){Ma.lastIndex=0;var r=Ma.exec(t.slice(e,e+1));return r?e+r[0].length:-1}function ct(n){for(var t=n.length,e=-1;++e=0?1:-1,a=o*e,l=Math.cos(t),c=Math.sin(t),f=u*c,s=i*l+f*Math.cos(a),h=f*o*Math.sin(a);ka.add(Math.atan2(h,s)),r=n,i=l,u=c}var t,e,r,i,u;Na.point=function(o,a){Na.point=n,r=(t=o)*Yo,i=Math.cos(a=(e=a)*Yo/2+Fo/4),u=Math.sin(a)},Na.lineEnd=function(){n(t,e)}}function dt(n){var t=n[0],e=n[1],r=Math.cos(e);return[r*Math.cos(t),r*Math.sin(t),Math.sin(e)]}function yt(n,t){return n[0]*t[0]+n[1]*t[1]+n[2]*t[2]}function mt(n,t){return[n[1]*t[2]-n[2]*t[1],n[2]*t[0]-n[0]*t[2],n[0]*t[1]-n[1]*t[0]]}function Mt(n,t){n[0]+=t[0],n[1]+=t[1],n[2]+=t[2]}function xt(n,t){return[n[0]*t,n[1]*t,n[2]*t]}function bt(n){var t=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);n[0]/=t,n[1]/=t,n[2]/=t}function _t(n){return[Math.atan2(n[1],n[0]),tn(n[2])]}function wt(n,t){return xo(n[0]-t[0])a;++a)i.point((e=n[a])[0],e[1]);return void i.lineEnd()}var l=new Tt(e,n,null,!0),c=new Tt(e,null,l,!1);l.o=c,u.push(l),o.push(c),l=new Tt(r,n,null,!1),c=new Tt(r,null,l,!0),l.o=c,u.push(l),o.push(c)}}),o.sort(t),qt(u),qt(o),u.length){for(var a=0,l=e,c=o.length;c>a;++a)o[a].e=l=!l;for(var f,s,h=u[0];;){for(var p=h,g=!0;p.v;)if((p=p.n)===h)return;f=p.z,i.lineStart();do{if(p.v=p.o.v=!0,p.e){if(g)for(var a=0,c=f.length;c>a;++a)i.point((s=f[a])[0],s[1]);else r(p.x,p.n.x,1,i);p=p.n}else{if(g){f=p.p.z;for(var a=f.length-1;a>=0;--a)i.point((s=f[a])[0],s[1])}else r(p.x,p.p.x,-1,i);p=p.p}p=p.o,f=p.z,g=!g}while(!p.v);i.lineEnd()}}}function qt(n){if(t=n.length){for(var t,e,r=0,i=n[0];++r0){for(b||(u.polygonStart(),b=!0),u.lineStart();++o1&&2&t&&e.push(e.pop().concat(e.shift())),p.push(e.filter(Dt))}var p,g,v,d=t(u),y=i.invert(r[0],r[1]),m={point:o,lineStart:l,lineEnd:c,polygonStart:function(){m.point=f,m.lineStart=s,m.lineEnd=h,p=[],g=[]},polygonEnd:function(){m.point=o,m.lineStart=l,m.lineEnd=c,p=ao.merge(p);var n=Ot(y,g);p.length?(b||(u.polygonStart(),b=!0),Lt(p,Ut,n,e,u)):n&&(b||(u.polygonStart(),b=!0),u.lineStart(),e(null,null,1,u),u.lineEnd()),b&&(u.polygonEnd(),b=!1),p=g=null},sphere:function(){u.polygonStart(),u.lineStart(),e(null,null,1,u),u.lineEnd(),u.polygonEnd()}},M=Pt(),x=t(M),b=!1;return m}}function Dt(n){return n.length>1}function Pt(){var n,t=[];return{lineStart:function(){t.push(n=[])},point:function(t,e){n.push([t,e])},lineEnd:b,buffer:function(){var e=t;return t=[],n=null,e},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function Ut(n,t){return((n=n.x)[0]<0?n[1]-Io-Uo:Io-n[1])-((t=t.x)[0]<0?t[1]-Io-Uo:Io-t[1])}function jt(n){var t,e=NaN,r=NaN,i=NaN;return{lineStart:function(){n.lineStart(),t=1},point:function(u,o){var a=u>0?Fo:-Fo,l=xo(u-e);xo(l-Fo)0?Io:-Io),n.point(i,r),n.lineEnd(),n.lineStart(),n.point(a,r),n.point(u,r),t=0):i!==a&&l>=Fo&&(xo(e-i)Uo?Math.atan((Math.sin(t)*(u=Math.cos(r))*Math.sin(e)-Math.sin(r)*(i=Math.cos(t))*Math.sin(n))/(i*u*o)):(t+r)/2}function Ht(n,t,e,r){var i;if(null==n)i=e*Io,r.point(-Fo,i),r.point(0,i),r.point(Fo,i),r.point(Fo,0),r.point(Fo,-i),r.point(0,-i),r.point(-Fo,-i),r.point(-Fo,0),r.point(-Fo,i);else if(xo(n[0]-t[0])>Uo){var u=n[0]a;++a){var c=t[a],f=c.length;if(f)for(var s=c[0],h=s[0],p=s[1]/2+Fo/4,g=Math.sin(p),v=Math.cos(p),d=1;;){d===f&&(d=0),n=c[d];var y=n[0],m=n[1]/2+Fo/4,M=Math.sin(m),x=Math.cos(m),b=y-h,_=b>=0?1:-1,w=_*b,S=w>Fo,k=g*M;if(ka.add(Math.atan2(k*_*Math.sin(w),v*x+k*Math.cos(w))),u+=S?b+_*Ho:b,S^h>=e^y>=e){var N=mt(dt(s),dt(n));bt(N);var E=mt(i,N);bt(E);var A=(S^b>=0?-1:1)*tn(E[2]);(r>A||r===A&&(N[0]||N[1]))&&(o+=S^b>=0?1:-1)}if(!d++)break;h=y,g=M,v=x,s=n}}return(-Uo>u||Uo>u&&-Uo>ka)^1&o}function It(n){function t(n,t){return Math.cos(n)*Math.cos(t)>u}function e(n){var e,u,l,c,f;return{lineStart:function(){c=l=!1,f=1},point:function(s,h){var p,g=[s,h],v=t(s,h),d=o?v?0:i(s,h):v?i(s+(0>s?Fo:-Fo),h):0;if(!e&&(c=l=v)&&n.lineStart(),v!==l&&(p=r(e,g),(wt(e,p)||wt(g,p))&&(g[0]+=Uo,g[1]+=Uo,v=t(g[0],g[1]))),v!==l)f=0,v?(n.lineStart(),p=r(g,e),n.point(p[0],p[1])):(p=r(e,g),n.point(p[0],p[1]),n.lineEnd()),e=p;else if(a&&e&&o^v){var y;d&u||!(y=r(g,e,!0))||(f=0,o?(n.lineStart(),n.point(y[0][0],y[0][1]),n.point(y[1][0],y[1][1]),n.lineEnd()):(n.point(y[1][0],y[1][1]),n.lineEnd(),n.lineStart(),n.point(y[0][0],y[0][1])))}!v||e&&wt(e,g)||n.point(g[0],g[1]),e=g,l=v,u=d},lineEnd:function(){l&&n.lineEnd(),e=null},clean:function(){return f|(c&&l)<<1}}}function r(n,t,e){var r=dt(n),i=dt(t),o=[1,0,0],a=mt(r,i),l=yt(a,a),c=a[0],f=l-c*c;if(!f)return!e&&n;var s=u*l/f,h=-u*c/f,p=mt(o,a),g=xt(o,s),v=xt(a,h);Mt(g,v);var d=p,y=yt(g,d),m=yt(d,d),M=y*y-m*(yt(g,g)-1);if(!(0>M)){var x=Math.sqrt(M),b=xt(d,(-y-x)/m);if(Mt(b,g),b=_t(b),!e)return b;var _,w=n[0],S=t[0],k=n[1],N=t[1];w>S&&(_=w,w=S,S=_);var E=S-w,A=xo(E-Fo)E;if(!A&&k>N&&(_=k,k=N,N=_),C?A?k+N>0^b[1]<(xo(b[0]-w)Fo^(w<=b[0]&&b[0]<=S)){var z=xt(d,(-y+x)/m);return Mt(z,g),[b,_t(z)]}}}function i(t,e){var r=o?n:Fo-n,i=0;return-r>t?i|=1:t>r&&(i|=2),-r>e?i|=4:e>r&&(i|=8),i}var u=Math.cos(n),o=u>0,a=xo(u)>Uo,l=ve(n,6*Yo);return Rt(t,e,l,o?[0,-n]:[-Fo,n-Fo])}function Yt(n,t,e,r){return function(i){var u,o=i.a,a=i.b,l=o.x,c=o.y,f=a.x,s=a.y,h=0,p=1,g=f-l,v=s-c;if(u=n-l,g||!(u>0)){if(u/=g,0>g){if(h>u)return;p>u&&(p=u)}else if(g>0){if(u>p)return;u>h&&(h=u)}if(u=e-l,g||!(0>u)){if(u/=g,0>g){if(u>p)return;u>h&&(h=u)}else if(g>0){if(h>u)return;p>u&&(p=u)}if(u=t-c,v||!(u>0)){if(u/=v,0>v){if(h>u)return;p>u&&(p=u)}else if(v>0){if(u>p)return;u>h&&(h=u)}if(u=r-c,v||!(0>u)){if(u/=v,0>v){if(u>p)return;u>h&&(h=u)}else if(v>0){if(h>u)return;p>u&&(p=u)}return h>0&&(i.a={x:l+h*g,y:c+h*v}),1>p&&(i.b={x:l+p*g,y:c+p*v}),i}}}}}}function Zt(n,t,e,r){function i(r,i){return xo(r[0]-n)0?0:3:xo(r[0]-e)0?2:1:xo(r[1]-t)0?1:0:i>0?3:2}function u(n,t){return o(n.x,t.x)}function o(n,t){var e=i(n,1),r=i(t,1);return e!==r?e-r:0===e?t[1]-n[1]:1===e?n[0]-t[0]:2===e?n[1]-t[1]:t[0]-n[0]}return function(a){function l(n){for(var t=0,e=d.length,r=n[1],i=0;e>i;++i)for(var u,o=1,a=d[i],l=a.length,c=a[0];l>o;++o)u=a[o],c[1]<=r?u[1]>r&&Q(c,u,n)>0&&++t:u[1]<=r&&Q(c,u,n)<0&&--t,c=u;return 0!==t}function c(u,a,l,c){var f=0,s=0;if(null==u||(f=i(u,l))!==(s=i(a,l))||o(u,a)<0^l>0){do c.point(0===f||3===f?n:e,f>1?r:t);while((f=(f+l+4)%4)!==s)}else c.point(a[0],a[1])}function f(i,u){return i>=n&&e>=i&&u>=t&&r>=u}function s(n,t){f(n,t)&&a.point(n,t)}function h(){C.point=g,d&&d.push(y=[]),S=!0,w=!1,b=_=NaN}function p(){v&&(g(m,M),x&&w&&E.rejoin(),v.push(E.buffer())),C.point=s,w&&a.lineEnd()}function g(n,t){n=Math.max(-Ha,Math.min(Ha,n)),t=Math.max(-Ha,Math.min(Ha,t));var e=f(n,t);if(d&&y.push([n,t]),S)m=n,M=t,x=e,S=!1,e&&(a.lineStart(),a.point(n,t));else if(e&&w)a.point(n,t);else{var r={a:{x:b,y:_},b:{x:n,y:t}};A(r)?(w||(a.lineStart(),a.point(r.a.x,r.a.y)),a.point(r.b.x,r.b.y),e||a.lineEnd(),k=!1):e&&(a.lineStart(),a.point(n,t),k=!1)}b=n,_=t,w=e}var v,d,y,m,M,x,b,_,w,S,k,N=a,E=Pt(),A=Yt(n,t,e,r),C={point:s,lineStart:h,lineEnd:p,polygonStart:function(){a=E,v=[],d=[],k=!0},polygonEnd:function(){a=N,v=ao.merge(v);var t=l([n,r]),e=k&&t,i=v.length;(e||i)&&(a.polygonStart(),e&&(a.lineStart(),c(null,null,1,a),a.lineEnd()),i&&Lt(v,u,t,c,a),a.polygonEnd()),v=d=y=null}};return C}}function Vt(n){var t=0,e=Fo/3,r=ae(n),i=r(t,e);return i.parallels=function(n){return arguments.length?r(t=n[0]*Fo/180,e=n[1]*Fo/180):[t/Fo*180,e/Fo*180]},i}function Xt(n,t){function e(n,t){var e=Math.sqrt(u-2*i*Math.sin(t))/i;return[e*Math.sin(n*=i),o-e*Math.cos(n)]}var r=Math.sin(n),i=(r+Math.sin(t))/2,u=1+r*(2*i-r),o=Math.sqrt(u)/i;return e.invert=function(n,t){var e=o-t;return[Math.atan2(n,e)/i,tn((u-(n*n+e*e)*i*i)/(2*i))]},e}function $t(){function n(n,t){Ia+=i*n-r*t,r=n,i=t}var t,e,r,i;$a.point=function(u,o){$a.point=n,t=r=u,e=i=o},$a.lineEnd=function(){n(t,e)}}function Bt(n,t){Ya>n&&(Ya=n),n>Va&&(Va=n),Za>t&&(Za=t),t>Xa&&(Xa=t)}function Wt(){function n(n,t){o.push("M",n,",",t,u)}function t(n,t){o.push("M",n,",",t),a.point=e}function e(n,t){o.push("L",n,",",t)}function r(){a.point=n}function i(){o.push("Z")}var u=Jt(4.5),o=[],a={point:n,lineStart:function(){a.point=t},lineEnd:r,polygonStart:function(){a.lineEnd=i},polygonEnd:function(){a.lineEnd=r,a.point=n},pointRadius:function(n){return u=Jt(n),a},result:function(){if(o.length){var n=o.join("");return o=[],n}}};return a}function Jt(n){return"m0,"+n+"a"+n+","+n+" 0 1,1 0,"+-2*n+"a"+n+","+n+" 0 1,1 0,"+2*n+"z"}function Gt(n,t){Ca+=n,za+=t,++La}function Kt(){function n(n,r){var i=n-t,u=r-e,o=Math.sqrt(i*i+u*u);qa+=o*(t+n)/2,Ta+=o*(e+r)/2,Ra+=o,Gt(t=n,e=r)}var t,e;Wa.point=function(r,i){Wa.point=n,Gt(t=r,e=i)}}function Qt(){Wa.point=Gt}function ne(){function n(n,t){var e=n-r,u=t-i,o=Math.sqrt(e*e+u*u);qa+=o*(r+n)/2,Ta+=o*(i+t)/2,Ra+=o,o=i*n-r*t,Da+=o*(r+n),Pa+=o*(i+t),Ua+=3*o,Gt(r=n,i=t)}var t,e,r,i;Wa.point=function(u,o){Wa.point=n,Gt(t=r=u,e=i=o)},Wa.lineEnd=function(){n(t,e)}}function te(n){function t(t,e){n.moveTo(t+o,e),n.arc(t,e,o,0,Ho)}function e(t,e){n.moveTo(t,e),a.point=r}function r(t,e){n.lineTo(t,e)}function i(){a.point=t}function u(){n.closePath()}var o=4.5,a={point:t,lineStart:function(){a.point=e},lineEnd:i,polygonStart:function(){a.lineEnd=u},polygonEnd:function(){a.lineEnd=i,a.point=t},pointRadius:function(n){return o=n,a},result:b};return a}function ee(n){function t(n){return(a?r:e)(n)}function e(t){return ue(t,function(e,r){e=n(e,r),t.point(e[0],e[1])})}function r(t){function e(e,r){e=n(e,r),t.point(e[0],e[1])}function r(){M=NaN,S.point=u,t.lineStart()}function u(e,r){var u=dt([e,r]),o=n(e,r);i(M,x,m,b,_,w,M=o[0],x=o[1],m=e,b=u[0],_=u[1],w=u[2],a,t),t.point(M,x)}function o(){S.point=e,t.lineEnd()}function l(){ +r(),S.point=c,S.lineEnd=f}function c(n,t){u(s=n,h=t),p=M,g=x,v=b,d=_,y=w,S.point=u}function f(){i(M,x,m,b,_,w,p,g,s,v,d,y,a,t),S.lineEnd=o,o()}var s,h,p,g,v,d,y,m,M,x,b,_,w,S={point:e,lineStart:r,lineEnd:o,polygonStart:function(){t.polygonStart(),S.lineStart=l},polygonEnd:function(){t.polygonEnd(),S.lineStart=r}};return S}function i(t,e,r,a,l,c,f,s,h,p,g,v,d,y){var m=f-t,M=s-e,x=m*m+M*M;if(x>4*u&&d--){var b=a+p,_=l+g,w=c+v,S=Math.sqrt(b*b+_*_+w*w),k=Math.asin(w/=S),N=xo(xo(w)-1)u||xo((m*z+M*L)/x-.5)>.3||o>a*p+l*g+c*v)&&(i(t,e,r,a,l,c,A,C,N,b/=S,_/=S,w,d,y),y.point(A,C),i(A,C,N,b,_,w,f,s,h,p,g,v,d,y))}}var u=.5,o=Math.cos(30*Yo),a=16;return t.precision=function(n){return arguments.length?(a=(u=n*n)>0&&16,t):Math.sqrt(u)},t}function re(n){var t=ee(function(t,e){return n([t*Zo,e*Zo])});return function(n){return le(t(n))}}function ie(n){this.stream=n}function ue(n,t){return{point:t,sphere:function(){n.sphere()},lineStart:function(){n.lineStart()},lineEnd:function(){n.lineEnd()},polygonStart:function(){n.polygonStart()},polygonEnd:function(){n.polygonEnd()}}}function oe(n){return ae(function(){return n})()}function ae(n){function t(n){return n=a(n[0]*Yo,n[1]*Yo),[n[0]*h+l,c-n[1]*h]}function e(n){return n=a.invert((n[0]-l)/h,(c-n[1])/h),n&&[n[0]*Zo,n[1]*Zo]}function r(){a=Ct(o=se(y,M,x),u);var n=u(v,d);return l=p-n[0]*h,c=g+n[1]*h,i()}function i(){return f&&(f.valid=!1,f=null),t}var u,o,a,l,c,f,s=ee(function(n,t){return n=u(n,t),[n[0]*h+l,c-n[1]*h]}),h=150,p=480,g=250,v=0,d=0,y=0,M=0,x=0,b=Fa,_=m,w=null,S=null;return t.stream=function(n){return f&&(f.valid=!1),f=le(b(o,s(_(n)))),f.valid=!0,f},t.clipAngle=function(n){return arguments.length?(b=null==n?(w=n,Fa):It((w=+n)*Yo),i()):w},t.clipExtent=function(n){return arguments.length?(S=n,_=n?Zt(n[0][0],n[0][1],n[1][0],n[1][1]):m,i()):S},t.scale=function(n){return arguments.length?(h=+n,r()):h},t.translate=function(n){return arguments.length?(p=+n[0],g=+n[1],r()):[p,g]},t.center=function(n){return arguments.length?(v=n[0]%360*Yo,d=n[1]%360*Yo,r()):[v*Zo,d*Zo]},t.rotate=function(n){return arguments.length?(y=n[0]%360*Yo,M=n[1]%360*Yo,x=n.length>2?n[2]%360*Yo:0,r()):[y*Zo,M*Zo,x*Zo]},ao.rebind(t,s,"precision"),function(){return u=n.apply(this,arguments),t.invert=u.invert&&e,r()}}function le(n){return ue(n,function(t,e){n.point(t*Yo,e*Yo)})}function ce(n,t){return[n,t]}function fe(n,t){return[n>Fo?n-Ho:-Fo>n?n+Ho:n,t]}function se(n,t,e){return n?t||e?Ct(pe(n),ge(t,e)):pe(n):t||e?ge(t,e):fe}function he(n){return function(t,e){return t+=n,[t>Fo?t-Ho:-Fo>t?t+Ho:t,e]}}function pe(n){var t=he(n);return t.invert=he(-n),t}function ge(n,t){function e(n,t){var e=Math.cos(t),a=Math.cos(n)*e,l=Math.sin(n)*e,c=Math.sin(t),f=c*r+a*i;return[Math.atan2(l*u-f*o,a*r-c*i),tn(f*u+l*o)]}var r=Math.cos(n),i=Math.sin(n),u=Math.cos(t),o=Math.sin(t);return e.invert=function(n,t){var e=Math.cos(t),a=Math.cos(n)*e,l=Math.sin(n)*e,c=Math.sin(t),f=c*u-l*o;return[Math.atan2(l*u+c*o,a*r+f*i),tn(f*r-a*i)]},e}function ve(n,t){var e=Math.cos(n),r=Math.sin(n);return function(i,u,o,a){var l=o*t;null!=i?(i=de(e,i),u=de(e,u),(o>0?u>i:i>u)&&(i+=o*Ho)):(i=n+o*Ho,u=n-.5*l);for(var c,f=i;o>0?f>u:u>f;f-=l)a.point((c=_t([e,-r*Math.cos(f),-r*Math.sin(f)]))[0],c[1])}}function de(n,t){var e=dt(t);e[0]-=n,bt(e);var r=nn(-e[1]);return((-e[2]<0?-r:r)+2*Math.PI-Uo)%(2*Math.PI)}function ye(n,t,e){var r=ao.range(n,t-Uo,e).concat(t);return function(n){return r.map(function(t){return[n,t]})}}function me(n,t,e){var r=ao.range(n,t-Uo,e).concat(t);return function(n){return r.map(function(t){return[t,n]})}}function Me(n){return n.source}function xe(n){return n.target}function be(n,t,e,r){var i=Math.cos(t),u=Math.sin(t),o=Math.cos(r),a=Math.sin(r),l=i*Math.cos(n),c=i*Math.sin(n),f=o*Math.cos(e),s=o*Math.sin(e),h=2*Math.asin(Math.sqrt(on(r-t)+i*o*on(e-n))),p=1/Math.sin(h),g=h?function(n){var t=Math.sin(n*=h)*p,e=Math.sin(h-n)*p,r=e*l+t*f,i=e*c+t*s,o=e*u+t*a;return[Math.atan2(i,r)*Zo,Math.atan2(o,Math.sqrt(r*r+i*i))*Zo]}:function(){return[n*Zo,t*Zo]};return g.distance=h,g}function _e(){function n(n,i){var u=Math.sin(i*=Yo),o=Math.cos(i),a=xo((n*=Yo)-t),l=Math.cos(a);Ja+=Math.atan2(Math.sqrt((a=o*Math.sin(a))*a+(a=r*u-e*o*l)*a),e*u+r*o*l),t=n,e=u,r=o}var t,e,r;Ga.point=function(i,u){t=i*Yo,e=Math.sin(u*=Yo),r=Math.cos(u),Ga.point=n},Ga.lineEnd=function(){Ga.point=Ga.lineEnd=b}}function we(n,t){function e(t,e){var r=Math.cos(t),i=Math.cos(e),u=n(r*i);return[u*i*Math.sin(t),u*Math.sin(e)]}return e.invert=function(n,e){var r=Math.sqrt(n*n+e*e),i=t(r),u=Math.sin(i),o=Math.cos(i);return[Math.atan2(n*u,r*o),Math.asin(r&&e*u/r)]},e}function Se(n,t){function e(n,t){o>0?-Io+Uo>t&&(t=-Io+Uo):t>Io-Uo&&(t=Io-Uo);var e=o/Math.pow(i(t),u);return[e*Math.sin(u*n),o-e*Math.cos(u*n)]}var r=Math.cos(n),i=function(n){return Math.tan(Fo/4+n/2)},u=n===t?Math.sin(n):Math.log(r/Math.cos(t))/Math.log(i(t)/i(n)),o=r*Math.pow(i(n),u)/u;return u?(e.invert=function(n,t){var e=o-t,r=K(u)*Math.sqrt(n*n+e*e);return[Math.atan2(n,e)/u,2*Math.atan(Math.pow(o/r,1/u))-Io]},e):Ne}function ke(n,t){function e(n,t){var e=u-t;return[e*Math.sin(i*n),u-e*Math.cos(i*n)]}var r=Math.cos(n),i=n===t?Math.sin(n):(r-Math.cos(t))/(t-n),u=r/i+n;return xo(i)i;i++){for(;r>1&&Q(n[e[r-2]],n[e[r-1]],n[i])<=0;)--r;e[r++]=i}return e.slice(0,r)}function qe(n,t){return n[0]-t[0]||n[1]-t[1]}function Te(n,t,e){return(e[0]-t[0])*(n[1]-t[1])<(e[1]-t[1])*(n[0]-t[0])}function Re(n,t,e,r){var i=n[0],u=e[0],o=t[0]-i,a=r[0]-u,l=n[1],c=e[1],f=t[1]-l,s=r[1]-c,h=(a*(l-c)-s*(i-u))/(s*o-a*f);return[i+h*o,l+h*f]}function De(n){var t=n[0],e=n[n.length-1];return!(t[0]-e[0]||t[1]-e[1])}function Pe(){rr(this),this.edge=this.site=this.circle=null}function Ue(n){var t=cl.pop()||new Pe;return t.site=n,t}function je(n){Be(n),ol.remove(n),cl.push(n),rr(n)}function Fe(n){var t=n.circle,e=t.x,r=t.cy,i={x:e,y:r},u=n.P,o=n.N,a=[n];je(n);for(var l=u;l.circle&&xo(e-l.circle.x)f;++f)c=a[f],l=a[f-1],nr(c.edge,l.site,c.site,i);l=a[0],c=a[s-1],c.edge=Ke(l.site,c.site,null,i),$e(l),$e(c)}function He(n){for(var t,e,r,i,u=n.x,o=n.y,a=ol._;a;)if(r=Oe(a,o)-u,r>Uo)a=a.L;else{if(i=u-Ie(a,o),!(i>Uo)){r>-Uo?(t=a.P,e=a):i>-Uo?(t=a,e=a.N):t=e=a;break}if(!a.R){t=a;break}a=a.R}var l=Ue(n);if(ol.insert(t,l),t||e){if(t===e)return Be(t),e=Ue(t.site),ol.insert(l,e),l.edge=e.edge=Ke(t.site,l.site),$e(t),void $e(e);if(!e)return void(l.edge=Ke(t.site,l.site));Be(t),Be(e);var c=t.site,f=c.x,s=c.y,h=n.x-f,p=n.y-s,g=e.site,v=g.x-f,d=g.y-s,y=2*(h*d-p*v),m=h*h+p*p,M=v*v+d*d,x={x:(d*m-p*M)/y+f,y:(h*M-v*m)/y+s};nr(e.edge,c,g,x),l.edge=Ke(c,n,null,x),e.edge=Ke(n,g,null,x),$e(t),$e(e)}}function Oe(n,t){var e=n.site,r=e.x,i=e.y,u=i-t;if(!u)return r;var o=n.P;if(!o)return-(1/0);e=o.site;var a=e.x,l=e.y,c=l-t;if(!c)return a;var f=a-r,s=1/u-1/c,h=f/c;return s?(-h+Math.sqrt(h*h-2*s*(f*f/(-2*c)-l+c/2+i-u/2)))/s+r:(r+a)/2}function Ie(n,t){var e=n.N;if(e)return Oe(e,t);var r=n.site;return r.y===t?r.x:1/0}function Ye(n){this.site=n,this.edges=[]}function Ze(n){for(var t,e,r,i,u,o,a,l,c,f,s=n[0][0],h=n[1][0],p=n[0][1],g=n[1][1],v=ul,d=v.length;d--;)if(u=v[d],u&&u.prepare())for(a=u.edges,l=a.length,o=0;l>o;)f=a[o].end(),r=f.x,i=f.y,c=a[++o%l].start(),t=c.x,e=c.y,(xo(r-t)>Uo||xo(i-e)>Uo)&&(a.splice(o,0,new tr(Qe(u.site,f,xo(r-s)Uo?{x:s,y:xo(t-s)Uo?{x:xo(e-g)Uo?{x:h,y:xo(t-h)Uo?{x:xo(e-p)=-jo)){var p=l*l+c*c,g=f*f+s*s,v=(s*p-c*g)/h,d=(l*g-f*p)/h,s=d+a,y=fl.pop()||new Xe;y.arc=n,y.site=i,y.x=v+o,y.y=s+Math.sqrt(v*v+d*d),y.cy=s,n.circle=y;for(var m=null,M=ll._;M;)if(y.yd||d>=a)return;if(h>g){if(u){if(u.y>=c)return}else u={x:d,y:l};e={x:d,y:c}}else{if(u){if(u.yr||r>1)if(h>g){if(u){if(u.y>=c)return}else u={x:(l-i)/r,y:l};e={x:(c-i)/r,y:c}}else{if(u){if(u.yp){if(u){if(u.x>=a)return}else u={x:o,y:r*o+i};e={x:a,y:r*a+i}}else{if(u){if(u.xu||s>o||r>h||i>p)){if(g=n.point){var g,v=t-n.x,d=e-n.y,y=v*v+d*d;if(l>y){var m=Math.sqrt(l=y);r=t-m,i=e-m,u=t+m,o=e+m,a=g}}for(var M=n.nodes,x=.5*(f+h),b=.5*(s+p),_=t>=x,w=e>=b,S=w<<1|_,k=S+4;k>S;++S)if(n=M[3&S])switch(3&S){case 0:c(n,f,s,x,b);break;case 1:c(n,x,s,h,b);break;case 2:c(n,f,b,x,p);break;case 3:c(n,x,b,h,p)}}}(n,r,i,u,o),a}function vr(n,t){n=ao.rgb(n),t=ao.rgb(t);var e=n.r,r=n.g,i=n.b,u=t.r-e,o=t.g-r,a=t.b-i;return function(n){return"#"+bn(Math.round(e+u*n))+bn(Math.round(r+o*n))+bn(Math.round(i+a*n))}}function dr(n,t){var e,r={},i={};for(e in n)e in t?r[e]=Mr(n[e],t[e]):i[e]=n[e];for(e in t)e in n||(i[e]=t[e]);return function(n){for(e in r)i[e]=r[e](n);return i}}function yr(n,t){return n=+n,t=+t,function(e){return n*(1-e)+t*e}}function mr(n,t){var e,r,i,u=hl.lastIndex=pl.lastIndex=0,o=-1,a=[],l=[];for(n+="",t+="";(e=hl.exec(n))&&(r=pl.exec(t));)(i=r.index)>u&&(i=t.slice(u,i),a[o]?a[o]+=i:a[++o]=i),(e=e[0])===(r=r[0])?a[o]?a[o]+=r:a[++o]=r:(a[++o]=null,l.push({i:o,x:yr(e,r)})),u=pl.lastIndex;return ur;++r)a[(e=l[r]).i]=e.x(n);return a.join("")})}function Mr(n,t){for(var e,r=ao.interpolators.length;--r>=0&&!(e=ao.interpolators[r](n,t)););return e}function xr(n,t){var e,r=[],i=[],u=n.length,o=t.length,a=Math.min(n.length,t.length);for(e=0;a>e;++e)r.push(Mr(n[e],t[e]));for(;u>e;++e)i[e]=n[e];for(;o>e;++e)i[e]=t[e];return function(n){for(e=0;a>e;++e)i[e]=r[e](n);return i}}function br(n){return function(t){return 0>=t?0:t>=1?1:n(t)}}function _r(n){return function(t){return 1-n(1-t)}}function wr(n){return function(t){return.5*(.5>t?n(2*t):2-n(2-2*t))}}function Sr(n){return n*n}function kr(n){return n*n*n}function Nr(n){if(0>=n)return 0;if(n>=1)return 1;var t=n*n,e=t*n;return 4*(.5>n?e:3*(n-t)+e-.75)}function Er(n){return function(t){return Math.pow(t,n)}}function Ar(n){return 1-Math.cos(n*Io)}function Cr(n){return Math.pow(2,10*(n-1))}function zr(n){return 1-Math.sqrt(1-n*n)}function Lr(n,t){var e;return arguments.length<2&&(t=.45),arguments.length?e=t/Ho*Math.asin(1/n):(n=1,e=t/4),function(r){return 1+n*Math.pow(2,-10*r)*Math.sin((r-e)*Ho/t)}}function qr(n){return n||(n=1.70158),function(t){return t*t*((n+1)*t-n)}}function Tr(n){return 1/2.75>n?7.5625*n*n:2/2.75>n?7.5625*(n-=1.5/2.75)*n+.75:2.5/2.75>n?7.5625*(n-=2.25/2.75)*n+.9375:7.5625*(n-=2.625/2.75)*n+.984375}function Rr(n,t){n=ao.hcl(n),t=ao.hcl(t);var e=n.h,r=n.c,i=n.l,u=t.h-e,o=t.c-r,a=t.l-i;return isNaN(o)&&(o=0,r=isNaN(r)?t.c:r),isNaN(u)?(u=0,e=isNaN(e)?t.h:e):u>180?u-=360:-180>u&&(u+=360),function(n){return sn(e+u*n,r+o*n,i+a*n)+""}}function Dr(n,t){n=ao.hsl(n),t=ao.hsl(t);var e=n.h,r=n.s,i=n.l,u=t.h-e,o=t.s-r,a=t.l-i;return isNaN(o)&&(o=0,r=isNaN(r)?t.s:r),isNaN(u)?(u=0,e=isNaN(e)?t.h:e):u>180?u-=360:-180>u&&(u+=360),function(n){return cn(e+u*n,r+o*n,i+a*n)+""}}function Pr(n,t){n=ao.lab(n),t=ao.lab(t);var e=n.l,r=n.a,i=n.b,u=t.l-e,o=t.a-r,a=t.b-i;return function(n){return pn(e+u*n,r+o*n,i+a*n)+""}}function Ur(n,t){return t-=n,function(e){return Math.round(n+t*e)}}function jr(n){var t=[n.a,n.b],e=[n.c,n.d],r=Hr(t),i=Fr(t,e),u=Hr(Or(e,t,-i))||0;t[0]*e[1]180?t+=360:t-n>180&&(n+=360),r.push({i:e.push(Ir(e)+"rotate(",null,")")-2,x:yr(n,t)})):t&&e.push(Ir(e)+"rotate("+t+")")}function Vr(n,t,e,r){n!==t?r.push({i:e.push(Ir(e)+"skewX(",null,")")-2,x:yr(n,t)}):t&&e.push(Ir(e)+"skewX("+t+")")}function Xr(n,t,e,r){if(n[0]!==t[0]||n[1]!==t[1]){var i=e.push(Ir(e)+"scale(",null,",",null,")");r.push({i:i-4,x:yr(n[0],t[0])},{i:i-2,x:yr(n[1],t[1])})}else 1===t[0]&&1===t[1]||e.push(Ir(e)+"scale("+t+")")}function $r(n,t){var e=[],r=[];return n=ao.transform(n),t=ao.transform(t),Yr(n.translate,t.translate,e,r),Zr(n.rotate,t.rotate,e,r),Vr(n.skew,t.skew,e,r),Xr(n.scale,t.scale,e,r),n=t=null,function(n){for(var t,i=-1,u=r.length;++i=0;)e.push(i[r])}function oi(n,t){for(var e=[n],r=[];null!=(n=e.pop());)if(r.push(n),(u=n.children)&&(i=u.length))for(var i,u,o=-1;++oe;++e)(t=n[e][1])>i&&(r=e,i=t);return r}function yi(n){return n.reduce(mi,0)}function mi(n,t){return n+t[1]}function Mi(n,t){return xi(n,Math.ceil(Math.log(t.length)/Math.LN2+1))}function xi(n,t){for(var e=-1,r=+n[0],i=(n[1]-r)/t,u=[];++e<=t;)u[e]=i*e+r;return u}function bi(n){return[ao.min(n),ao.max(n)]}function _i(n,t){return n.value-t.value}function wi(n,t){var e=n._pack_next;n._pack_next=t,t._pack_prev=n,t._pack_next=e,e._pack_prev=t}function Si(n,t){n._pack_next=t,t._pack_prev=n}function ki(n,t){var e=t.x-n.x,r=t.y-n.y,i=n.r+t.r;return.999*i*i>e*e+r*r}function Ni(n){function t(n){f=Math.min(n.x-n.r,f),s=Math.max(n.x+n.r,s),h=Math.min(n.y-n.r,h),p=Math.max(n.y+n.r,p)}if((e=n.children)&&(c=e.length)){var e,r,i,u,o,a,l,c,f=1/0,s=-(1/0),h=1/0,p=-(1/0);if(e.forEach(Ei),r=e[0],r.x=-r.r,r.y=0,t(r),c>1&&(i=e[1],i.x=i.r,i.y=0,t(i),c>2))for(u=e[2],zi(r,i,u),t(u),wi(r,u),r._pack_prev=u,wi(u,i),i=r._pack_next,o=3;c>o;o++){zi(r,i,u=e[o]);var g=0,v=1,d=1;for(a=i._pack_next;a!==i;a=a._pack_next,v++)if(ki(a,u)){g=1;break}if(1==g)for(l=r._pack_prev;l!==a._pack_prev&&!ki(l,u);l=l._pack_prev,d++);g?(d>v||v==d&&i.ro;o++)u=e[o],u.x-=y,u.y-=m,M=Math.max(M,u.r+Math.sqrt(u.x*u.x+u.y*u.y));n.r=M,e.forEach(Ai)}}function Ei(n){n._pack_next=n._pack_prev=n}function Ai(n){delete n._pack_next,delete n._pack_prev}function Ci(n,t,e,r){var i=n.children;if(n.x=t+=r*n.x,n.y=e+=r*n.y,n.r*=r,i)for(var u=-1,o=i.length;++u=0;)t=i[u],t.z+=e,t.m+=e,e+=t.s+(r+=t.c)}function Pi(n,t,e){return n.a.parent===t.parent?n.a:e}function Ui(n){return 1+ao.max(n,function(n){return n.y})}function ji(n){return n.reduce(function(n,t){return n+t.x},0)/n.length}function Fi(n){var t=n.children;return t&&t.length?Fi(t[0]):n}function Hi(n){var t,e=n.children;return e&&(t=e.length)?Hi(e[t-1]):n}function Oi(n){return{x:n.x,y:n.y,dx:n.dx,dy:n.dy}}function Ii(n,t){var e=n.x+t[3],r=n.y+t[0],i=n.dx-t[1]-t[3],u=n.dy-t[0]-t[2];return 0>i&&(e+=i/2,i=0),0>u&&(r+=u/2,u=0),{x:e,y:r,dx:i,dy:u}}function Yi(n){var t=n[0],e=n[n.length-1];return e>t?[t,e]:[e,t]}function Zi(n){return n.rangeExtent?n.rangeExtent():Yi(n.range())}function Vi(n,t,e,r){var i=e(n[0],n[1]),u=r(t[0],t[1]);return function(n){return u(i(n))}}function Xi(n,t){var e,r=0,i=n.length-1,u=n[r],o=n[i];return u>o&&(e=r,r=i,i=e,e=u,u=o,o=e),n[r]=t.floor(u),n[i]=t.ceil(o),n}function $i(n){return n?{floor:function(t){return Math.floor(t/n)*n},ceil:function(t){return Math.ceil(t/n)*n}}:Sl}function Bi(n,t,e,r){var i=[],u=[],o=0,a=Math.min(n.length,t.length)-1;for(n[a]2?Bi:Vi,l=r?Wr:Br;return o=i(n,t,l,e),a=i(t,n,l,Mr),u}function u(n){return o(n)}var o,a;return u.invert=function(n){return a(n)},u.domain=function(t){return arguments.length?(n=t.map(Number),i()):n},u.range=function(n){return arguments.length?(t=n,i()):t},u.rangeRound=function(n){return u.range(n).interpolate(Ur)},u.clamp=function(n){return arguments.length?(r=n,i()):r},u.interpolate=function(n){return arguments.length?(e=n,i()):e},u.ticks=function(t){return Qi(n,t)},u.tickFormat=function(t,e){return nu(n,t,e)},u.nice=function(t){return Gi(n,t),i()},u.copy=function(){return Wi(n,t,e,r)},i()}function Ji(n,t){return ao.rebind(n,t,"range","rangeRound","interpolate","clamp")}function Gi(n,t){return Xi(n,$i(Ki(n,t)[2])),Xi(n,$i(Ki(n,t)[2])),n}function Ki(n,t){null==t&&(t=10);var e=Yi(n),r=e[1]-e[0],i=Math.pow(10,Math.floor(Math.log(r/t)/Math.LN10)),u=t/r*i;return.15>=u?i*=10:.35>=u?i*=5:.75>=u&&(i*=2),e[0]=Math.ceil(e[0]/i)*i,e[1]=Math.floor(e[1]/i)*i+.5*i,e[2]=i,e}function Qi(n,t){return ao.range.apply(ao,Ki(n,t))}function nu(n,t,e){var r=Ki(n,t);if(e){var i=ha.exec(e);if(i.shift(),"s"===i[8]){var u=ao.formatPrefix(Math.max(xo(r[0]),xo(r[1])));return i[7]||(i[7]="."+tu(u.scale(r[2]))),i[8]="f",e=ao.format(i.join("")),function(n){return e(u.scale(n))+u.symbol}}i[7]||(i[7]="."+eu(i[8],r)),e=i.join("")}else e=",."+tu(r[2])+"f";return ao.format(e)}function tu(n){return-Math.floor(Math.log(n)/Math.LN10+.01)}function eu(n,t){var e=tu(t[2]);return n in kl?Math.abs(e-tu(Math.max(xo(t[0]),xo(t[1]))))+ +("e"!==n):e-2*("%"===n)}function ru(n,t,e,r){function i(n){return(e?Math.log(0>n?0:n):-Math.log(n>0?0:-n))/Math.log(t)}function u(n){return e?Math.pow(t,n):-Math.pow(t,-n)}function o(t){return n(i(t))}return o.invert=function(t){return u(n.invert(t))},o.domain=function(t){return arguments.length?(e=t[0]>=0,n.domain((r=t.map(Number)).map(i)),o):r},o.base=function(e){return arguments.length?(t=+e,n.domain(r.map(i)),o):t},o.nice=function(){var t=Xi(r.map(i),e?Math:El);return n.domain(t),r=t.map(u),o},o.ticks=function(){var n=Yi(r),o=[],a=n[0],l=n[1],c=Math.floor(i(a)),f=Math.ceil(i(l)),s=t%1?2:t;if(isFinite(f-c)){if(e){for(;f>c;c++)for(var h=1;s>h;h++)o.push(u(c)*h);o.push(u(c))}else for(o.push(u(c));c++0;h--)o.push(u(c)*h);for(c=0;o[c]l;f--);o=o.slice(c,f)}return o},o.tickFormat=function(n,e){if(!arguments.length)return Nl;arguments.length<2?e=Nl:"function"!=typeof e&&(e=ao.format(e));var r=Math.max(1,t*n/o.ticks().length);return function(n){var o=n/u(Math.round(i(n)));return t-.5>o*t&&(o*=t),r>=o?e(n):""}},o.copy=function(){return ru(n.copy(),t,e,r)},Ji(o,n)}function iu(n,t,e){function r(t){return n(i(t))}var i=uu(t),u=uu(1/t);return r.invert=function(t){return u(n.invert(t))},r.domain=function(t){return arguments.length?(n.domain((e=t.map(Number)).map(i)),r):e},r.ticks=function(n){return Qi(e,n)},r.tickFormat=function(n,t){return nu(e,n,t)},r.nice=function(n){return r.domain(Gi(e,n))},r.exponent=function(o){return arguments.length?(i=uu(t=o),u=uu(1/t),n.domain(e.map(i)),r):t},r.copy=function(){return iu(n.copy(),t,e)},Ji(r,n)}function uu(n){return function(t){return 0>t?-Math.pow(-t,n):Math.pow(t,n)}}function ou(n,t){function e(e){return u[((i.get(e)||("range"===t.t?i.set(e,n.push(e)):NaN))-1)%u.length]}function r(t,e){return ao.range(n.length).map(function(n){return t+e*n})}var i,u,o;return e.domain=function(r){if(!arguments.length)return n;n=[],i=new c;for(var u,o=-1,a=r.length;++oe?[NaN,NaN]:[e>0?a[e-1]:n[0],et?NaN:t/u+n,[t,t+1/u]},r.copy=function(){return lu(n,t,e)},i()}function cu(n,t){function e(e){return e>=e?t[ao.bisect(n,e)]:void 0}return e.domain=function(t){return arguments.length?(n=t,e):n},e.range=function(n){return arguments.length?(t=n,e):t},e.invertExtent=function(e){return e=t.indexOf(e),[n[e-1],n[e]]},e.copy=function(){return cu(n,t)},e}function fu(n){function t(n){return+n}return t.invert=t,t.domain=t.range=function(e){return arguments.length?(n=e.map(t),t):n},t.ticks=function(t){return Qi(n,t)},t.tickFormat=function(t,e){return nu(n,t,e)},t.copy=function(){return fu(n)},t}function su(){return 0}function hu(n){return n.innerRadius}function pu(n){return n.outerRadius}function gu(n){return n.startAngle}function vu(n){return n.endAngle}function du(n){return n&&n.padAngle}function yu(n,t,e,r){return(n-e)*t-(t-r)*n>0?0:1}function mu(n,t,e,r,i){var u=n[0]-t[0],o=n[1]-t[1],a=(i?r:-r)/Math.sqrt(u*u+o*o),l=a*o,c=-a*u,f=n[0]+l,s=n[1]+c,h=t[0]+l,p=t[1]+c,g=(f+h)/2,v=(s+p)/2,d=h-f,y=p-s,m=d*d+y*y,M=e-r,x=f*p-h*s,b=(0>y?-1:1)*Math.sqrt(Math.max(0,M*M*m-x*x)),_=(x*y-d*b)/m,w=(-x*d-y*b)/m,S=(x*y+d*b)/m,k=(-x*d+y*b)/m,N=_-g,E=w-v,A=S-g,C=k-v;return N*N+E*E>A*A+C*C&&(_=S,w=k),[[_-l,w-c],[_*e/M,w*e/M]]}function Mu(n){function t(t){function o(){c.push("M",u(n(f),a))}for(var l,c=[],f=[],s=-1,h=t.length,p=En(e),g=En(r);++s1?n.join("L"):n+"Z"}function bu(n){return n.join("L")+"Z"}function _u(n){for(var t=0,e=n.length,r=n[0],i=[r[0],",",r[1]];++t1&&i.push("H",r[0]),i.join("")}function wu(n){for(var t=0,e=n.length,r=n[0],i=[r[0],",",r[1]];++t1){a=t[1],u=n[l],l++,r+="C"+(i[0]+o[0])+","+(i[1]+o[1])+","+(u[0]-a[0])+","+(u[1]-a[1])+","+u[0]+","+u[1];for(var c=2;c9&&(i=3*t/Math.sqrt(i),o[a]=i*e,o[a+1]=i*r));for(a=-1;++a<=l;)i=(n[Math.min(l,a+1)][0]-n[Math.max(0,a-1)][0])/(6*(1+o[a]*o[a])),u.push([i||0,o[a]*i||0]);return u}function Fu(n){return n.length<3?xu(n):n[0]+Au(n,ju(n))}function Hu(n){for(var t,e,r,i=-1,u=n.length;++i=t?o(n-t):void(f.c=o)}function o(e){var i=g.active,u=g[i];u&&(u.timer.c=null,u.timer.t=NaN,--g.count,delete g[i],u.event&&u.event.interrupt.call(n,n.__data__,u.index));for(var o in g)if(r>+o){var c=g[o];c.timer.c=null,c.timer.t=NaN,--g.count,delete g[o]}f.c=a,qn(function(){return f.c&&a(e||1)&&(f.c=null,f.t=NaN),1},0,l),g.active=r,v.event&&v.event.start.call(n,n.__data__,t),p=[],v.tween.forEach(function(e,r){(r=r.call(n,n.__data__,t))&&p.push(r)}),h=v.ease,s=v.duration}function a(i){for(var u=i/s,o=h(u),a=p.length;a>0;)p[--a].call(n,o);return u>=1?(v.event&&v.event.end.call(n,n.__data__,t),--g.count?delete g[r]:delete n[e],1):void 0}var l,f,s,h,p,g=n[e]||(n[e]={active:0,count:0}),v=g[r];v||(l=i.time,f=qn(u,0,l),v=g[r]={tween:new c,time:l,timer:f,delay:i.delay,duration:i.duration,ease:i.ease,index:t},i=null,++g.count)}function no(n,t,e){n.attr("transform",function(n){var r=t(n);return"translate("+(isFinite(r)?r:e(n))+",0)"})}function to(n,t,e){n.attr("transform",function(n){var r=t(n);return"translate(0,"+(isFinite(r)?r:e(n))+")"})}function eo(n){return n.toISOString()}function ro(n,t,e){function r(t){return n(t)}function i(n,e){var r=n[1]-n[0],i=r/e,u=ao.bisect(Kl,i);return u==Kl.length?[t.year,Ki(n.map(function(n){return n/31536e6}),e)[2]]:u?t[i/Kl[u-1]1?{floor:function(t){for(;e(t=n.floor(t));)t=io(t-1);return t},ceil:function(t){for(;e(t=n.ceil(t));)t=io(+t+1);return t}}:n))},r.ticks=function(n,t){var e=Yi(r.domain()),u=null==n?i(e,10):"number"==typeof n?i(e,n):!n.range&&[{range:n},t];return u&&(n=u[0],t=u[1]),n.range(e[0],io(+e[1]+1),1>t?1:t)},r.tickFormat=function(){return e},r.copy=function(){return ro(n.copy(),t,e)},Ji(r,n)}function io(n){return new Date(n)}function uo(n){return JSON.parse(n.responseText)}function oo(n){var t=fo.createRange();return t.selectNode(fo.body),t.createContextualFragment(n.responseText)}var ao={version:"3.5.17"},lo=[].slice,co=function(n){return lo.call(n)},fo=this.document;if(fo)try{co(fo.documentElement.childNodes)[0].nodeType}catch(so){co=function(n){for(var t=n.length,e=new Array(t);t--;)e[t]=n[t];return e}}if(Date.now||(Date.now=function(){return+new Date}),fo)try{fo.createElement("DIV").style.setProperty("opacity",0,"")}catch(ho){var po=this.Element.prototype,go=po.setAttribute,vo=po.setAttributeNS,yo=this.CSSStyleDeclaration.prototype,mo=yo.setProperty;po.setAttribute=function(n,t){go.call(this,n,t+"")},po.setAttributeNS=function(n,t,e){vo.call(this,n,t,e+"")},yo.setProperty=function(n,t,e){mo.call(this,n,t+"",e)}}ao.ascending=e,ao.descending=function(n,t){return n>t?-1:t>n?1:t>=n?0:NaN},ao.min=function(n,t){var e,r,i=-1,u=n.length;if(1===arguments.length){for(;++i=r){e=r;break}for(;++ir&&(e=r)}else{for(;++i=r){e=r;break}for(;++ir&&(e=r)}return e},ao.max=function(n,t){var e,r,i=-1,u=n.length;if(1===arguments.length){for(;++i=r){e=r;break}for(;++ie&&(e=r)}else{for(;++i=r){e=r;break}for(;++ie&&(e=r)}return e},ao.extent=function(n,t){var e,r,i,u=-1,o=n.length;if(1===arguments.length){for(;++u=r){e=i=r;break}for(;++ur&&(e=r),r>i&&(i=r))}else{for(;++u=r){e=i=r;break}for(;++ur&&(e=r),r>i&&(i=r))}return[e,i]},ao.sum=function(n,t){var e,r=0,u=n.length,o=-1;if(1===arguments.length)for(;++o1?l/(f-1):void 0},ao.deviation=function(){var n=ao.variance.apply(this,arguments);return n?Math.sqrt(n):n};var Mo=u(e);ao.bisectLeft=Mo.left,ao.bisect=ao.bisectRight=Mo.right,ao.bisector=function(n){return u(1===n.length?function(t,r){return e(n(t),r)}:n)},ao.shuffle=function(n,t,e){(u=arguments.length)<3&&(e=n.length,2>u&&(t=0));for(var r,i,u=e-t;u;)i=Math.random()*u--|0,r=n[u+t],n[u+t]=n[i+t],n[i+t]=r;return n},ao.permute=function(n,t){for(var e=t.length,r=new Array(e);e--;)r[e]=n[t[e]];return r},ao.pairs=function(n){for(var t,e=0,r=n.length-1,i=n[0],u=new Array(0>r?0:r);r>e;)u[e]=[t=i,i=n[++e]];return u},ao.transpose=function(n){if(!(i=n.length))return[];for(var t=-1,e=ao.min(n,o),r=new Array(e);++t=0;)for(r=n[i],t=r.length;--t>=0;)e[--o]=r[t];return e};var xo=Math.abs;ao.range=function(n,t,e){if(arguments.length<3&&(e=1,arguments.length<2&&(t=n,n=0)),(t-n)/e===1/0)throw new Error("infinite range");var r,i=[],u=a(xo(e)),o=-1;if(n*=u,t*=u,e*=u,0>e)for(;(r=n+e*++o)>t;)i.push(r/u);else for(;(r=n+e*++o)=u.length)return r?r.call(i,o):e?o.sort(e):o;for(var l,f,s,h,p=-1,g=o.length,v=u[a++],d=new c;++p=u.length)return n;var r=[],i=o[e++];return n.forEach(function(n,i){r.push({key:n,values:t(i,e)})}),i?r.sort(function(n,t){return i(n.key,t.key)}):r}var e,r,i={},u=[],o=[];return i.map=function(t,e){return n(e,t,0)},i.entries=function(e){return t(n(ao.map,e,0),0)},i.key=function(n){return u.push(n),i},i.sortKeys=function(n){return o[u.length-1]=n,i},i.sortValues=function(n){return e=n,i},i.rollup=function(n){return r=n,i},i},ao.set=function(n){var t=new y;if(n)for(var e=0,r=n.length;r>e;++e)t.add(n[e]);return t},l(y,{has:h,add:function(n){return this._[f(n+="")]=!0,n},remove:p,values:g,size:v,empty:d,forEach:function(n){for(var t in this._)n.call(this,s(t))}}),ao.behavior={},ao.rebind=function(n,t){for(var e,r=1,i=arguments.length;++r=0&&(r=n.slice(e+1),n=n.slice(0,e)),n)return arguments.length<2?this[n].on(r):this[n].on(r,t);if(2===arguments.length){if(null==t)for(n in this)this.hasOwnProperty(n)&&this[n].on(r,null);return this}},ao.event=null,ao.requote=function(n){return n.replace(So,"\\$&")};var So=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,ko={}.__proto__?function(n,t){n.__proto__=t}:function(n,t){for(var e in t)n[e]=t[e]},No=function(n,t){return t.querySelector(n)},Eo=function(n,t){return t.querySelectorAll(n)},Ao=function(n,t){var e=n.matches||n[x(n,"matchesSelector")];return(Ao=function(n,t){return e.call(n,t)})(n,t)};"function"==typeof Sizzle&&(No=function(n,t){return Sizzle(n,t)[0]||null},Eo=Sizzle,Ao=Sizzle.matchesSelector),ao.selection=function(){return ao.select(fo.documentElement)};var Co=ao.selection.prototype=[];Co.select=function(n){var t,e,r,i,u=[];n=A(n);for(var o=-1,a=this.length;++o=0&&"xmlns"!==(e=n.slice(0,t))&&(n=n.slice(t+1)),Lo.hasOwnProperty(e)?{space:Lo[e],local:n}:n}},Co.attr=function(n,t){if(arguments.length<2){if("string"==typeof n){var e=this.node();return n=ao.ns.qualify(n),n.local?e.getAttributeNS(n.space,n.local):e.getAttribute(n)}for(t in n)this.each(z(t,n[t]));return this}return this.each(z(n,t))},Co.classed=function(n,t){if(arguments.length<2){if("string"==typeof n){var e=this.node(),r=(n=T(n)).length,i=-1;if(t=e.classList){for(;++ii){if("string"!=typeof n){2>i&&(e="");for(r in n)this.each(P(r,n[r],e));return this}if(2>i){var u=this.node();return t(u).getComputedStyle(u,null).getPropertyValue(n)}r=""}return this.each(P(n,e,r))},Co.property=function(n,t){if(arguments.length<2){if("string"==typeof n)return this.node()[n];for(t in n)this.each(U(t,n[t]));return this}return this.each(U(n,t))},Co.text=function(n){return arguments.length?this.each("function"==typeof n?function(){var t=n.apply(this,arguments);this.textContent=null==t?"":t}:null==n?function(){this.textContent=""}:function(){this.textContent=n}):this.node().textContent},Co.html=function(n){return arguments.length?this.each("function"==typeof n?function(){var t=n.apply(this,arguments);this.innerHTML=null==t?"":t}:null==n?function(){this.innerHTML=""}:function(){this.innerHTML=n}):this.node().innerHTML},Co.append=function(n){return n=j(n),this.select(function(){return this.appendChild(n.apply(this,arguments))})},Co.insert=function(n,t){return n=j(n),t=A(t),this.select(function(){return this.insertBefore(n.apply(this,arguments),t.apply(this,arguments)||null)})},Co.remove=function(){return this.each(F)},Co.data=function(n,t){function e(n,e){var r,i,u,o=n.length,s=e.length,h=Math.min(o,s),p=new Array(s),g=new Array(s),v=new Array(o);if(t){var d,y=new c,m=new Array(o);for(r=-1;++rr;++r)g[r]=H(e[r]);for(;o>r;++r)v[r]=n[r]}g.update=p,g.parentNode=p.parentNode=v.parentNode=n.parentNode,a.push(g),l.push(p),f.push(v)}var r,i,u=-1,o=this.length;if(!arguments.length){for(n=new Array(o=(r=this[0]).length);++uu;u++){i.push(t=[]),t.parentNode=(e=this[u]).parentNode;for(var a=0,l=e.length;l>a;a++)(r=e[a])&&n.call(r,r.__data__,a,u)&&t.push(r)}return E(i)},Co.order=function(){for(var n=-1,t=this.length;++n=0;)(e=r[i])&&(u&&u!==e.nextSibling&&u.parentNode.insertBefore(e,u),u=e);return this},Co.sort=function(n){n=I.apply(this,arguments);for(var t=-1,e=this.length;++tn;n++)for(var e=this[n],r=0,i=e.length;i>r;r++){var u=e[r];if(u)return u}return null},Co.size=function(){var n=0;return Y(this,function(){++n}),n};var qo=[];ao.selection.enter=Z,ao.selection.enter.prototype=qo,qo.append=Co.append,qo.empty=Co.empty,qo.node=Co.node,qo.call=Co.call,qo.size=Co.size,qo.select=function(n){for(var t,e,r,i,u,o=[],a=-1,l=this.length;++ar){if("string"!=typeof n){2>r&&(t=!1);for(e in n)this.each(X(e,n[e],t));return this}if(2>r)return(r=this.node()["__on"+n])&&r._;e=!1}return this.each(X(n,t,e))};var To=ao.map({mouseenter:"mouseover",mouseleave:"mouseout"});fo&&To.forEach(function(n){"on"+n in fo&&To.remove(n)});var Ro,Do=0;ao.mouse=function(n){return J(n,k())};var Po=this.navigator&&/WebKit/.test(this.navigator.userAgent)?-1:0;ao.touch=function(n,t,e){if(arguments.length<3&&(e=t,t=k().changedTouches),t)for(var r,i=0,u=t.length;u>i;++i)if((r=t[i]).identifier===e)return J(n,r)},ao.behavior.drag=function(){function n(){this.on("mousedown.drag",u).on("touchstart.drag",o)}function e(n,t,e,u,o){return function(){function a(){var n,e,r=t(h,v);r&&(n=r[0]-M[0],e=r[1]-M[1],g|=n|e,M=r,p({type:"drag",x:r[0]+c[0],y:r[1]+c[1],dx:n,dy:e}))}function l(){t(h,v)&&(y.on(u+d,null).on(o+d,null),m(g),p({type:"dragend"}))}var c,f=this,s=ao.event.target.correspondingElement||ao.event.target,h=f.parentNode,p=r.of(f,arguments),g=0,v=n(),d=".drag"+(null==v?"":"-"+v),y=ao.select(e(s)).on(u+d,a).on(o+d,l),m=W(s),M=t(h,v);i?(c=i.apply(f,arguments),c=[c.x-M[0],c.y-M[1]]):c=[0,0],p({type:"dragstart"})}}var r=N(n,"drag","dragstart","dragend"),i=null,u=e(b,ao.mouse,t,"mousemove","mouseup"),o=e(G,ao.touch,m,"touchmove","touchend");return n.origin=function(t){return arguments.length?(i=t,n):i},ao.rebind(n,r,"on")},ao.touches=function(n,t){return arguments.length<2&&(t=k().touches),t?co(t).map(function(t){var e=J(n,t);return e.identifier=t.identifier,e}):[]};var Uo=1e-6,jo=Uo*Uo,Fo=Math.PI,Ho=2*Fo,Oo=Ho-Uo,Io=Fo/2,Yo=Fo/180,Zo=180/Fo,Vo=Math.SQRT2,Xo=2,$o=4;ao.interpolateZoom=function(n,t){var e,r,i=n[0],u=n[1],o=n[2],a=t[0],l=t[1],c=t[2],f=a-i,s=l-u,h=f*f+s*s;if(jo>h)r=Math.log(c/o)/Vo,e=function(n){return[i+n*f,u+n*s,o*Math.exp(Vo*n*r)]};else{var p=Math.sqrt(h),g=(c*c-o*o+$o*h)/(2*o*Xo*p),v=(c*c-o*o-$o*h)/(2*c*Xo*p),d=Math.log(Math.sqrt(g*g+1)-g),y=Math.log(Math.sqrt(v*v+1)-v);r=(y-d)/Vo,e=function(n){var t=n*r,e=rn(d),a=o/(Xo*p)*(e*un(Vo*t+d)-en(d));return[i+a*f,u+a*s,o*e/rn(Vo*t+d)]}}return e.duration=1e3*r,e},ao.behavior.zoom=function(){function n(n){n.on(L,s).on(Wo+".zoom",p).on("dblclick.zoom",g).on(R,h)}function e(n){return[(n[0]-k.x)/k.k,(n[1]-k.y)/k.k]}function r(n){return[n[0]*k.k+k.x,n[1]*k.k+k.y]}function i(n){k.k=Math.max(A[0],Math.min(A[1],n))}function u(n,t){t=r(t),k.x+=n[0]-t[0],k.y+=n[1]-t[1]}function o(t,e,r,o){t.__chart__={x:k.x,y:k.y,k:k.k},i(Math.pow(2,o)),u(d=e,r),t=ao.select(t),C>0&&(t=t.transition().duration(C)),t.call(n.event)}function a(){b&&b.domain(x.range().map(function(n){return(n-k.x)/k.k}).map(x.invert)),w&&w.domain(_.range().map(function(n){return(n-k.y)/k.k}).map(_.invert))}function l(n){z++||n({type:"zoomstart"})}function c(n){a(),n({type:"zoom",scale:k.k,translate:[k.x,k.y]})}function f(n){--z||(n({type:"zoomend"}),d=null)}function s(){function n(){a=1,u(ao.mouse(i),h),c(o)}function r(){s.on(q,null).on(T,null),p(a),f(o)}var i=this,o=D.of(i,arguments),a=0,s=ao.select(t(i)).on(q,n).on(T,r),h=e(ao.mouse(i)),p=W(i);Il.call(i),l(o)}function h(){function n(){var n=ao.touches(g);return p=k.k,n.forEach(function(n){n.identifier in d&&(d[n.identifier]=e(n))}),n}function t(){var t=ao.event.target;ao.select(t).on(x,r).on(b,a),_.push(t);for(var e=ao.event.changedTouches,i=0,u=e.length;u>i;++i)d[e[i].identifier]=null;var l=n(),c=Date.now();if(1===l.length){if(500>c-M){var f=l[0];o(g,f,d[f.identifier],Math.floor(Math.log(k.k)/Math.LN2)+1),S()}M=c}else if(l.length>1){var f=l[0],s=l[1],h=f[0]-s[0],p=f[1]-s[1];y=h*h+p*p}}function r(){var n,t,e,r,o=ao.touches(g);Il.call(g);for(var a=0,l=o.length;l>a;++a,r=null)if(e=o[a],r=d[e.identifier]){if(t)break;n=e,t=r}if(r){var f=(f=e[0]-n[0])*f+(f=e[1]-n[1])*f,s=y&&Math.sqrt(f/y);n=[(n[0]+e[0])/2,(n[1]+e[1])/2],t=[(t[0]+r[0])/2,(t[1]+r[1])/2],i(s*p)}M=null,u(n,t),c(v)}function a(){if(ao.event.touches.length){for(var t=ao.event.changedTouches,e=0,r=t.length;r>e;++e)delete d[t[e].identifier];for(var i in d)return void n()}ao.selectAll(_).on(m,null),w.on(L,s).on(R,h),N(),f(v)}var p,g=this,v=D.of(g,arguments),d={},y=0,m=".zoom-"+ao.event.changedTouches[0].identifier,x="touchmove"+m,b="touchend"+m,_=[],w=ao.select(g),N=W(g);t(),l(v),w.on(L,null).on(R,t)}function p(){var n=D.of(this,arguments);m?clearTimeout(m):(Il.call(this),v=e(d=y||ao.mouse(this)),l(n)),m=setTimeout(function(){m=null,f(n)},50),S(),i(Math.pow(2,.002*Bo())*k.k),u(d,v),c(n)}function g(){var n=ao.mouse(this),t=Math.log(k.k)/Math.LN2;o(this,n,e(n),ao.event.shiftKey?Math.ceil(t)-1:Math.floor(t)+1)}var v,d,y,m,M,x,b,_,w,k={x:0,y:0,k:1},E=[960,500],A=Jo,C=250,z=0,L="mousedown.zoom",q="mousemove.zoom",T="mouseup.zoom",R="touchstart.zoom",D=N(n,"zoomstart","zoom","zoomend");return Wo||(Wo="onwheel"in fo?(Bo=function(){return-ao.event.deltaY*(ao.event.deltaMode?120:1)},"wheel"):"onmousewheel"in fo?(Bo=function(){return ao.event.wheelDelta},"mousewheel"):(Bo=function(){return-ao.event.detail},"MozMousePixelScroll")),n.event=function(n){n.each(function(){var n=D.of(this,arguments),t=k;Hl?ao.select(this).transition().each("start.zoom",function(){k=this.__chart__||{x:0,y:0,k:1},l(n)}).tween("zoom:zoom",function(){var e=E[0],r=E[1],i=d?d[0]:e/2,u=d?d[1]:r/2,o=ao.interpolateZoom([(i-k.x)/k.k,(u-k.y)/k.k,e/k.k],[(i-t.x)/t.k,(u-t.y)/t.k,e/t.k]);return function(t){var r=o(t),a=e/r[2];this.__chart__=k={x:i-r[0]*a,y:u-r[1]*a,k:a},c(n)}}).each("interrupt.zoom",function(){f(n)}).each("end.zoom",function(){f(n)}):(this.__chart__=k,l(n),c(n),f(n))})},n.translate=function(t){return arguments.length?(k={x:+t[0],y:+t[1],k:k.k},a(),n):[k.x,k.y]},n.scale=function(t){return arguments.length?(k={x:k.x,y:k.y,k:null},i(+t),a(),n):k.k},n.scaleExtent=function(t){return arguments.length?(A=null==t?Jo:[+t[0],+t[1]],n):A},n.center=function(t){return arguments.length?(y=t&&[+t[0],+t[1]],n):y},n.size=function(t){return arguments.length?(E=t&&[+t[0],+t[1]],n):E},n.duration=function(t){return arguments.length?(C=+t,n):C},n.x=function(t){return arguments.length?(b=t,x=t.copy(),k={x:0,y:0,k:1},n):b},n.y=function(t){return arguments.length?(w=t,_=t.copy(),k={x:0,y:0,k:1},n):w},ao.rebind(n,D,"on")};var Bo,Wo,Jo=[0,1/0];ao.color=an,an.prototype.toString=function(){return this.rgb()+""},ao.hsl=ln;var Go=ln.prototype=new an;Go.brighter=function(n){return n=Math.pow(.7,arguments.length?n:1),new ln(this.h,this.s,this.l/n)},Go.darker=function(n){return n=Math.pow(.7,arguments.length?n:1),new ln(this.h,this.s,n*this.l)},Go.rgb=function(){return cn(this.h,this.s,this.l)},ao.hcl=fn;var Ko=fn.prototype=new an;Ko.brighter=function(n){return new fn(this.h,this.c,Math.min(100,this.l+Qo*(arguments.length?n:1)))},Ko.darker=function(n){return new fn(this.h,this.c,Math.max(0,this.l-Qo*(arguments.length?n:1)))},Ko.rgb=function(){return sn(this.h,this.c,this.l).rgb()},ao.lab=hn;var Qo=18,na=.95047,ta=1,ea=1.08883,ra=hn.prototype=new an;ra.brighter=function(n){return new hn(Math.min(100,this.l+Qo*(arguments.length?n:1)),this.a,this.b)},ra.darker=function(n){return new hn(Math.max(0,this.l-Qo*(arguments.length?n:1)),this.a,this.b)},ra.rgb=function(){return pn(this.l,this.a,this.b)},ao.rgb=mn;var ia=mn.prototype=new an;ia.brighter=function(n){n=Math.pow(.7,arguments.length?n:1);var t=this.r,e=this.g,r=this.b,i=30;return t||e||r?(t&&i>t&&(t=i),e&&i>e&&(e=i),r&&i>r&&(r=i),new mn(Math.min(255,t/n),Math.min(255,e/n),Math.min(255,r/n))):new mn(i,i,i)},ia.darker=function(n){return n=Math.pow(.7,arguments.length?n:1),new mn(n*this.r,n*this.g,n*this.b)},ia.hsl=function(){return wn(this.r,this.g,this.b)},ia.toString=function(){return"#"+bn(this.r)+bn(this.g)+bn(this.b)};var ua=ao.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});ua.forEach(function(n,t){ua.set(n,Mn(t))}),ao.functor=En,ao.xhr=An(m),ao.dsv=function(n,t){function e(n,e,u){arguments.length<3&&(u=e,e=null);var o=Cn(n,t,null==e?r:i(e),u);return o.row=function(n){return arguments.length?o.response(null==(e=n)?r:i(n)):e},o}function r(n){return e.parse(n.responseText)}function i(n){return function(t){return e.parse(t.responseText,n)}}function u(t){return t.map(o).join(n)}function o(n){return a.test(n)?'"'+n.replace(/\"/g,'""')+'"':n}var a=new RegExp('["'+n+"\n]"),l=n.charCodeAt(0);return e.parse=function(n,t){var r;return e.parseRows(n,function(n,e){if(r)return r(n,e-1);var i=new Function("d","return {"+n.map(function(n,t){return JSON.stringify(n)+": d["+t+"]"}).join(",")+"}");r=t?function(n,e){return t(i(n),e)}:i})},e.parseRows=function(n,t){function e(){if(f>=c)return o;if(i)return i=!1,u;var t=f;if(34===n.charCodeAt(t)){for(var e=t;e++f;){var r=n.charCodeAt(f++),a=1;if(10===r)i=!0;else if(13===r)i=!0,10===n.charCodeAt(f)&&(++f,++a);else if(r!==l)continue;return n.slice(t,f-a)}return n.slice(t)}for(var r,i,u={},o={},a=[],c=n.length,f=0,s=0;(r=e())!==o;){for(var h=[];r!==u&&r!==o;)h.push(r),r=e();t&&null==(h=t(h,s++))||a.push(h)}return a},e.format=function(t){if(Array.isArray(t[0]))return e.formatRows(t);var r=new y,i=[];return t.forEach(function(n){for(var t in n)r.has(t)||i.push(r.add(t))}),[i.map(o).join(n)].concat(t.map(function(t){return i.map(function(n){return o(t[n])}).join(n)})).join("\n")},e.formatRows=function(n){return n.map(u).join("\n")},e},ao.csv=ao.dsv(",","text/csv"),ao.tsv=ao.dsv(" ","text/tab-separated-values");var oa,aa,la,ca,fa=this[x(this,"requestAnimationFrame")]||function(n){setTimeout(n,17)};ao.timer=function(){qn.apply(this,arguments)},ao.timer.flush=function(){Rn(),Dn()},ao.round=function(n,t){return t?Math.round(n*(t=Math.pow(10,t)))/t:Math.round(n)};var sa=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"].map(Un);ao.formatPrefix=function(n,t){var e=0;return(n=+n)&&(0>n&&(n*=-1),t&&(n=ao.round(n,Pn(n,t))),e=1+Math.floor(1e-12+Math.log(n)/Math.LN10),e=Math.max(-24,Math.min(24,3*Math.floor((e-1)/3)))),sa[8+e/3]};var ha=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,pa=ao.map({b:function(n){return n.toString(2)},c:function(n){return String.fromCharCode(n)},o:function(n){return n.toString(8)},x:function(n){return n.toString(16)},X:function(n){return n.toString(16).toUpperCase()},g:function(n,t){return n.toPrecision(t)},e:function(n,t){return n.toExponential(t)},f:function(n,t){return n.toFixed(t)},r:function(n,t){return(n=ao.round(n,Pn(n,t))).toFixed(Math.max(0,Math.min(20,Pn(n*(1+1e-15),t))))}}),ga=ao.time={},va=Date;Hn.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(){da.setUTCDate.apply(this._,arguments)},setDay:function(){da.setUTCDay.apply(this._,arguments)},setFullYear:function(){da.setUTCFullYear.apply(this._,arguments)},setHours:function(){da.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){da.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){da.setUTCMinutes.apply(this._,arguments)},setMonth:function(){da.setUTCMonth.apply(this._,arguments)},setSeconds:function(){da.setUTCSeconds.apply(this._,arguments)},setTime:function(){da.setTime.apply(this._,arguments)}};var da=Date.prototype;ga.year=On(function(n){return n=ga.day(n),n.setMonth(0,1),n},function(n,t){n.setFullYear(n.getFullYear()+t)},function(n){return n.getFullYear()}),ga.years=ga.year.range,ga.years.utc=ga.year.utc.range,ga.day=On(function(n){var t=new va(2e3,0);return t.setFullYear(n.getFullYear(),n.getMonth(),n.getDate()),t},function(n,t){n.setDate(n.getDate()+t)},function(n){return n.getDate()-1}),ga.days=ga.day.range,ga.days.utc=ga.day.utc.range,ga.dayOfYear=function(n){var t=ga.year(n);return Math.floor((n-t-6e4*(n.getTimezoneOffset()-t.getTimezoneOffset()))/864e5)},["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(n,t){t=7-t;var e=ga[n]=On(function(n){return(n=ga.day(n)).setDate(n.getDate()-(n.getDay()+t)%7),n},function(n,t){n.setDate(n.getDate()+7*Math.floor(t))},function(n){var e=ga.year(n).getDay();return Math.floor((ga.dayOfYear(n)+(e+t)%7)/7)-(e!==t)});ga[n+"s"]=e.range,ga[n+"s"].utc=e.utc.range,ga[n+"OfYear"]=function(n){var e=ga.year(n).getDay();return Math.floor((ga.dayOfYear(n)+(e+t)%7)/7)}}),ga.week=ga.sunday,ga.weeks=ga.sunday.range,ga.weeks.utc=ga.sunday.utc.range,ga.weekOfYear=ga.sundayOfYear;var ya={"-":"",_:" ",0:"0"},ma=/^\s*\d+/,Ma=/^%/;ao.locale=function(n){return{numberFormat:jn(n),timeFormat:Yn(n)}};var xa=ao.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"]});ao.format=xa.numberFormat,ao.geo={},ft.prototype={s:0,t:0,add:function(n){st(n,this.t,ba),st(ba.s,this.s,this),this.s?this.t+=ba.t:this.s=ba.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var ba=new ft;ao.geo.stream=function(n,t){n&&_a.hasOwnProperty(n.type)?_a[n.type](n,t):ht(n,t)};var _a={Feature:function(n,t){ht(n.geometry,t)},FeatureCollection:function(n,t){for(var e=n.features,r=-1,i=e.length;++rn?4*Fo+n:n,Na.lineStart=Na.lineEnd=Na.point=b}};ao.geo.bounds=function(){function n(n,t){M.push(x=[f=n,h=n]),s>t&&(s=t),t>p&&(p=t)}function t(t,e){var r=dt([t*Yo,e*Yo]);if(y){var i=mt(y,r),u=[i[1],-i[0],0],o=mt(u,i);bt(o),o=_t(o);var l=t-g,c=l>0?1:-1,v=o[0]*Zo*c,d=xo(l)>180;if(d^(v>c*g&&c*t>v)){var m=o[1]*Zo;m>p&&(p=m)}else if(v=(v+360)%360-180,d^(v>c*g&&c*t>v)){var m=-o[1]*Zo;s>m&&(s=m)}else s>e&&(s=e),e>p&&(p=e);d?g>t?a(f,t)>a(f,h)&&(h=t):a(t,h)>a(f,h)&&(f=t):h>=f?(f>t&&(f=t),t>h&&(h=t)):t>g?a(f,t)>a(f,h)&&(h=t):a(t,h)>a(f,h)&&(f=t)}else n(t,e);y=r,g=t}function e(){b.point=t}function r(){x[0]=f,x[1]=h,b.point=n,y=null}function i(n,e){if(y){var r=n-g;m+=xo(r)>180?r+(r>0?360:-360):r}else v=n,d=e;Na.point(n,e),t(n,e)}function u(){Na.lineStart()}function o(){i(v,d),Na.lineEnd(),xo(m)>Uo&&(f=-(h=180)),x[0]=f,x[1]=h,y=null}function a(n,t){return(t-=n)<0?t+360:t}function l(n,t){return n[0]-t[0]}function c(n,t){return t[0]<=t[1]?t[0]<=n&&n<=t[1]:nka?(f=-(h=180),s=-(p=90)):m>Uo?p=90:-Uo>m&&(s=-90),x[0]=f,x[1]=h}};return function(n){p=h=-(f=s=1/0),M=[],ao.geo.stream(n,b);var t=M.length;if(t){M.sort(l);for(var e,r=1,i=M[0],u=[i];t>r;++r)e=M[r],c(e[0],i)||c(e[1],i)?(a(i[0],e[1])>a(i[0],i[1])&&(i[1]=e[1]),a(e[0],i[1])>a(i[0],i[1])&&(i[0]=e[0])):u.push(i=e);for(var o,e,g=-(1/0),t=u.length-1,r=0,i=u[t];t>=r;i=e,++r)e=u[r],(o=a(i[1],e[0]))>g&&(g=o,f=e[0],h=i[1])}return M=x=null,f===1/0||s===1/0?[[NaN,NaN],[NaN,NaN]]:[[f,s],[h,p]]}}(),ao.geo.centroid=function(n){Ea=Aa=Ca=za=La=qa=Ta=Ra=Da=Pa=Ua=0,ao.geo.stream(n,ja);var t=Da,e=Pa,r=Ua,i=t*t+e*e+r*r;return jo>i&&(t=qa,e=Ta,r=Ra,Uo>Aa&&(t=Ca,e=za,r=La),i=t*t+e*e+r*r,jo>i)?[NaN,NaN]:[Math.atan2(e,t)*Zo,tn(r/Math.sqrt(i))*Zo]};var Ea,Aa,Ca,za,La,qa,Ta,Ra,Da,Pa,Ua,ja={sphere:b,point:St,lineStart:Nt,lineEnd:Et,polygonStart:function(){ja.lineStart=At},polygonEnd:function(){ja.lineStart=Nt}},Fa=Rt(zt,jt,Ht,[-Fo,-Fo/2]),Ha=1e9;ao.geo.clipExtent=function(){var n,t,e,r,i,u,o={stream:function(n){return i&&(i.valid=!1),i=u(n),i.valid=!0,i},extent:function(a){return arguments.length?(u=Zt(n=+a[0][0],t=+a[0][1],e=+a[1][0],r=+a[1][1]),i&&(i.valid=!1,i=null),o):[[n,t],[e,r]]}};return o.extent([[0,0],[960,500]])},(ao.geo.conicEqualArea=function(){return Vt(Xt)}).raw=Xt,ao.geo.albers=function(){return ao.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},ao.geo.albersUsa=function(){function n(n){var u=n[0],o=n[1];return t=null,e(u,o),t||(r(u,o),t)||i(u,o),t}var t,e,r,i,u=ao.geo.albers(),o=ao.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),a=ao.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(n,e){t=[n,e]}};return n.invert=function(n){var t=u.scale(),e=u.translate(),r=(n[0]-e[0])/t,i=(n[1]-e[1])/t;return(i>=.12&&.234>i&&r>=-.425&&-.214>r?o:i>=.166&&.234>i&&r>=-.214&&-.115>r?a:u).invert(n)},n.stream=function(n){var t=u.stream(n),e=o.stream(n),r=a.stream(n);return{point:function(n,i){t.point(n,i),e.point(n,i),r.point(n,i)},sphere:function(){t.sphere(),e.sphere(),r.sphere()},lineStart:function(){t.lineStart(),e.lineStart(),r.lineStart()},lineEnd:function(){t.lineEnd(),e.lineEnd(),r.lineEnd()},polygonStart:function(){t.polygonStart(),e.polygonStart(),r.polygonStart()},polygonEnd:function(){t.polygonEnd(),e.polygonEnd(),r.polygonEnd()}}},n.precision=function(t){return arguments.length?(u.precision(t),o.precision(t),a.precision(t),n):u.precision()},n.scale=function(t){return arguments.length?(u.scale(t),o.scale(.35*t),a.scale(t),n.translate(u.translate())):u.scale()},n.translate=function(t){if(!arguments.length)return u.translate();var c=u.scale(),f=+t[0],s=+t[1];return e=u.translate(t).clipExtent([[f-.455*c,s-.238*c],[f+.455*c,s+.238*c]]).stream(l).point,r=o.translate([f-.307*c,s+.201*c]).clipExtent([[f-.425*c+Uo,s+.12*c+Uo],[f-.214*c-Uo,s+.234*c-Uo]]).stream(l).point,i=a.translate([f-.205*c,s+.212*c]).clipExtent([[f-.214*c+Uo,s+.166*c+Uo],[f-.115*c-Uo,s+.234*c-Uo]]).stream(l).point,n},n.scale(1070)};var Oa,Ia,Ya,Za,Va,Xa,$a={point:b,lineStart:b,lineEnd:b,polygonStart:function(){Ia=0,$a.lineStart=$t},polygonEnd:function(){$a.lineStart=$a.lineEnd=$a.point=b,Oa+=xo(Ia/2)}},Ba={point:Bt,lineStart:b,lineEnd:b,polygonStart:b,polygonEnd:b},Wa={point:Gt,lineStart:Kt,lineEnd:Qt,polygonStart:function(){Wa.lineStart=ne},polygonEnd:function(){Wa.point=Gt,Wa.lineStart=Kt,Wa.lineEnd=Qt}};ao.geo.path=function(){function n(n){return n&&("function"==typeof a&&u.pointRadius(+a.apply(this,arguments)),o&&o.valid||(o=i(u)),ao.geo.stream(n,o)),u.result()}function t(){return o=null,n}var e,r,i,u,o,a=4.5;return n.area=function(n){return Oa=0,ao.geo.stream(n,i($a)),Oa},n.centroid=function(n){return Ca=za=La=qa=Ta=Ra=Da=Pa=Ua=0,ao.geo.stream(n,i(Wa)),Ua?[Da/Ua,Pa/Ua]:Ra?[qa/Ra,Ta/Ra]:La?[Ca/La,za/La]:[NaN,NaN]},n.bounds=function(n){return Va=Xa=-(Ya=Za=1/0),ao.geo.stream(n,i(Ba)),[[Ya,Za],[Va,Xa]]},n.projection=function(n){return arguments.length?(i=(e=n)?n.stream||re(n):m,t()):e},n.context=function(n){return arguments.length?(u=null==(r=n)?new Wt:new te(n),"function"!=typeof a&&u.pointRadius(a),t()):r},n.pointRadius=function(t){return arguments.length?(a="function"==typeof t?t:(u.pointRadius(+t),+t),n):a},n.projection(ao.geo.albersUsa()).context(null)},ao.geo.transform=function(n){return{stream:function(t){var e=new ie(t);for(var r in n)e[r]=n[r];return e}}},ie.prototype={point:function(n,t){this.stream.point(n,t)},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()}},ao.geo.projection=oe,ao.geo.projectionMutator=ae,(ao.geo.equirectangular=function(){return oe(ce)}).raw=ce.invert=ce,ao.geo.rotation=function(n){function t(t){return t=n(t[0]*Yo,t[1]*Yo),t[0]*=Zo,t[1]*=Zo,t}return n=se(n[0]%360*Yo,n[1]*Yo,n.length>2?n[2]*Yo:0),t.invert=function(t){return t=n.invert(t[0]*Yo,t[1]*Yo),t[0]*=Zo,t[1]*=Zo,t},t},fe.invert=ce,ao.geo.circle=function(){function n(){var n="function"==typeof r?r.apply(this,arguments):r,t=se(-n[0]*Yo,-n[1]*Yo,0).invert,i=[];return e(null,null,1,{point:function(n,e){i.push(n=t(n,e)),n[0]*=Zo,n[1]*=Zo}}),{type:"Polygon",coordinates:[i]}}var t,e,r=[0,0],i=6;return n.origin=function(t){return arguments.length?(r=t,n):r},n.angle=function(r){return arguments.length?(e=ve((t=+r)*Yo,i*Yo),n):t},n.precision=function(r){return arguments.length?(e=ve(t*Yo,(i=+r)*Yo),n):i},n.angle(90)},ao.geo.distance=function(n,t){var e,r=(t[0]-n[0])*Yo,i=n[1]*Yo,u=t[1]*Yo,o=Math.sin(r),a=Math.cos(r),l=Math.sin(i),c=Math.cos(i),f=Math.sin(u),s=Math.cos(u);return Math.atan2(Math.sqrt((e=s*o)*e+(e=c*f-l*s*a)*e),l*f+c*s*a)},ao.geo.graticule=function(){function n(){return{type:"MultiLineString",coordinates:t()}}function t(){return ao.range(Math.ceil(u/d)*d,i,d).map(h).concat(ao.range(Math.ceil(c/y)*y,l,y).map(p)).concat(ao.range(Math.ceil(r/g)*g,e,g).filter(function(n){return xo(n%d)>Uo}).map(f)).concat(ao.range(Math.ceil(a/v)*v,o,v).filter(function(n){return xo(n%y)>Uo}).map(s))}var e,r,i,u,o,a,l,c,f,s,h,p,g=10,v=g,d=90,y=360,m=2.5;return n.lines=function(){return t().map(function(n){return{type:"LineString",coordinates:n}})},n.outline=function(){return{type:"Polygon",coordinates:[h(u).concat(p(l).slice(1),h(i).reverse().slice(1),p(c).reverse().slice(1))]}},n.extent=function(t){return arguments.length?n.majorExtent(t).minorExtent(t):n.minorExtent()},n.majorExtent=function(t){return arguments.length?(u=+t[0][0],i=+t[1][0],c=+t[0][1],l=+t[1][1],u>i&&(t=u,u=i,i=t),c>l&&(t=c,c=l,l=t),n.precision(m)):[[u,c],[i,l]]},n.minorExtent=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],a=+t[0][1],o=+t[1][1],r>e&&(t=r,r=e,e=t),a>o&&(t=a,a=o,o=t),n.precision(m)):[[r,a],[e,o]]},n.step=function(t){return arguments.length?n.majorStep(t).minorStep(t):n.minorStep()},n.majorStep=function(t){return arguments.length?(d=+t[0],y=+t[1],n):[d,y]},n.minorStep=function(t){return arguments.length?(g=+t[0],v=+t[1],n):[g,v]},n.precision=function(t){return arguments.length?(m=+t,f=ye(a,o,90),s=me(r,e,m),h=ye(c,l,90),p=me(u,i,m),n):m},n.majorExtent([[-180,-90+Uo],[180,90-Uo]]).minorExtent([[-180,-80-Uo],[180,80+Uo]])},ao.geo.greatArc=function(){function n(){return{type:"LineString",coordinates:[t||r.apply(this,arguments),e||i.apply(this,arguments)]}}var t,e,r=Me,i=xe;return n.distance=function(){return ao.geo.distance(t||r.apply(this,arguments),e||i.apply(this,arguments))},n.source=function(e){return arguments.length?(r=e,t="function"==typeof e?null:e,n):r},n.target=function(t){return arguments.length?(i=t,e="function"==typeof t?null:t,n):i},n.precision=function(){return arguments.length?n:0},n},ao.geo.interpolate=function(n,t){return be(n[0]*Yo,n[1]*Yo,t[0]*Yo,t[1]*Yo)},ao.geo.length=function(n){return Ja=0,ao.geo.stream(n,Ga),Ja};var Ja,Ga={sphere:b,point:b,lineStart:_e,lineEnd:b,polygonStart:b,polygonEnd:b},Ka=we(function(n){return Math.sqrt(2/(1+n))},function(n){return 2*Math.asin(n/2)});(ao.geo.azimuthalEqualArea=function(){return oe(Ka)}).raw=Ka;var Qa=we(function(n){var t=Math.acos(n);return t&&t/Math.sin(t)},m);(ao.geo.azimuthalEquidistant=function(){return oe(Qa)}).raw=Qa,(ao.geo.conicConformal=function(){return Vt(Se)}).raw=Se,(ao.geo.conicEquidistant=function(){return Vt(ke)}).raw=ke;var nl=we(function(n){return 1/n},Math.atan);(ao.geo.gnomonic=function(){return oe(nl)}).raw=nl,Ne.invert=function(n,t){return[n,2*Math.atan(Math.exp(t))-Io]},(ao.geo.mercator=function(){return Ee(Ne)}).raw=Ne;var tl=we(function(){return 1},Math.asin);(ao.geo.orthographic=function(){return oe(tl)}).raw=tl;var el=we(function(n){return 1/(1+n)},function(n){return 2*Math.atan(n)});(ao.geo.stereographic=function(){return oe(el)}).raw=el,Ae.invert=function(n,t){return[-t,2*Math.atan(Math.exp(n))-Io]},(ao.geo.transverseMercator=function(){var n=Ee(Ae),t=n.center,e=n.rotate;return n.center=function(n){return n?t([-n[1],n[0]]):(n=t(),[n[1],-n[0]])},n.rotate=function(n){return n?e([n[0],n[1],n.length>2?n[2]+90:90]):(n=e(),[n[0],n[1],n[2]-90])},e([0,0,90])}).raw=Ae,ao.geom={},ao.geom.hull=function(n){function t(n){if(n.length<3)return[];var t,i=En(e),u=En(r),o=n.length,a=[],l=[];for(t=0;o>t;t++)a.push([+i.call(this,n[t],t),+u.call(this,n[t],t),t]);for(a.sort(qe),t=0;o>t;t++)l.push([a[t][0],-a[t][1]]);var c=Le(a),f=Le(l),s=f[0]===c[0],h=f[f.length-1]===c[c.length-1],p=[];for(t=c.length-1;t>=0;--t)p.push(n[a[c[t]][2]]);for(t=+s;t=r&&c.x<=u&&c.y>=i&&c.y<=o?[[r,o],[u,o],[u,i],[r,i]]:[];f.point=n[a]}),t}function e(n){return n.map(function(n,t){return{x:Math.round(u(n,t)/Uo)*Uo,y:Math.round(o(n,t)/Uo)*Uo,i:t}})}var r=Ce,i=ze,u=r,o=i,a=sl;return n?t(n):(t.links=function(n){return ar(e(n)).edges.filter(function(n){return n.l&&n.r}).map(function(t){return{source:n[t.l.i],target:n[t.r.i]}})},t.triangles=function(n){var t=[];return ar(e(n)).cells.forEach(function(e,r){for(var i,u,o=e.site,a=e.edges.sort(Ve),l=-1,c=a.length,f=a[c-1].edge,s=f.l===o?f.r:f.l;++l=c,h=r>=f,p=h<<1|s;n.leaf=!1,n=n.nodes[p]||(n.nodes[p]=hr()),s?i=c:a=c,h?o=f:l=f,u(n,t,e,r,i,o,a,l)}var f,s,h,p,g,v,d,y,m,M=En(a),x=En(l);if(null!=t)v=t,d=e,y=r,m=i;else if(y=m=-(v=d=1/0),s=[],h=[],g=n.length,o)for(p=0;g>p;++p)f=n[p],f.xy&&(y=f.x),f.y>m&&(m=f.y),s.push(f.x),h.push(f.y);else for(p=0;g>p;++p){var b=+M(f=n[p],p),_=+x(f,p);v>b&&(v=b),d>_&&(d=_),b>y&&(y=b),_>m&&(m=_),s.push(b),h.push(_)}var w=y-v,S=m-d;w>S?m=d+w:y=v+S;var k=hr();if(k.add=function(n){u(k,n,+M(n,++p),+x(n,p),v,d,y,m)},k.visit=function(n){pr(n,k,v,d,y,m)},k.find=function(n){return gr(k,n[0],n[1],v,d,y,m)},p=-1,null==t){for(;++p=0?n.slice(0,t):n,r=t>=0?n.slice(t+1):"in";return e=vl.get(e)||gl,r=dl.get(r)||m,br(r(e.apply(null,lo.call(arguments,1))))},ao.interpolateHcl=Rr,ao.interpolateHsl=Dr,ao.interpolateLab=Pr,ao.interpolateRound=Ur,ao.transform=function(n){var t=fo.createElementNS(ao.ns.prefix.svg,"g");return(ao.transform=function(n){if(null!=n){t.setAttribute("transform",n);var e=t.transform.baseVal.consolidate()}return new jr(e?e.matrix:yl)})(n)},jr.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var yl={a:1,b:0,c:0,d:1,e:0,f:0};ao.interpolateTransform=$r,ao.layout={},ao.layout.bundle=function(){return function(n){for(var t=[],e=-1,r=n.length;++ea*a/y){if(v>l){var c=t.charge/l;n.px-=u*c,n.py-=o*c}return!0}if(t.point&&l&&v>l){var c=t.pointCharge/l;n.px-=u*c,n.py-=o*c}}return!t.charge}}function t(n){n.px=ao.event.x,n.py=ao.event.y,l.resume()}var e,r,i,u,o,a,l={},c=ao.dispatch("start","tick","end"),f=[1,1],s=.9,h=ml,p=Ml,g=-30,v=xl,d=.1,y=.64,M=[],x=[];return l.tick=function(){if((i*=.99)<.005)return e=null,c.end({type:"end",alpha:i=0}),!0;var t,r,l,h,p,v,y,m,b,_=M.length,w=x.length;for(r=0;w>r;++r)l=x[r],h=l.source,p=l.target,m=p.x-h.x,b=p.y-h.y,(v=m*m+b*b)&&(v=i*o[r]*((v=Math.sqrt(v))-u[r])/v,m*=v,b*=v,p.x-=m*(y=h.weight+p.weight?h.weight/(h.weight+p.weight):.5),p.y-=b*y,h.x+=m*(y=1-y),h.y+=b*y);if((y=i*d)&&(m=f[0]/2,b=f[1]/2,r=-1,y))for(;++r<_;)l=M[r],l.x+=(m-l.x)*y,l.y+=(b-l.y)*y;if(g)for(ri(t=ao.geom.quadtree(M),i,a),r=-1;++r<_;)(l=M[r]).fixed||t.visit(n(l));for(r=-1;++r<_;)l=M[r],l.fixed?(l.x=l.px,l.y=l.py):(l.x-=(l.px-(l.px=l.x))*s,l.y-=(l.py-(l.py=l.y))*s);c.tick({type:"tick",alpha:i})},l.nodes=function(n){return arguments.length?(M=n,l):M},l.links=function(n){return arguments.length?(x=n,l):x},l.size=function(n){return arguments.length?(f=n,l):f},l.linkDistance=function(n){return arguments.length?(h="function"==typeof n?n:+n,l):h},l.distance=l.linkDistance,l.linkStrength=function(n){return arguments.length?(p="function"==typeof n?n:+n,l):p},l.friction=function(n){return arguments.length?(s=+n,l):s},l.charge=function(n){return arguments.length?(g="function"==typeof n?n:+n,l):g},l.chargeDistance=function(n){return arguments.length?(v=n*n,l):Math.sqrt(v)},l.gravity=function(n){return arguments.length?(d=+n,l):d},l.theta=function(n){return arguments.length?(y=n*n,l):Math.sqrt(y)},l.alpha=function(n){return arguments.length?(n=+n,i?n>0?i=n:(e.c=null,e.t=NaN,e=null,c.end({type:"end",alpha:i=0})):n>0&&(c.start({type:"start",alpha:i=n}),e=qn(l.tick)),l):i},l.start=function(){function n(n,r){if(!e){for(e=new Array(i),l=0;i>l;++l)e[l]=[];for(l=0;c>l;++l){var u=x[l];e[u.source.index].push(u.target),e[u.target.index].push(u.source)}}for(var o,a=e[t],l=-1,f=a.length;++lt;++t)(r=M[t]).index=t,r.weight=0;for(t=0;c>t;++t)r=x[t],"number"==typeof r.source&&(r.source=M[r.source]),"number"==typeof r.target&&(r.target=M[r.target]),++r.source.weight,++r.target.weight;for(t=0;i>t;++t)r=M[t],isNaN(r.x)&&(r.x=n("x",s)),isNaN(r.y)&&(r.y=n("y",v)),isNaN(r.px)&&(r.px=r.x),isNaN(r.py)&&(r.py=r.y);if(u=[],"function"==typeof h)for(t=0;c>t;++t)u[t]=+h.call(this,x[t],t);else for(t=0;c>t;++t)u[t]=h;if(o=[],"function"==typeof p)for(t=0;c>t;++t)o[t]=+p.call(this,x[t],t);else for(t=0;c>t;++t)o[t]=p;if(a=[],"function"==typeof g)for(t=0;i>t;++t)a[t]=+g.call(this,M[t],t);else for(t=0;i>t;++t)a[t]=g;return l.resume()},l.resume=function(){return l.alpha(.1)},l.stop=function(){return l.alpha(0)},l.drag=function(){return r||(r=ao.behavior.drag().origin(m).on("dragstart.force",Qr).on("drag.force",t).on("dragend.force",ni)),arguments.length?void this.on("mouseover.force",ti).on("mouseout.force",ei).call(r):r},ao.rebind(l,c,"on")};var ml=20,Ml=1,xl=1/0;ao.layout.hierarchy=function(){function n(i){var u,o=[i],a=[];for(i.depth=0;null!=(u=o.pop());)if(a.push(u),(c=e.call(n,u,u.depth))&&(l=c.length)){for(var l,c,f;--l>=0;)o.push(f=c[l]),f.parent=u,f.depth=u.depth+1;r&&(u.value=0),u.children=c}else r&&(u.value=+r.call(n,u,u.depth)||0),delete u.children;return oi(i,function(n){var e,i;t&&(e=n.children)&&e.sort(t),r&&(i=n.parent)&&(i.value+=n.value)}),a}var t=ci,e=ai,r=li;return n.sort=function(e){return arguments.length?(t=e,n):t},n.children=function(t){return arguments.length?(e=t,n):e},n.value=function(t){return arguments.length?(r=t,n):r},n.revalue=function(t){return r&&(ui(t,function(n){n.children&&(n.value=0)}),oi(t,function(t){var e;t.children||(t.value=+r.call(n,t,t.depth)||0),(e=t.parent)&&(e.value+=t.value)})),t},n},ao.layout.partition=function(){function n(t,e,r,i){var u=t.children;if(t.x=e,t.y=t.depth*i,t.dx=r,t.dy=i,u&&(o=u.length)){var o,a,l,c=-1;for(r=t.value?r/t.value:0;++cs?-1:1),g=ao.sum(c),v=g?(s-l*p)/g:0,d=ao.range(l),y=[];return null!=e&&d.sort(e===bl?function(n,t){return c[t]-c[n]}:function(n,t){return e(o[n],o[t])}),d.forEach(function(n){y[n]={data:o[n],value:a=c[n],startAngle:f,endAngle:f+=a*v+p,padAngle:h}}),y}var t=Number,e=bl,r=0,i=Ho,u=0;return n.value=function(e){return arguments.length?(t=e,n):t},n.sort=function(t){return arguments.length?(e=t,n):e},n.startAngle=function(t){return arguments.length?(r=t,n):r},n.endAngle=function(t){return arguments.length?(i=t,n):i},n.padAngle=function(t){return arguments.length?(u=t,n):u},n};var bl={};ao.layout.stack=function(){function n(a,l){if(!(h=a.length))return a;var c=a.map(function(e,r){return t.call(n,e,r)}),f=c.map(function(t){return t.map(function(t,e){return[u.call(n,t,e),o.call(n,t,e)]})}),s=e.call(n,f,l);c=ao.permute(c,s),f=ao.permute(f,s);var h,p,g,v,d=r.call(n,f,l),y=c[0].length;for(g=0;y>g;++g)for(i.call(n,c[0][g],v=d[g],f[0][g][1]),p=1;h>p;++p)i.call(n,c[p][g],v+=f[p-1][g][1],f[p][g][1]);return a}var t=m,e=gi,r=vi,i=pi,u=si,o=hi;return n.values=function(e){return arguments.length?(t=e,n):t},n.order=function(t){return arguments.length?(e="function"==typeof t?t:_l.get(t)||gi,n):e},n.offset=function(t){return arguments.length?(r="function"==typeof t?t:wl.get(t)||vi,n):r},n.x=function(t){return arguments.length?(u=t,n):u},n.y=function(t){return arguments.length?(o=t,n):o},n.out=function(t){return arguments.length?(i=t,n):i},n};var _l=ao.map({"inside-out":function(n){var t,e,r=n.length,i=n.map(di),u=n.map(yi),o=ao.range(r).sort(function(n,t){return i[n]-i[t]}),a=0,l=0,c=[],f=[];for(t=0;r>t;++t)e=o[t],l>a?(a+=u[e],c.push(e)):(l+=u[e],f.push(e));return f.reverse().concat(c)},reverse:function(n){return ao.range(n.length).reverse()},"default":gi}),wl=ao.map({silhouette:function(n){var t,e,r,i=n.length,u=n[0].length,o=[],a=0,l=[];for(e=0;u>e;++e){for(t=0,r=0;i>t;t++)r+=n[t][e][1];r>a&&(a=r),o.push(r)}for(e=0;u>e;++e)l[e]=(a-o[e])/2;return l},wiggle:function(n){var t,e,r,i,u,o,a,l,c,f=n.length,s=n[0],h=s.length,p=[];for(p[0]=l=c=0,e=1;h>e;++e){for(t=0,i=0;f>t;++t)i+=n[t][e][1];for(t=0,u=0,a=s[e][0]-s[e-1][0];f>t;++t){for(r=0,o=(n[t][e][1]-n[t][e-1][1])/(2*a);t>r;++r)o+=(n[r][e][1]-n[r][e-1][1])/a;u+=o*n[t][e][1]}p[e]=l-=i?u/i*a:0,c>l&&(c=l)}for(e=0;h>e;++e)p[e]-=c;return p},expand:function(n){var t,e,r,i=n.length,u=n[0].length,o=1/i,a=[];for(e=0;u>e;++e){for(t=0,r=0;i>t;t++)r+=n[t][e][1];if(r)for(t=0;i>t;t++)n[t][e][1]/=r;else for(t=0;i>t;t++)n[t][e][1]=o}for(e=0;u>e;++e)a[e]=0;return a},zero:vi});ao.layout.histogram=function(){function n(n,u){for(var o,a,l=[],c=n.map(e,this),f=r.call(this,c,u),s=i.call(this,f,c,u),u=-1,h=c.length,p=s.length-1,g=t?1:1/h;++u0)for(u=-1;++u=f[0]&&a<=f[1]&&(o=l[ao.bisect(s,a,1,p)-1],o.y+=g,o.push(n[u]));return l}var t=!0,e=Number,r=bi,i=Mi;return n.value=function(t){return arguments.length?(e=t,n):e},n.range=function(t){return arguments.length?(r=En(t),n):r},n.bins=function(t){return arguments.length?(i="number"==typeof t?function(n){return xi(n,t)}:En(t),n):i},n.frequency=function(e){return arguments.length?(t=!!e,n):t},n},ao.layout.pack=function(){function n(n,u){var o=e.call(this,n,u),a=o[0],l=i[0],c=i[1],f=null==t?Math.sqrt:"function"==typeof t?t:function(){return t};if(a.x=a.y=0,oi(a,function(n){n.r=+f(n.value)}),oi(a,Ni),r){var s=r*(t?1:Math.max(2*a.r/l,2*a.r/c))/2;oi(a,function(n){n.r+=s}),oi(a,Ni),oi(a,function(n){n.r-=s})}return Ci(a,l/2,c/2,t?1:1/Math.max(2*a.r/l,2*a.r/c)),o}var t,e=ao.layout.hierarchy().sort(_i),r=0,i=[1,1];return n.size=function(t){return arguments.length?(i=t,n):i},n.radius=function(e){return arguments.length?(t=null==e||"function"==typeof e?e:+e,n):t},n.padding=function(t){return arguments.length?(r=+t,n):r},ii(n,e)},ao.layout.tree=function(){function n(n,i){var f=o.call(this,n,i),s=f[0],h=t(s);if(oi(h,e),h.parent.m=-h.z,ui(h,r),c)ui(s,u);else{var p=s,g=s,v=s;ui(s,function(n){n.xg.x&&(g=n),n.depth>v.depth&&(v=n)});var d=a(p,g)/2-p.x,y=l[0]/(g.x+a(g,p)/2+d),m=l[1]/(v.depth||1);ui(s,function(n){n.x=(n.x+d)*y,n.y=n.depth*m})}return f}function t(n){for(var t,e={A:null,children:[n]},r=[e];null!=(t=r.pop());)for(var i,u=t.children,o=0,a=u.length;a>o;++o)r.push((u[o]=i={_:u[o],parent:t,children:(i=u[o].children)&&i.slice()||[],A:null,a:null,z:0,m:0,c:0,s:0,t:null,i:o}).a=i);return e.children[0]}function e(n){var t=n.children,e=n.parent.children,r=n.i?e[n.i-1]:null;if(t.length){Di(n);var u=(t[0].z+t[t.length-1].z)/2;r?(n.z=r.z+a(n._,r._),n.m=n.z-u):n.z=u}else r&&(n.z=r.z+a(n._,r._));n.parent.A=i(n,r,n.parent.A||e[0])}function r(n){n._.x=n.z+n.parent.m,n.m+=n.parent.m}function i(n,t,e){if(t){for(var r,i=n,u=n,o=t,l=i.parent.children[0],c=i.m,f=u.m,s=o.m,h=l.m;o=Ti(o),i=qi(i),o&&i;)l=qi(l),u=Ti(u),u.a=n,r=o.z+s-i.z-c+a(o._,i._),r>0&&(Ri(Pi(o,n,e),n,r),c+=r,f+=r),s+=o.m,c+=i.m,h+=l.m,f+=u.m;o&&!Ti(u)&&(u.t=o,u.m+=s-f),i&&!qi(l)&&(l.t=i,l.m+=c-h,e=n)}return e}function u(n){n.x*=l[0],n.y=n.depth*l[1]}var o=ao.layout.hierarchy().sort(null).value(null),a=Li,l=[1,1],c=null;return n.separation=function(t){return arguments.length?(a=t,n):a},n.size=function(t){return arguments.length?(c=null==(l=t)?u:null,n):c?null:l},n.nodeSize=function(t){return arguments.length?(c=null==(l=t)?null:u,n):c?l:null},ii(n,o)},ao.layout.cluster=function(){function n(n,u){var o,a=t.call(this,n,u),l=a[0],c=0;oi(l,function(n){var t=n.children;t&&t.length?(n.x=ji(t),n.y=Ui(t)):(n.x=o?c+=e(n,o):0,n.y=0,o=n)});var f=Fi(l),s=Hi(l),h=f.x-e(f,s)/2,p=s.x+e(s,f)/2;return oi(l,i?function(n){n.x=(n.x-l.x)*r[0],n.y=(l.y-n.y)*r[1]}:function(n){n.x=(n.x-h)/(p-h)*r[0],n.y=(1-(l.y?n.y/l.y:1))*r[1]}),a}var t=ao.layout.hierarchy().sort(null).value(null),e=Li,r=[1,1],i=!1;return n.separation=function(t){return arguments.length?(e=t,n):e},n.size=function(t){return arguments.length?(i=null==(r=t),n):i?null:r},n.nodeSize=function(t){return arguments.length?(i=null!=(r=t),n):i?r:null},ii(n,t)},ao.layout.treemap=function(){function n(n,t){for(var e,r,i=-1,u=n.length;++it?0:t),e.area=isNaN(r)||0>=r?0:r}function t(e){var u=e.children;if(u&&u.length){var o,a,l,c=s(e),f=[],h=u.slice(),g=1/0,v="slice"===p?c.dx:"dice"===p?c.dy:"slice-dice"===p?1&e.depth?c.dy:c.dx:Math.min(c.dx,c.dy);for(n(h,c.dx*c.dy/e.value),f.area=0;(l=h.length)>0;)f.push(o=h[l-1]),f.area+=o.area,"squarify"!==p||(a=r(f,v))<=g?(h.pop(),g=a):(f.area-=f.pop().area,i(f,v,c,!1),v=Math.min(c.dx,c.dy),f.length=f.area=0,g=1/0);f.length&&(i(f,v,c,!0),f.length=f.area=0),u.forEach(t)}}function e(t){var r=t.children;if(r&&r.length){var u,o=s(t),a=r.slice(),l=[];for(n(a,o.dx*o.dy/t.value),l.area=0;u=a.pop();)l.push(u),l.area+=u.area,null!=u.z&&(i(l,u.z?o.dx:o.dy,o,!a.length),l.length=l.area=0);r.forEach(e)}}function r(n,t){for(var e,r=n.area,i=0,u=1/0,o=-1,a=n.length;++oe&&(u=e),e>i&&(i=e));return r*=r,t*=t,r?Math.max(t*i*g/r,r/(t*u*g)):1/0}function i(n,t,e,r){var i,u=-1,o=n.length,a=e.x,c=e.y,f=t?l(n.area/t):0; +if(t==e.dx){for((r||f>e.dy)&&(f=e.dy);++ue.dx)&&(f=e.dx);++ue&&(t=1),1>e&&(n=0),function(){var e,r,i;do e=2*Math.random()-1,r=2*Math.random()-1,i=e*e+r*r;while(!i||i>1);return n+t*e*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var n=ao.random.normal.apply(ao,arguments);return function(){return Math.exp(n())}},bates:function(n){var t=ao.random.irwinHall(n);return function(){return t()/n}},irwinHall:function(n){return function(){for(var t=0,e=0;n>e;e++)t+=Math.random();return t}}},ao.scale={};var Sl={floor:m,ceil:m};ao.scale.linear=function(){return Wi([0,1],[0,1],Mr,!1)};var kl={s:1,g:1,p:1,r:1,e:1};ao.scale.log=function(){return ru(ao.scale.linear().domain([0,1]),10,!0,[1,10])};var Nl=ao.format(".0e"),El={floor:function(n){return-Math.ceil(-n)},ceil:function(n){return-Math.floor(-n)}};ao.scale.pow=function(){return iu(ao.scale.linear(),1,[0,1])},ao.scale.sqrt=function(){return ao.scale.pow().exponent(.5)},ao.scale.ordinal=function(){return ou([],{t:"range",a:[[]]})},ao.scale.category10=function(){return ao.scale.ordinal().range(Al)},ao.scale.category20=function(){return ao.scale.ordinal().range(Cl)},ao.scale.category20b=function(){return ao.scale.ordinal().range(zl)},ao.scale.category20c=function(){return ao.scale.ordinal().range(Ll)};var Al=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(xn),Cl=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(xn),zl=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(xn),Ll=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(xn);ao.scale.quantile=function(){return au([],[])},ao.scale.quantize=function(){return lu(0,1,[0,1])},ao.scale.threshold=function(){return cu([.5],[0,1])},ao.scale.identity=function(){return fu([0,1])},ao.svg={},ao.svg.arc=function(){function n(){var n=Math.max(0,+e.apply(this,arguments)),c=Math.max(0,+r.apply(this,arguments)),f=o.apply(this,arguments)-Io,s=a.apply(this,arguments)-Io,h=Math.abs(s-f),p=f>s?0:1;if(n>c&&(g=c,c=n,n=g),h>=Oo)return t(c,p)+(n?t(n,1-p):"")+"Z";var g,v,d,y,m,M,x,b,_,w,S,k,N=0,E=0,A=[];if((y=(+l.apply(this,arguments)||0)/2)&&(d=u===ql?Math.sqrt(n*n+c*c):+u.apply(this,arguments),p||(E*=-1),c&&(E=tn(d/c*Math.sin(y))),n&&(N=tn(d/n*Math.sin(y)))),c){m=c*Math.cos(f+E),M=c*Math.sin(f+E),x=c*Math.cos(s-E),b=c*Math.sin(s-E);var C=Math.abs(s-f-2*E)<=Fo?0:1;if(E&&yu(m,M,x,b)===p^C){var z=(f+s)/2;m=c*Math.cos(z),M=c*Math.sin(z),x=b=null}}else m=M=0;if(n){_=n*Math.cos(s-N),w=n*Math.sin(s-N),S=n*Math.cos(f+N),k=n*Math.sin(f+N);var L=Math.abs(f-s+2*N)<=Fo?0:1;if(N&&yu(_,w,S,k)===1-p^L){var q=(f+s)/2;_=n*Math.cos(q),w=n*Math.sin(q),S=k=null}}else _=w=0;if(h>Uo&&(g=Math.min(Math.abs(c-n)/2,+i.apply(this,arguments)))>.001){v=c>n^p?0:1;var T=g,R=g;if(Fo>h){var D=null==S?[_,w]:null==x?[m,M]:Re([m,M],[S,k],[x,b],[_,w]),P=m-D[0],U=M-D[1],j=x-D[0],F=b-D[1],H=1/Math.sin(Math.acos((P*j+U*F)/(Math.sqrt(P*P+U*U)*Math.sqrt(j*j+F*F)))/2),O=Math.sqrt(D[0]*D[0]+D[1]*D[1]);R=Math.min(g,(n-O)/(H-1)),T=Math.min(g,(c-O)/(H+1))}if(null!=x){var I=mu(null==S?[_,w]:[S,k],[m,M],c,T,p),Y=mu([x,b],[_,w],c,T,p);g===T?A.push("M",I[0],"A",T,",",T," 0 0,",v," ",I[1],"A",c,",",c," 0 ",1-p^yu(I[1][0],I[1][1],Y[1][0],Y[1][1]),",",p," ",Y[1],"A",T,",",T," 0 0,",v," ",Y[0]):A.push("M",I[0],"A",T,",",T," 0 1,",v," ",Y[0])}else A.push("M",m,",",M);if(null!=S){var Z=mu([m,M],[S,k],n,-R,p),V=mu([_,w],null==x?[m,M]:[x,b],n,-R,p);g===R?A.push("L",V[0],"A",R,",",R," 0 0,",v," ",V[1],"A",n,",",n," 0 ",p^yu(V[1][0],V[1][1],Z[1][0],Z[1][1]),",",1-p," ",Z[1],"A",R,",",R," 0 0,",v," ",Z[0]):A.push("L",V[0],"A",R,",",R," 0 0,",v," ",Z[0])}else A.push("L",_,",",w)}else A.push("M",m,",",M),null!=x&&A.push("A",c,",",c," 0 ",C,",",p," ",x,",",b),A.push("L",_,",",w),null!=S&&A.push("A",n,",",n," 0 ",L,",",1-p," ",S,",",k);return A.push("Z"),A.join("")}function t(n,t){return"M0,"+n+"A"+n+","+n+" 0 1,"+t+" 0,"+-n+"A"+n+","+n+" 0 1,"+t+" 0,"+n}var e=hu,r=pu,i=su,u=ql,o=gu,a=vu,l=du;return n.innerRadius=function(t){return arguments.length?(e=En(t),n):e},n.outerRadius=function(t){return arguments.length?(r=En(t),n):r},n.cornerRadius=function(t){return arguments.length?(i=En(t),n):i},n.padRadius=function(t){return arguments.length?(u=t==ql?ql:En(t),n):u},n.startAngle=function(t){return arguments.length?(o=En(t),n):o},n.endAngle=function(t){return arguments.length?(a=En(t),n):a},n.padAngle=function(t){return arguments.length?(l=En(t),n):l},n.centroid=function(){var n=(+e.apply(this,arguments)+ +r.apply(this,arguments))/2,t=(+o.apply(this,arguments)+ +a.apply(this,arguments))/2-Io;return[Math.cos(t)*n,Math.sin(t)*n]},n};var ql="auto";ao.svg.line=function(){return Mu(m)};var Tl=ao.map({linear:xu,"linear-closed":bu,step:_u,"step-before":wu,"step-after":Su,basis:zu,"basis-open":Lu,"basis-closed":qu,bundle:Tu,cardinal:Eu,"cardinal-open":ku,"cardinal-closed":Nu,monotone:Fu});Tl.forEach(function(n,t){t.key=n,t.closed=/-closed$/.test(n)});var Rl=[0,2/3,1/3,0],Dl=[0,1/3,2/3,0],Pl=[0,1/6,2/3,1/6];ao.svg.line.radial=function(){var n=Mu(Hu);return n.radius=n.x,delete n.x,n.angle=n.y,delete n.y,n},wu.reverse=Su,Su.reverse=wu,ao.svg.area=function(){return Ou(m)},ao.svg.area.radial=function(){var n=Ou(Hu);return n.radius=n.x,delete n.x,n.innerRadius=n.x0,delete n.x0,n.outerRadius=n.x1,delete n.x1,n.angle=n.y,delete n.y,n.startAngle=n.y0,delete n.y0,n.endAngle=n.y1,delete n.y1,n},ao.svg.chord=function(){function n(n,a){var l=t(this,u,n,a),c=t(this,o,n,a);return"M"+l.p0+r(l.r,l.p1,l.a1-l.a0)+(e(l,c)?i(l.r,l.p1,l.r,l.p0):i(l.r,l.p1,c.r,c.p0)+r(c.r,c.p1,c.a1-c.a0)+i(c.r,c.p1,l.r,l.p0))+"Z"}function t(n,t,e,r){var i=t.call(n,e,r),u=a.call(n,i,r),o=l.call(n,i,r)-Io,f=c.call(n,i,r)-Io;return{r:u,a0:o,a1:f,p0:[u*Math.cos(o),u*Math.sin(o)],p1:[u*Math.cos(f),u*Math.sin(f)]}}function e(n,t){return n.a0==t.a0&&n.a1==t.a1}function r(n,t,e){return"A"+n+","+n+" 0 "+ +(e>Fo)+",1 "+t}function i(n,t,e,r){return"Q 0,0 "+r}var u=Me,o=xe,a=Iu,l=gu,c=vu;return n.radius=function(t){return arguments.length?(a=En(t),n):a},n.source=function(t){return arguments.length?(u=En(t),n):u},n.target=function(t){return arguments.length?(o=En(t),n):o},n.startAngle=function(t){return arguments.length?(l=En(t),n):l},n.endAngle=function(t){return arguments.length?(c=En(t),n):c},n},ao.svg.diagonal=function(){function n(n,i){var u=t.call(this,n,i),o=e.call(this,n,i),a=(u.y+o.y)/2,l=[u,{x:u.x,y:a},{x:o.x,y:a},o];return l=l.map(r),"M"+l[0]+"C"+l[1]+" "+l[2]+" "+l[3]}var t=Me,e=xe,r=Yu;return n.source=function(e){return arguments.length?(t=En(e),n):t},n.target=function(t){return arguments.length?(e=En(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},ao.svg.diagonal.radial=function(){var n=ao.svg.diagonal(),t=Yu,e=n.projection;return n.projection=function(n){return arguments.length?e(Zu(t=n)):t},n},ao.svg.symbol=function(){function n(n,r){return(Ul.get(t.call(this,n,r))||$u)(e.call(this,n,r))}var t=Xu,e=Vu;return n.type=function(e){return arguments.length?(t=En(e),n):t},n.size=function(t){return arguments.length?(e=En(t),n):e},n};var Ul=ao.map({circle:$u,cross:function(n){var t=Math.sqrt(n/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(n){var t=Math.sqrt(n/(2*Fl)),e=t*Fl;return"M0,"+-t+"L"+e+",0 0,"+t+" "+-e+",0Z"},square:function(n){var t=Math.sqrt(n)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(n){var t=Math.sqrt(n/jl),e=t*jl/2;return"M0,"+e+"L"+t+","+-e+" "+-t+","+-e+"Z"},"triangle-up":function(n){var t=Math.sqrt(n/jl),e=t*jl/2;return"M0,"+-e+"L"+t+","+e+" "+-t+","+e+"Z"}});ao.svg.symbolTypes=Ul.keys();var jl=Math.sqrt(3),Fl=Math.tan(30*Yo);Co.transition=function(n){for(var t,e,r=Hl||++Zl,i=Ku(n),u=[],o=Ol||{time:Date.now(),ease:Nr,delay:0,duration:250},a=-1,l=this.length;++au;u++){i.push(t=[]);for(var e=this[u],a=0,l=e.length;l>a;a++)(r=e[a])&&n.call(r,r.__data__,a,u)&&t.push(r)}return Wu(i,this.namespace,this.id)},Yl.tween=function(n,t){var e=this.id,r=this.namespace;return arguments.length<2?this.node()[r][e].tween.get(n):Y(this,null==t?function(t){t[r][e].tween.remove(n)}:function(i){i[r][e].tween.set(n,t)})},Yl.attr=function(n,t){function e(){this.removeAttribute(a)}function r(){this.removeAttributeNS(a.space,a.local)}function i(n){return null==n?e:(n+="",function(){var t,e=this.getAttribute(a);return e!==n&&(t=o(e,n),function(n){this.setAttribute(a,t(n))})})}function u(n){return null==n?r:(n+="",function(){var t,e=this.getAttributeNS(a.space,a.local);return e!==n&&(t=o(e,n),function(n){this.setAttributeNS(a.space,a.local,t(n))})})}if(arguments.length<2){for(t in n)this.attr(t,n[t]);return this}var o="transform"==n?$r:Mr,a=ao.ns.qualify(n);return Ju(this,"attr."+n,t,a.local?u:i)},Yl.attrTween=function(n,t){function e(n,e){var r=t.call(this,n,e,this.getAttribute(i));return r&&function(n){this.setAttribute(i,r(n))}}function r(n,e){var r=t.call(this,n,e,this.getAttributeNS(i.space,i.local));return r&&function(n){this.setAttributeNS(i.space,i.local,r(n))}}var i=ao.ns.qualify(n);return this.tween("attr."+n,i.local?r:e)},Yl.style=function(n,e,r){function i(){this.style.removeProperty(n)}function u(e){return null==e?i:(e+="",function(){var i,u=t(this).getComputedStyle(this,null).getPropertyValue(n);return u!==e&&(i=Mr(u,e),function(t){this.style.setProperty(n,i(t),r)})})}var o=arguments.length;if(3>o){if("string"!=typeof n){2>o&&(e="");for(r in n)this.style(r,n[r],e);return this}r=""}return Ju(this,"style."+n,e,u)},Yl.styleTween=function(n,e,r){function i(i,u){var o=e.call(this,i,u,t(this).getComputedStyle(this,null).getPropertyValue(n));return o&&function(t){this.style.setProperty(n,o(t),r)}}return arguments.length<3&&(r=""),this.tween("style."+n,i)},Yl.text=function(n){return Ju(this,"text",n,Gu)},Yl.remove=function(){var n=this.namespace;return this.each("end.transition",function(){var t;this[n].count<2&&(t=this.parentNode)&&t.removeChild(this)})},Yl.ease=function(n){var t=this.id,e=this.namespace;return arguments.length<1?this.node()[e][t].ease:("function"!=typeof n&&(n=ao.ease.apply(ao,arguments)),Y(this,function(r){r[e][t].ease=n}))},Yl.delay=function(n){var t=this.id,e=this.namespace;return arguments.length<1?this.node()[e][t].delay:Y(this,"function"==typeof n?function(r,i,u){r[e][t].delay=+n.call(r,r.__data__,i,u)}:(n=+n,function(r){r[e][t].delay=n}))},Yl.duration=function(n){var t=this.id,e=this.namespace;return arguments.length<1?this.node()[e][t].duration:Y(this,"function"==typeof n?function(r,i,u){r[e][t].duration=Math.max(1,n.call(r,r.__data__,i,u))}:(n=Math.max(1,n),function(r){r[e][t].duration=n}))},Yl.each=function(n,t){var e=this.id,r=this.namespace;if(arguments.length<2){var i=Ol,u=Hl;try{Hl=e,Y(this,function(t,i,u){Ol=t[r][e],n.call(t,t.__data__,i,u)})}finally{Ol=i,Hl=u}}else Y(this,function(i){var u=i[r][e];(u.event||(u.event=ao.dispatch("start","end","interrupt"))).on(n,t)});return this},Yl.transition=function(){for(var n,t,e,r,i=this.id,u=++Zl,o=this.namespace,a=[],l=0,c=this.length;c>l;l++){a.push(n=[]);for(var t=this[l],f=0,s=t.length;s>f;f++)(e=t[f])&&(r=e[o][i],Qu(e,f,o,u,{time:r.time,ease:r.ease,delay:r.delay+r.duration,duration:r.duration})),n.push(e)}return Wu(a,o,u)},ao.svg.axis=function(){function n(n){n.each(function(){var n,c=ao.select(this),f=this.__chart__||e,s=this.__chart__=e.copy(),h=null==l?s.ticks?s.ticks.apply(s,a):s.domain():l,p=null==t?s.tickFormat?s.tickFormat.apply(s,a):m:t,g=c.selectAll(".tick").data(h,s),v=g.enter().insert("g",".domain").attr("class","tick").style("opacity",Uo),d=ao.transition(g.exit()).style("opacity",Uo).remove(),y=ao.transition(g.order()).style("opacity",1),M=Math.max(i,0)+o,x=Zi(s),b=c.selectAll(".domain").data([0]),_=(b.enter().append("path").attr("class","domain"),ao.transition(b));v.append("line"),v.append("text");var w,S,k,N,E=v.select("line"),A=y.select("line"),C=g.select("text").text(p),z=v.select("text"),L=y.select("text"),q="top"===r||"left"===r?-1:1;if("bottom"===r||"top"===r?(n=no,w="x",k="y",S="x2",N="y2",C.attr("dy",0>q?"0em":".71em").style("text-anchor","middle"),_.attr("d","M"+x[0]+","+q*u+"V0H"+x[1]+"V"+q*u)):(n=to,w="y",k="x",S="y2",N="x2",C.attr("dy",".32em").style("text-anchor",0>q?"end":"start"),_.attr("d","M"+q*u+","+x[0]+"H0V"+x[1]+"H"+q*u)),E.attr(N,q*i),z.attr(k,q*M),A.attr(S,0).attr(N,q*i),L.attr(w,0).attr(k,q*M),s.rangeBand){var T=s,R=T.rangeBand()/2;f=s=function(n){return T(n)+R}}else f.rangeBand?f=s:d.call(n,s,f);v.call(n,f,s),y.call(n,s,s)})}var t,e=ao.scale.linear(),r=Vl,i=6,u=6,o=3,a=[10],l=null;return n.scale=function(t){return arguments.length?(e=t,n):e},n.orient=function(t){return arguments.length?(r=t in Xl?t+"":Vl,n):r},n.ticks=function(){return arguments.length?(a=co(arguments),n):a},n.tickValues=function(t){return arguments.length?(l=t,n):l},n.tickFormat=function(e){return arguments.length?(t=e,n):t},n.tickSize=function(t){var e=arguments.length;return e?(i=+t,u=+arguments[e-1],n):i},n.innerTickSize=function(t){return arguments.length?(i=+t,n):i},n.outerTickSize=function(t){return arguments.length?(u=+t,n):u},n.tickPadding=function(t){return arguments.length?(o=+t,n):o},n.tickSubdivide=function(){return arguments.length&&n},n};var Vl="bottom",Xl={top:1,right:1,bottom:1,left:1};ao.svg.brush=function(){function n(t){t.each(function(){var t=ao.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",u).on("touchstart.brush",u),o=t.selectAll(".background").data([0]);o.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair"),t.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var a=t.selectAll(".resize").data(v,m);a.exit().remove(),a.enter().append("g").attr("class",function(n){return"resize "+n}).style("cursor",function(n){return $l[n]}).append("rect").attr("x",function(n){return/[ew]$/.test(n)?-3:null}).attr("y",function(n){return/^[ns]/.test(n)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden"),a.style("display",n.empty()?"none":null);var l,s=ao.transition(t),h=ao.transition(o);c&&(l=Zi(c),h.attr("x",l[0]).attr("width",l[1]-l[0]),r(s)),f&&(l=Zi(f),h.attr("y",l[0]).attr("height",l[1]-l[0]),i(s)),e(s)})}function e(n){n.selectAll(".resize").attr("transform",function(n){return"translate("+s[+/e$/.test(n)]+","+h[+/^s/.test(n)]+")"})}function r(n){n.select(".extent").attr("x",s[0]),n.selectAll(".extent,.n>rect,.s>rect").attr("width",s[1]-s[0])}function i(n){n.select(".extent").attr("y",h[0]),n.selectAll(".extent,.e>rect,.w>rect").attr("height",h[1]-h[0])}function u(){function u(){32==ao.event.keyCode&&(C||(M=null,L[0]-=s[1],L[1]-=h[1],C=2),S())}function v(){32==ao.event.keyCode&&2==C&&(L[0]+=s[1],L[1]+=h[1],C=0,S())}function d(){var n=ao.mouse(b),t=!1;x&&(n[0]+=x[0],n[1]+=x[1]),C||(ao.event.altKey?(M||(M=[(s[0]+s[1])/2,(h[0]+h[1])/2]),L[0]=s[+(n[0]f?(i=r,r=f):i=f),v[0]!=r||v[1]!=i?(e?a=null:o=null,v[0]=r,v[1]=i,!0):void 0}function m(){d(),k.style("pointer-events","all").selectAll(".resize").style("display",n.empty()?"none":null),ao.select("body").style("cursor",null),q.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null),z(),w({type:"brushend"})}var M,x,b=this,_=ao.select(ao.event.target),w=l.of(b,arguments),k=ao.select(b),N=_.datum(),E=!/^(n|s)$/.test(N)&&c,A=!/^(e|w)$/.test(N)&&f,C=_.classed("extent"),z=W(b),L=ao.mouse(b),q=ao.select(t(b)).on("keydown.brush",u).on("keyup.brush",v);if(ao.event.changedTouches?q.on("touchmove.brush",d).on("touchend.brush",m):q.on("mousemove.brush",d).on("mouseup.brush",m),k.interrupt().selectAll("*").interrupt(),C)L[0]=s[0]-L[0],L[1]=h[0]-L[1];else if(N){var T=+/w$/.test(N),R=+/^n/.test(N);x=[s[1-T]-L[0],h[1-R]-L[1]],L[0]=s[T],L[1]=h[R]}else ao.event.altKey&&(M=L.slice());k.style("pointer-events","none").selectAll(".resize").style("display",null),ao.select("body").style("cursor",_.style("cursor")),w({type:"brushstart"}),d()}var o,a,l=N(n,"brushstart","brush","brushend"),c=null,f=null,s=[0,0],h=[0,0],p=!0,g=!0,v=Bl[0];return n.event=function(n){n.each(function(){var n=l.of(this,arguments),t={x:s,y:h,i:o,j:a},e=this.__chart__||t;this.__chart__=t,Hl?ao.select(this).transition().each("start.brush",function(){o=e.i,a=e.j,s=e.x,h=e.y,n({type:"brushstart"})}).tween("brush:brush",function(){var e=xr(s,t.x),r=xr(h,t.y);return o=a=null,function(i){s=t.x=e(i),h=t.y=r(i),n({type:"brush",mode:"resize"})}}).each("end.brush",function(){o=t.i,a=t.j,n({type:"brush",mode:"resize"}),n({type:"brushend"})}):(n({type:"brushstart"}),n({type:"brush",mode:"resize"}),n({type:"brushend"}))})},n.x=function(t){return arguments.length?(c=t,v=Bl[!c<<1|!f],n):c},n.y=function(t){return arguments.length?(f=t,v=Bl[!c<<1|!f],n):f},n.clamp=function(t){return arguments.length?(c&&f?(p=!!t[0],g=!!t[1]):c?p=!!t:f&&(g=!!t),n):c&&f?[p,g]:c?p:f?g:null},n.extent=function(t){var e,r,i,u,l;return arguments.length?(c&&(e=t[0],r=t[1],f&&(e=e[0],r=r[0]),o=[e,r],c.invert&&(e=c(e),r=c(r)),e>r&&(l=e,e=r,r=l),e==s[0]&&r==s[1]||(s=[e,r])),f&&(i=t[0],u=t[1],c&&(i=i[1],u=u[1]),a=[i,u],f.invert&&(i=f(i),u=f(u)),i>u&&(l=i,i=u,u=l),i==h[0]&&u==h[1]||(h=[i,u])),n):(c&&(o?(e=o[0],r=o[1]):(e=s[0],r=s[1],c.invert&&(e=c.invert(e),r=c.invert(r)),e>r&&(l=e,e=r,r=l))),f&&(a?(i=a[0],u=a[1]):(i=h[0],u=h[1],f.invert&&(i=f.invert(i),u=f.invert(u)),i>u&&(l=i,i=u,u=l))),c&&f?[[e,i],[r,u]]:c?[e,r]:f&&[i,u])},n.clear=function(){return n.empty()||(s=[0,0],h=[0,0],o=a=null),n},n.empty=function(){return!!c&&s[0]==s[1]||!!f&&h[0]==h[1]},ao.rebind(n,l,"on")};var $l={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Bl=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],Wl=ga.format=xa.timeFormat,Jl=Wl.utc,Gl=Jl("%Y-%m-%dT%H:%M:%S.%LZ");Wl.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?eo:Gl,eo.parse=function(n){var t=new Date(n);return isNaN(t)?null:t},eo.toString=Gl.toString,ga.second=On(function(n){return new va(1e3*Math.floor(n/1e3))},function(n,t){n.setTime(n.getTime()+1e3*Math.floor(t))},function(n){return n.getSeconds()}),ga.seconds=ga.second.range,ga.seconds.utc=ga.second.utc.range,ga.minute=On(function(n){return new va(6e4*Math.floor(n/6e4))},function(n,t){n.setTime(n.getTime()+6e4*Math.floor(t))},function(n){return n.getMinutes()}),ga.minutes=ga.minute.range,ga.minutes.utc=ga.minute.utc.range,ga.hour=On(function(n){var t=n.getTimezoneOffset()/60;return new va(36e5*(Math.floor(n/36e5-t)+t))},function(n,t){n.setTime(n.getTime()+36e5*Math.floor(t))},function(n){return n.getHours()}),ga.hours=ga.hour.range,ga.hours.utc=ga.hour.utc.range,ga.month=On(function(n){return n=ga.day(n),n.setDate(1),n},function(n,t){n.setMonth(n.getMonth()+t)},function(n){return n.getMonth()}),ga.months=ga.month.range,ga.months.utc=ga.month.utc.range;var Kl=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Ql=[[ga.second,1],[ga.second,5],[ga.second,15],[ga.second,30],[ga.minute,1],[ga.minute,5],[ga.minute,15],[ga.minute,30],[ga.hour,1],[ga.hour,3],[ga.hour,6],[ga.hour,12],[ga.day,1],[ga.day,2],[ga.week,1],[ga.month,1],[ga.month,3],[ga.year,1]],nc=Wl.multi([[".%L",function(n){return n.getMilliseconds()}],[":%S",function(n){return n.getSeconds()}],["%I:%M",function(n){return n.getMinutes()}],["%I %p",function(n){return n.getHours()}],["%a %d",function(n){return n.getDay()&&1!=n.getDate()}],["%b %d",function(n){return 1!=n.getDate()}],["%B",function(n){return n.getMonth()}],["%Y",zt]]),tc={range:function(n,t,e){return ao.range(Math.ceil(n/e)*e,+t,e).map(io)},floor:m,ceil:m};Ql.year=ga.year,ga.scale=function(){return ro(ao.scale.linear(),Ql,nc)};var ec=Ql.map(function(n){return[n[0].utc,n[1]]}),rc=Jl.multi([[".%L",function(n){return n.getUTCMilliseconds()}],[":%S",function(n){return n.getUTCSeconds()}],["%I:%M",function(n){return n.getUTCMinutes()}],["%I %p",function(n){return n.getUTCHours()}],["%a %d",function(n){return n.getUTCDay()&&1!=n.getUTCDate()}],["%b %d",function(n){return 1!=n.getUTCDate()}],["%B",function(n){return n.getUTCMonth()}],["%Y",zt]]);ec.year=ga.year.utc,ga.scale.utc=function(){return ro(ao.scale.linear(),ec,rc)},ao.text=An(function(n){return n.responseText}),ao.json=function(n,t){return Cn(n,"application/json",uo,t)},ao.html=function(n,t){return Cn(n,"text/html",oo,t)},ao.xml=An(function(n){return n.responseXML}),"function"==typeof define&&define.amd?(this.d3=ao,define(ao)):"object"==typeof module&&module.exports?module.exports=ao:this.d3=ao}(); \ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/libs/d3plus/d3plus.full.js b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/libs/d3plus/d3plus.full.js new file mode 100644 index 0000000..dfac33f --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/libs/d3plus/d3plus.full.js @@ -0,0 +1,45904 @@ +(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 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len + + var L = 0 + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' + } + + parts.push(output) + + return parts.join('') +} + +},{}],2:[function(require,module,exports){ +(function (global){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') +var isArray = require('isarray') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + +/* + * Export kMaxLength after typed array support is determined. + */ +exports.kMaxLength = kMaxLength() + +function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } +} + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr +} + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +} + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +} + +function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0 + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +} + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + var actual = that.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual) + } + + return that +} + +function fromArrayLike (that, array) { + var length = checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that +} + +function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start] + } + } + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 +} + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"base64-js":1,"ieee754":6,"isarray":7}],3:[function(require,module,exports){ +!function() { + var d3 = { + version: "3.5.15" + }; + 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.transpose = function(matrix) { + if (!(n = matrix.length)) return []; + for (var i = -1, m = d3.min(matrix, d3_transposeLength), transpose = new Array(m); ++i < m; ) { + for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n; ) { + row[j] = matrix[j][i]; + } + } + return transpose; + }; + function d3_transposeLength(d) { + return d.length; + } + d3.zip = function() { + return d3.transpose(arguments); + }; + 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)) !== "xmlns") 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 && namespace !== document.documentElement.namespaceURI ? 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 (node = group[i]) { + if (nodeByKeyValue.has(keyValue = key.call(node, 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 (i in keyValues && 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 = d3_array(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.correspondingElement || 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); + 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], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S; + if (d2 < ε2) { + S = Math.log(w1 / w0) / ρ; + i = function(t) { + return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * t * S) ]; + }; + } else { + var 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); + S = (r1 - r0) / ρ; + i = function(t) { + var s = t * S, 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) ]; + }; + } + i.duration = S * 1e3; + return i; + }; + 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: null + }; + scaleTo(+_); + 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, 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); + 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 d3_selection_interrupt.call(this), + translate0 = location(center0 = center || d3.mouse(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]+)\((.*)\)/.exec(format = format.toLowerCase()); + 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)) { + 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_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) { + setTimeout(callback, 17); + }; + d3.timer = function() { + d3_timer.apply(this, arguments); + }; + function d3_timer(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, + 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); + } + return timer; + } + 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(), timer = d3_timer_queueHead; + while (timer) { + if (now >= timer.t && timer.c(now - timer.t)) timer.c = null; + timer = timer.n; + } + return now; + } + function d3_timer_sweep() { + var t0, t1 = d3_timer_queueHead, time = Infinity; + while (t1) { + if (t1.c) { + if (t1.t < time) time = t1.t; + t1 = (t0 = t1).n; + } else { + t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = 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 = +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 || "U" in d) { + if (!("w" in d)) d.w = "W" in d ? 1 : 0; + 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.toLowerCase()) || /^(#|rgb\(|hsl\()/i.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_interpolateTransformPop(s) { + return s.length ? s.pop() + "," : ""; + } + function d3_interpolateTranslate(ta, tb, s, q) { + if (ta[0] !== tb[0] || ta[1] !== tb[1]) { + var i = s.push("translate(", null, ",", null, ")"); + q.push({ + i: i - 4, + x: d3_interpolateNumber(ta[0], tb[0]) + }, { + i: i - 2, + x: d3_interpolateNumber(ta[1], tb[1]) + }); + } else if (tb[0] || tb[1]) { + s.push("translate(" + tb + ")"); + } + } + function d3_interpolateRotate(ra, rb, s, q) { + if (ra !== rb) { + if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360; + q.push({ + i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2, + x: d3_interpolateNumber(ra, rb) + }); + } else if (rb) { + s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")"); + } + } + function d3_interpolateSkew(wa, wb, s, q) { + if (wa !== wb) { + q.push({ + i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2, + x: d3_interpolateNumber(wa, wb) + }); + } else if (wb) { + s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")"); + } + } + function d3_interpolateScale(ka, kb, s, q) { + if (ka[0] !== kb[0] || ka[1] !== kb[1]) { + var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")"); + q.push({ + i: i - 4, + x: d3_interpolateNumber(ka[0], kb[0]) + }, { + i: i - 2, + x: d3_interpolateNumber(ka[1], kb[1]) + }); + } else if (kb[0] !== 1 || kb[1] !== 1) { + s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")"); + } + } + function d3_interpolateTransform(a, b) { + var s = [], q = []; + a = d3.transform(a), b = d3.transform(b); + d3_interpolateTranslate(a.translate, b.translate, s, q); + d3_interpolateRotate(a.rotate, b.rotate, s, q); + d3_interpolateSkew(a.skew, b.skew, s, q); + d3_interpolateScale(a.scale, b.scale, s, q); + a = b = null; + return function(t) { + var i = -1, n = q.length, 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: groupSums[di] + }; + 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"), timer, 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) { + timer = null; + 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 / (s.weight + t.weight) : .5); + 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 { + timer.c = null, timer.t = NaN, timer = null; + event.end({ + type: "end", + alpha: alpha = 0 + }); + } + } else if (x > 0) { + event.start({ + type: "start", + alpha: alpha = x + }); + timer = 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), sum = d3.sum(values), k = sum ? (da - n * pa) / sum : 0, 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 = root.y = 0; + if (root.value) root.dx = size[0], root.dy = size[1]; else root.dx = root.dy = 0; + 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) { + d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); + d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); + return domain; + } + 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, base * n / scale.ticks().length); + return function(d) { + var i = d / pow(Math.round(log(d))); + if (i * base < base - .5) i *= base; + return i <= 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 (da > ε && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) { + cr = r0 < r1 ^ cw ? 0 : 1; + var rc1 = rc, rc0 = rc; + if (da < π) { + 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]); + rc0 = Math.min(rc, (r0 - lc) / (kc - 1)); + rc1 = Math.min(rc, (r1 - lc) / (kc + 1)); + } + if (x1 != null) { + var 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 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(Math.max(0, 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.length > 1 ? points.join("L") : points + "Z"; + } + function d3_svg_lineLinearClosed(points) { + return points.join("L") + "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_lineLinearClosed(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, activeId, active; + if ((lock = this[ns]) && (active = lock[activeId = lock.active])) { + active.timer.c = null; + active.timer.t = NaN; + if (--lock.count) delete lock[activeId]; 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], time, timer, duration, ease, tweens; + function schedule(elapsed) { + var delay = transition.delay; + timer.t = delay + time; + if (delay <= elapsed) return start(elapsed - delay); + timer.c = start; + } + function start(elapsed) { + var activeId = lock.active, active = lock[activeId]; + if (active) { + active.timer.c = null; + active.timer.t = NaN; + --lock.count; + delete lock[activeId]; + active.event && active.event.interrupt.call(node, node.__data__, active.index); + } + for (var cancelId in lock) { + if (+cancelId < id) { + var cancel = lock[cancelId]; + cancel.timer.c = null; + cancel.timer.t = NaN; + --lock.count; + delete lock[cancelId]; + } + } + timer.c = tick; + d3_timer(function() { + if (timer.c && tick(elapsed || 1)) { + timer.c = null; + timer.t = NaN; + } + return 1; + }, 0, time); + lock.active = id; + transition.event && transition.event.start.call(node, node.__data__, i); + tweens = []; + transition.tween.forEach(function(key, value) { + if (value = value.call(node, node.__data__, i)) { + tweens.push(value); + } + }); + ease = transition.ease; + duration = transition.duration; + } + function tick(elapsed) { + var t = elapsed / duration, e = ease(t), n = tweens.length; + while (n > 0) { + tweens[--n].call(node, e); + } + if (t >= 1) { + transition.event && transition.event.end.call(node, node.__data__, i); + if (--lock.count) delete lock[id]; else delete node[ns]; + return 1; + } + } + if (!transition) { + time = inherit.time; + timer = d3_timer(schedule, 0, time); + transition = lock[id] = { + tween: new d3_Map(), + time: time, + timer: timer, + delay: inherit.delay, + duration: inherit.duration, + ease: inherit.ease, + index: i + }; + inherit = null; + ++lock.count; + } + } + 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_ = d3_array(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) this.d3 = d3, define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; else this.d3 = d3; +}(); +},{}],4:[function(require,module,exports){ +module.exports = require('./lib/heap'); + +},{"./lib/heap":5}],5:[function(require,module,exports){ +// Generated by CoffeeScript 1.8.0 +(function() { + var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup; + + floor = Math.floor, min = Math.min; + + + /* + Default comparison function to be used + */ + + defaultCmp = function(x, y) { + if (x < y) { + return -1; + } + if (x > y) { + return 1; + } + return 0; + }; + + + /* + Insert item x in list a, and keep it sorted assuming a is sorted. + + If x is already in a, insert it to the right of the rightmost x. + + Optional args lo (default 0) and hi (default a.length) bound the slice + of a to be searched. + */ + + insort = function(a, x, lo, hi, cmp) { + var mid; + if (lo == null) { + lo = 0; + } + if (cmp == null) { + cmp = defaultCmp; + } + if (lo < 0) { + throw new Error('lo must be non-negative'); + } + if (hi == null) { + hi = a.length; + } + while (lo < hi) { + mid = floor((lo + hi) / 2); + if (cmp(x, a[mid]) < 0) { + hi = mid; + } else { + lo = mid + 1; + } + } + return ([].splice.apply(a, [lo, lo - lo].concat(x)), x); + }; + + + /* + Push item onto heap, maintaining the heap invariant. + */ + + heappush = function(array, item, cmp) { + if (cmp == null) { + cmp = defaultCmp; + } + array.push(item); + return _siftdown(array, 0, array.length - 1, cmp); + }; + + + /* + Pop the smallest item off the heap, maintaining the heap invariant. + */ + + heappop = function(array, cmp) { + var lastelt, returnitem; + if (cmp == null) { + cmp = defaultCmp; + } + lastelt = array.pop(); + if (array.length) { + returnitem = array[0]; + array[0] = lastelt; + _siftup(array, 0, cmp); + } else { + returnitem = lastelt; + } + return returnitem; + }; + + + /* + Pop and return the current smallest value, and add the new item. + + This is more efficient than heappop() followed by heappush(), and can be + more appropriate when using a fixed size heap. Note that the value + returned may be larger than item! That constrains reasonable use of + this routine unless written as part of a conditional replacement: + if item > array[0] + item = heapreplace(array, item) + */ + + heapreplace = function(array, item, cmp) { + var returnitem; + if (cmp == null) { + cmp = defaultCmp; + } + returnitem = array[0]; + array[0] = item; + _siftup(array, 0, cmp); + return returnitem; + }; + + + /* + Fast version of a heappush followed by a heappop. + */ + + heappushpop = function(array, item, cmp) { + var _ref; + if (cmp == null) { + cmp = defaultCmp; + } + if (array.length && cmp(array[0], item) < 0) { + _ref = [array[0], item], item = _ref[0], array[0] = _ref[1]; + _siftup(array, 0, cmp); + } + return item; + }; + + + /* + Transform list into a heap, in-place, in O(array.length) time. + */ + + heapify = function(array, cmp) { + var i, _i, _j, _len, _ref, _ref1, _results, _results1; + if (cmp == null) { + cmp = defaultCmp; + } + _ref1 = (function() { + _results1 = []; + for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); } + return _results1; + }).apply(this).reverse(); + _results = []; + for (_i = 0, _len = _ref1.length; _i < _len; _i++) { + i = _ref1[_i]; + _results.push(_siftup(array, i, cmp)); + } + return _results; + }; + + + /* + Update the position of the given item in the heap. + This function should be called every time the item is being modified. + */ + + updateItem = function(array, item, cmp) { + var pos; + if (cmp == null) { + cmp = defaultCmp; + } + pos = array.indexOf(item); + if (pos === -1) { + return; + } + _siftdown(array, 0, pos, cmp); + return _siftup(array, pos, cmp); + }; + + + /* + Find the n largest elements in a dataset. + */ + + nlargest = function(array, n, cmp) { + var elem, result, _i, _len, _ref; + if (cmp == null) { + cmp = defaultCmp; + } + result = array.slice(0, n); + if (!result.length) { + return result; + } + heapify(result, cmp); + _ref = array.slice(n); + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + elem = _ref[_i]; + heappushpop(result, elem, cmp); + } + return result.sort(cmp).reverse(); + }; + + + /* + Find the n smallest elements in a dataset. + */ + + nsmallest = function(array, n, cmp) { + var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results; + if (cmp == null) { + cmp = defaultCmp; + } + if (n * 10 <= array.length) { + result = array.slice(0, n).sort(cmp); + if (!result.length) { + return result; + } + los = result[result.length - 1]; + _ref = array.slice(n); + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + elem = _ref[_i]; + if (cmp(elem, los) < 0) { + insort(result, elem, 0, null, cmp); + result.pop(); + los = result[result.length - 1]; + } + } + return result; + } + heapify(array, cmp); + _results = []; + for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) { + _results.push(heappop(array, cmp)); + } + return _results; + }; + + _siftdown = function(array, startpos, pos, cmp) { + var newitem, parent, parentpos; + if (cmp == null) { + cmp = defaultCmp; + } + newitem = array[pos]; + while (pos > startpos) { + parentpos = (pos - 1) >> 1; + parent = array[parentpos]; + if (cmp(newitem, parent) < 0) { + array[pos] = parent; + pos = parentpos; + continue; + } + break; + } + return array[pos] = newitem; + }; + + _siftup = function(array, pos, cmp) { + var childpos, endpos, newitem, rightpos, startpos; + if (cmp == null) { + cmp = defaultCmp; + } + endpos = array.length; + startpos = pos; + newitem = array[pos]; + childpos = 2 * pos + 1; + while (childpos < endpos) { + rightpos = childpos + 1; + if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) { + childpos = rightpos; + } + array[pos] = array[childpos]; + pos = childpos; + childpos = 2 * pos + 1; + } + array[pos] = newitem; + return _siftdown(array, startpos, pos, cmp); + }; + + Heap = (function() { + Heap.push = heappush; + + Heap.pop = heappop; + + Heap.replace = heapreplace; + + Heap.pushpop = heappushpop; + + Heap.heapify = heapify; + + Heap.updateItem = updateItem; + + Heap.nlargest = nlargest; + + Heap.nsmallest = nsmallest; + + function Heap(cmp) { + this.cmp = cmp != null ? cmp : defaultCmp; + this.nodes = []; + } + + Heap.prototype.push = function(x) { + return heappush(this.nodes, x, this.cmp); + }; + + Heap.prototype.pop = function() { + return heappop(this.nodes, this.cmp); + }; + + Heap.prototype.peek = function() { + return this.nodes[0]; + }; + + Heap.prototype.contains = function(x) { + return this.nodes.indexOf(x) !== -1; + }; + + Heap.prototype.replace = function(x) { + return heapreplace(this.nodes, x, this.cmp); + }; + + Heap.prototype.pushpop = function(x) { + return heappushpop(this.nodes, x, this.cmp); + }; + + Heap.prototype.heapify = function() { + return heapify(this.nodes, this.cmp); + }; + + Heap.prototype.updateItem = function(x) { + return updateItem(this.nodes, x, this.cmp); + }; + + Heap.prototype.clear = function() { + return this.nodes = []; + }; + + Heap.prototype.empty = function() { + return this.nodes.length === 0; + }; + + Heap.prototype.size = function() { + return this.nodes.length; + }; + + Heap.prototype.clone = function() { + var heap; + heap = new Heap(); + heap.nodes = this.nodes.slice(0); + return heap; + }; + + Heap.prototype.toArray = function() { + return this.nodes.slice(0); + }; + + Heap.prototype.insert = Heap.prototype.push; + + Heap.prototype.top = Heap.prototype.peek; + + Heap.prototype.front = Heap.prototype.peek; + + Heap.prototype.has = Heap.prototype.contains; + + Heap.prototype.copy = Heap.prototype.clone; + + return Heap; + + })(); + + (function(root, factory) { + if (typeof define === 'function' && define.amd) { + return define([], factory); + } else if (typeof exports === 'object') { + return module.exports = factory(); + } else { + return root.Heap = factory(); + } + })(this, function() { + return Heap; + }); + +}).call(this); + +},{}],6:[function(require,module,exports){ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}],7:[function(require,module,exports){ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +},{}],8:[function(require,module,exports){ +(function (global){ +"use strict"; + +var numeric = (typeof exports === "undefined")?(function numeric() {}):(exports); +if(typeof global !== "undefined") { global.numeric = numeric; } + +numeric.version = "1.2.6"; + +// 1. Utility functions +numeric.bench = function bench (f,interval) { + var t1,t2,n,i; + if(typeof interval === "undefined") { interval = 15; } + n = 0.5; + t1 = new Date(); + while(1) { + n*=2; + for(i=n;i>3;i-=4) { f(); f(); f(); f(); } + while(i>0) { f(); i--; } + t2 = new Date(); + if(t2-t1 > interval) break; + } + for(i=n;i>3;i-=4) { f(); f(); f(); f(); } + while(i>0) { f(); i--; } + t2 = new Date(); + return 1000*(3*n-1)/(t2-t1); +} + +numeric._myIndexOf = (function _myIndexOf(w) { + var n = this.length,k; + for(k=0;k numeric.largeArray) { ret.push('...Large Array...'); return true; } + var flag = false; + ret.push('['); + for(k=0;k0) { ret.push(','); if(flag) ret.push('\n '); } flag = foo(x[k]); } + ret.push(']'); + return true; + } + ret.push('{'); + var flag = false; + for(k in x) { if(x.hasOwnProperty(k)) { if(flag) ret.push(',\n'); flag = true; ret.push(k); ret.push(': \n'); foo(x[k]); } } + ret.push('}'); + return true; + } + foo(x); + return ret.join(''); +} + +numeric.parseDate = function parseDate(d) { + function foo(d) { + if(typeof d === 'string') { return Date.parse(d.replace(/-/g,'/')); } + if(!(d instanceof Array)) { throw new Error("parseDate: parameter must be arrays of strings"); } + var ret = [],k; + for(k=0;k0) { + ret[count] = []; + for(j=0;j> 2; + q = ((x & 3) << 4) + (y >> 4); + r = ((y & 15) << 2) + (z >> 6); + s = z & 63; + if(i+1>=n) { r = s = 64; } + else if(i+2>=n) { s = 64; } + ret += key.charAt(p) + key.charAt(q) + key.charAt(r) + key.charAt(s); + } + return ret; + } + function crc32Array (a,from,to) { + if(typeof from === "undefined") { from = 0; } + if(typeof to === "undefined") { to = a.length; } + var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, + 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, + 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, + 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, + 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, + 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, + 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, + 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, + 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, + 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, + 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, + 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, + 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, + 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, + 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, + 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, + 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, + 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, + 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, + 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, + 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, + 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, + 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, + 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, + 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, + 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, + 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, + 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, + 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, + 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, + 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, + 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; + + var crc = -1, y = 0, n = a.length,i; + + for (i = from; i < to; i++) { + y = (crc ^ a[i]) & 0xFF; + crc = (crc >>> 8) ^ table[y]; + } + + return crc ^ (-1); + } + + var h = img[0].length, w = img[0][0].length, s1, s2, next,k,length,a,b,i,j,adler32,crc32; + var stream = [ + 137, 80, 78, 71, 13, 10, 26, 10, // 0: PNG signature + 0,0,0,13, // 8: IHDR Chunk length + 73, 72, 68, 82, // 12: "IHDR" + (w >> 24) & 255, (w >> 16) & 255, (w >> 8) & 255, w&255, // 16: Width + (h >> 24) & 255, (h >> 16) & 255, (h >> 8) & 255, h&255, // 20: Height + 8, // 24: bit depth + 2, // 25: RGB + 0, // 26: deflate + 0, // 27: no filter + 0, // 28: no interlace + -1,-2,-3,-4, // 29: CRC + -5,-6,-7,-8, // 33: IDAT Chunk length + 73, 68, 65, 84, // 37: "IDAT" + // RFC 1950 header starts here + 8, // 41: RFC1950 CMF + 29 // 42: RFC1950 FLG + ]; + crc32 = crc32Array(stream,12,29); + stream[29] = (crc32>>24)&255; + stream[30] = (crc32>>16)&255; + stream[31] = (crc32>>8)&255; + stream[32] = (crc32)&255; + s1 = 1; + s2 = 0; + for(i=0;i>8)&255; + stream.push(a); stream.push(b); + stream.push((~a)&255); stream.push((~b)&255); + if(i===0) stream.push(0); + for(j=0;j255) a = 255; + else if(a<0) a=0; + else a = Math.round(a); + s1 = (s1 + a )%65521; + s2 = (s2 + s1)%65521; + stream.push(a); + } + } + stream.push(0); + } + adler32 = (s2<<16)+s1; + stream.push((adler32>>24)&255); + stream.push((adler32>>16)&255); + stream.push((adler32>>8)&255); + stream.push((adler32)&255); + length = stream.length - 41; + stream[33] = (length>>24)&255; + stream[34] = (length>>16)&255; + stream[35] = (length>>8)&255; + stream[36] = (length)&255; + crc32 = crc32Array(stream,37); + stream.push((crc32>>24)&255); + stream.push((crc32>>16)&255); + stream.push((crc32>>8)&255); + stream.push((crc32)&255); + stream.push(0); + stream.push(0); + stream.push(0); + stream.push(0); +// a = stream.length; + stream.push(73); // I + stream.push(69); // E + stream.push(78); // N + stream.push(68); // D + stream.push(174); // CRC1 + stream.push(66); // CRC2 + stream.push(96); // CRC3 + stream.push(130); // CRC4 + return 'data:image/png;base64,'+base64(stream); +} + +// 2. Linear algebra with Arrays. +numeric._dim = function _dim(x) { + var ret = []; + while(typeof x === "object") { ret.push(x.length); x = x[0]; } + return ret; +} + +numeric.dim = function dim(x) { + var y,z; + if(typeof x === "object") { + y = x[0]; + if(typeof y === "object") { + z = y[0]; + if(typeof z === "object") { + return numeric._dim(x); + } + return [x.length,y.length]; + } + return [x.length]; + } + return []; +} + +numeric.mapreduce = function mapreduce(body,init) { + return Function('x','accum','_s','_k', + 'if(typeof accum === "undefined") accum = '+init+';\n'+ + 'if(typeof x === "number") { var xi = x; '+body+'; return accum; }\n'+ + 'if(typeof _s === "undefined") _s = numeric.dim(x);\n'+ + 'if(typeof _k === "undefined") _k = 0;\n'+ + 'var _n = _s[_k];\n'+ + 'var i,xi;\n'+ + 'if(_k < _s.length-1) {\n'+ + ' for(i=_n-1;i>=0;i--) {\n'+ + ' accum = arguments.callee(x[i],accum,_s,_k+1);\n'+ + ' }'+ + ' return accum;\n'+ + '}\n'+ + 'for(i=_n-1;i>=1;i-=2) { \n'+ + ' xi = x[i];\n'+ + ' '+body+';\n'+ + ' xi = x[i-1];\n'+ + ' '+body+';\n'+ + '}\n'+ + 'if(i === 0) {\n'+ + ' xi = x[i];\n'+ + ' '+body+'\n'+ + '}\n'+ + 'return accum;' + ); +} +numeric.mapreduce2 = function mapreduce2(body,setup) { + return Function('x', + 'var n = x.length;\n'+ + 'var i,xi;\n'+setup+';\n'+ + 'for(i=n-1;i!==-1;--i) { \n'+ + ' xi = x[i];\n'+ + ' '+body+';\n'+ + '}\n'+ + 'return accum;' + ); +} + + +numeric.same = function same(x,y) { + var i,n; + if(!(x instanceof Array) || !(y instanceof Array)) { return false; } + n = x.length; + if(n !== y.length) { return false; } + for(i=0;i=0;i-=2) { ret[i+1] = v; ret[i] = v; } + if(i===-1) { ret[0] = v; } + return ret; + } + for(i=n-1;i>=0;i--) { ret[i] = numeric.rep(s,v,k+1); } + return ret; +} + + +numeric.dotMMsmall = function dotMMsmall(x,y) { + var i,j,k,p,q,r,ret,foo,bar,woo,i0,k0,p0,r0; + p = x.length; q = y.length; r = y[0].length; + ret = Array(p); + for(i=p-1;i>=0;i--) { + foo = Array(r); + bar = x[i]; + for(k=r-1;k>=0;k--) { + woo = bar[q-1]*y[q-1][k]; + for(j=q-2;j>=1;j-=2) { + i0 = j-1; + woo += bar[j]*y[j][k] + bar[i0]*y[i0][k]; + } + if(j===0) { woo += bar[0]*y[0][k]; } + foo[k] = woo; + } + ret[i] = foo; + } + return ret; +} +numeric._getCol = function _getCol(A,j,x) { + var n = A.length, i; + for(i=n-1;i>0;--i) { + x[i] = A[i][j]; + --i; + x[i] = A[i][j]; + } + if(i===0) x[0] = A[0][j]; +} +numeric.dotMMbig = function dotMMbig(x,y){ + var gc = numeric._getCol, p = y.length, v = Array(p); + var m = x.length, n = y[0].length, A = new Array(m), xj; + var VV = numeric.dotVV; + var i,j,k,z; + --p; + --m; + for(i=m;i!==-1;--i) A[i] = Array(n); + --n; + for(i=n;i!==-1;--i) { + gc(y,i,v); + for(j=m;j!==-1;--j) { + z=0; + xj = x[j]; + A[j][i] = VV(xj,v); + } + } + return A; +} + +numeric.dotMV = function dotMV(x,y) { + var p = x.length, q = y.length,i; + var ret = Array(p), dotVV = numeric.dotVV; + for(i=p-1;i>=0;i--) { ret[i] = dotVV(x[i],y); } + return ret; +} + +numeric.dotVM = function dotVM(x,y) { + var i,j,k,p,q,r,ret,foo,bar,woo,i0,k0,p0,r0,s1,s2,s3,baz,accum; + p = x.length; q = y[0].length; + ret = Array(q); + for(k=q-1;k>=0;k--) { + woo = x[p-1]*y[p-1][k]; + for(j=p-2;j>=1;j-=2) { + i0 = j-1; + woo += x[j]*y[j][k] + x[i0]*y[i0][k]; + } + if(j===0) { woo += x[0]*y[0][k]; } + ret[k] = woo; + } + return ret; +} + +numeric.dotVV = function dotVV(x,y) { + var i,n=x.length,i1,ret = x[n-1]*y[n-1]; + for(i=n-2;i>=1;i-=2) { + i1 = i-1; + ret += x[i]*y[i] + x[i1]*y[i1]; + } + if(i===0) { ret += x[0]*y[0]; } + return ret; +} + +numeric.dot = function dot(x,y) { + var d = numeric.dim; + switch(d(x).length*1000+d(y).length) { + case 2002: + if(y.length < 10) return numeric.dotMMsmall(x,y); + else return numeric.dotMMbig(x,y); + case 2001: return numeric.dotMV(x,y); + case 1002: return numeric.dotVM(x,y); + case 1001: return numeric.dotVV(x,y); + case 1000: return numeric.mulVS(x,y); + case 1: return numeric.mulSV(x,y); + case 0: return x*y; + default: throw new Error('numeric.dot only works on vectors and matrices'); + } +} + +numeric.diag = function diag(d) { + var i,i1,j,n = d.length, A = Array(n), Ai; + for(i=n-1;i>=0;i--) { + Ai = Array(n); + i1 = i+2; + for(j=n-1;j>=i1;j-=2) { + Ai[j] = 0; + Ai[j-1] = 0; + } + if(j>i) { Ai[j] = 0; } + Ai[i] = d[i]; + for(j=i-1;j>=1;j-=2) { + Ai[j] = 0; + Ai[j-1] = 0; + } + if(j===0) { Ai[0] = 0; } + A[i] = Ai; + } + return A; +} +numeric.getDiag = function(A) { + var n = Math.min(A.length,A[0].length),i,ret = Array(n); + for(i=n-1;i>=1;--i) { + ret[i] = A[i][i]; + --i; + ret[i] = A[i][i]; + } + if(i===0) { + ret[0] = A[0][0]; + } + return ret; +} + +numeric.identity = function identity(n) { return numeric.diag(numeric.rep([n],1)); } +numeric.pointwise = function pointwise(params,body,setup) { + if(typeof setup === "undefined") { setup = ""; } + var fun = []; + var k; + var avec = /\[i\]$/,p,thevec = ''; + var haveret = false; + for(k=0;k=0;i--) ret[i] = arguments.callee('+params.join(',')+',_s,_k+1);\n'+ + ' return ret;\n'+ + '}\n'+ + setup+'\n'+ + 'for(i=_n-1;i!==-1;--i) {\n'+ + ' '+body+'\n'+ + '}\n'+ + 'return ret;' + ); + return Function.apply(null,fun); +} +numeric.pointwise2 = function pointwise2(params,body,setup) { + if(typeof setup === "undefined") { setup = ""; } + var fun = []; + var k; + var avec = /\[i\]$/,p,thevec = ''; + var haveret = false; + for(k=0;k=0;i--) { _biforeach(typeof x==="object"?x[i]:x,typeof y==="object"?y[i]:y,s,k+1,f); } +}); +numeric._biforeach2 = (function _biforeach2(x,y,s,k,f) { + if(k === s.length-1) { return f(x,y); } + var i,n=s[k],ret = Array(n); + for(i=n-1;i>=0;--i) { ret[i] = _biforeach2(typeof x==="object"?x[i]:x,typeof y==="object"?y[i]:y,s,k+1,f); } + return ret; +}); +numeric._foreach = (function _foreach(x,s,k,f) { + if(k === s.length-1) { f(x); return; } + var i,n=s[k]; + for(i=n-1;i>=0;i--) { _foreach(x[i],s,k+1,f); } +}); +numeric._foreach2 = (function _foreach2(x,s,k,f) { + if(k === s.length-1) { return f(x); } + var i,n=s[k], ret = Array(n); + for(i=n-1;i>=0;i--) { ret[i] = _foreach2(x[i],s,k+1,f); } + return ret; +}); + +/*numeric.anyV = numeric.mapreduce('if(xi) return true;','false'); +numeric.allV = numeric.mapreduce('if(!xi) return false;','true'); +numeric.any = function(x) { if(typeof x.length === "undefined") return x; return numeric.anyV(x); } +numeric.all = function(x) { if(typeof x.length === "undefined") return x; return numeric.allV(x); }*/ + +numeric.ops2 = { + add: '+', + sub: '-', + mul: '*', + div: '/', + mod: '%', + and: '&&', + or: '||', + eq: '===', + neq: '!==', + lt: '<', + gt: '>', + leq: '<=', + geq: '>=', + band: '&', + bor: '|', + bxor: '^', + lshift: '<<', + rshift: '>>', + rrshift: '>>>' +}; +numeric.opseq = { + addeq: '+=', + subeq: '-=', + muleq: '*=', + diveq: '/=', + modeq: '%=', + lshifteq: '<<=', + rshifteq: '>>=', + rrshifteq: '>>>=', + bandeq: '&=', + boreq: '|=', + bxoreq: '^=' +}; +numeric.mathfuns = ['abs','acos','asin','atan','ceil','cos', + 'exp','floor','log','round','sin','sqrt','tan', + 'isNaN','isFinite']; +numeric.mathfuns2 = ['atan2','pow','max','min']; +numeric.ops1 = { + neg: '-', + not: '!', + bnot: '~', + clone: '' +}; +numeric.mapreducers = { + any: ['if(xi) return true;','var accum = false;'], + all: ['if(!xi) return false;','var accum = true;'], + sum: ['accum += xi;','var accum = 0;'], + prod: ['accum *= xi;','var accum = 1;'], + norm2Squared: ['accum += xi*xi;','var accum = 0;'], + norminf: ['accum = max(accum,abs(xi));','var accum = 0, max = Math.max, abs = Math.abs;'], + norm1: ['accum += abs(xi)','var accum = 0, abs = Math.abs;'], + sup: ['accum = max(accum,xi);','var accum = -Infinity, max = Math.max;'], + inf: ['accum = min(accum,xi);','var accum = Infinity, min = Math.min;'] +}; + +(function () { + var i,o; + for(i=0;iv0) { i0 = i; v0 = k; } } + Aj = A[i0]; A[i0] = A[j]; A[j] = Aj; + Ij = I[i0]; I[i0] = I[j]; I[j] = Ij; + x = Aj[j]; + for(k=j;k!==n;++k) Aj[k] /= x; + for(k=n-1;k!==-1;--k) Ij[k] /= x; + for(i=m-1;i!==-1;--i) { + if(i!==j) { + Ai = A[i]; + Ii = I[i]; + x = Ai[j]; + for(k=j+1;k!==n;++k) Ai[k] -= Aj[k]*x; + for(k=n-1;k>0;--k) { Ii[k] -= Ij[k]*x; --k; Ii[k] -= Ij[k]*x; } + if(k===0) Ii[0] -= Ij[0]*x; + } + } + } + return I; +} + +numeric.det = function det(x) { + var s = numeric.dim(x); + if(s.length !== 2 || s[0] !== s[1]) { throw new Error('numeric: det() only works on square matrices'); } + var n = s[0], ret = 1,i,j,k,A = numeric.clone(x),Aj,Ai,alpha,temp,k1,k2,k3; + for(j=0;j Math.abs(A[k][j])) { k = i; } } + if(k !== j) { + temp = A[k]; A[k] = A[j]; A[j] = temp; + ret *= -1; + } + Aj = A[j]; + for(i=j+1;i=1;i-=2) { + A1 = x[i]; + A0 = x[i-1]; + for(j=n-1;j>=1;--j) { + Bj = ret[j]; Bj[i] = A1[j]; Bj[i-1] = A0[j]; + --j; + Bj = ret[j]; Bj[i] = A1[j]; Bj[i-1] = A0[j]; + } + if(j===0) { + Bj = ret[0]; Bj[i] = A1[0]; Bj[i-1] = A0[0]; + } + } + if(i===0) { + A0 = x[0]; + for(j=n-1;j>=1;--j) { + ret[j][0] = A0[j]; + --j; + ret[j][0] = A0[j]; + } + if(j===0) { ret[0][0] = A0[0]; } + } + return ret; +} +numeric.negtranspose = function negtranspose(x) { + var i,j,m = x.length,n = x[0].length, ret=Array(n),A0,A1,Bj; + for(j=0;j=1;i-=2) { + A1 = x[i]; + A0 = x[i-1]; + for(j=n-1;j>=1;--j) { + Bj = ret[j]; Bj[i] = -A1[j]; Bj[i-1] = -A0[j]; + --j; + Bj = ret[j]; Bj[i] = -A1[j]; Bj[i-1] = -A0[j]; + } + if(j===0) { + Bj = ret[0]; Bj[i] = -A1[0]; Bj[i-1] = -A0[0]; + } + } + if(i===0) { + A0 = x[0]; + for(j=n-1;j>=1;--j) { + ret[j][0] = -A0[j]; + --j; + ret[j][0] = -A0[j]; + } + if(j===0) { ret[0][0] = -A0[0]; } + } + return ret; +} + +numeric._random = function _random(s,k) { + var i,n=s[k],ret=Array(n), rnd; + if(k === s.length-1) { + rnd = Math.random; + for(i=n-1;i>=1;i-=2) { + ret[i] = rnd(); + ret[i-1] = rnd(); + } + if(i===0) { ret[0] = rnd(); } + return ret; + } + for(i=n-1;i>=0;i--) ret[i] = _random(s,k+1); + return ret; +} +numeric.random = function random(s) { return numeric._random(s,0); } + +numeric.norm2 = function norm2(x) { return Math.sqrt(numeric.norm2Squared(x)); } + +numeric.linspace = function linspace(a,b,n) { + if(typeof n === "undefined") n = Math.max(Math.round(b-a)+1,1); + if(n<2) { return n===1?[a]:[]; } + var i,ret = Array(n); + n--; + for(i=n;i>=0;i--) { ret[i] = (i*b+(n-i)*a)/n; } + return ret; +} + +numeric.getBlock = function getBlock(x,from,to) { + var s = numeric.dim(x); + function foo(x,k) { + var i,a = from[k], n = to[k]-a, ret = Array(n); + if(k === s.length-1) { + for(i=n;i>=0;i--) { ret[i] = x[i+a]; } + return ret; + } + for(i=n;i>=0;i--) { ret[i] = foo(x[i+a],k+1); } + return ret; + } + return foo(x,0); +} + +numeric.setBlock = function setBlock(x,from,to,B) { + var s = numeric.dim(x); + function foo(x,y,k) { + var i,a = from[k], n = to[k]-a; + if(k === s.length-1) { for(i=n;i>=0;i--) { x[i+a] = y[i]; } } + for(i=n;i>=0;i--) { foo(x[i+a],y[i],k+1); } + } + foo(x,B,0); + return x; +} + +numeric.getRange = function getRange(A,I,J) { + var m = I.length, n = J.length; + var i,j; + var B = Array(m), Bi, AI; + for(i=m-1;i!==-1;--i) { + B[i] = Array(n); + Bi = B[i]; + AI = A[I[i]]; + for(j=n-1;j!==-1;--j) Bi[j] = AI[J[j]]; + } + return B; +} + +numeric.blockMatrix = function blockMatrix(X) { + var s = numeric.dim(X); + if(s.length<4) return numeric.blockMatrix([X]); + var m=s[0],n=s[1],M,N,i,j,Xij; + M = 0; N = 0; + for(i=0;i=0;i--) { + Ai = Array(n); + xi = x[i]; + for(j=n-1;j>=3;--j) { + Ai[j] = xi * y[j]; + --j; + Ai[j] = xi * y[j]; + --j; + Ai[j] = xi * y[j]; + --j; + Ai[j] = xi * y[j]; + } + while(j>=0) { Ai[j] = xi * y[j]; --j; } + A[i] = Ai; + } + return A; +} + +// 3. The Tensor type T +numeric.T = function T(x,y) { this.x = x; this.y = y; } +numeric.t = function t(x,y) { return new numeric.T(x,y); } + +numeric.Tbinop = function Tbinop(rr,rc,cr,cc,setup) { + var io = numeric.indexOf; + if(typeof setup !== "string") { + var k; + setup = ''; + for(k in numeric) { + if(numeric.hasOwnProperty(k) && (rr.indexOf(k)>=0 || rc.indexOf(k)>=0 || cr.indexOf(k)>=0 || cc.indexOf(k)>=0) && k.length>1) { + setup += 'var '+k+' = numeric.'+k+';\n'; + } + } + } + return Function(['y'], + 'var x = this;\n'+ + 'if(!(y instanceof numeric.T)) { y = new numeric.T(y); }\n'+ + setup+'\n'+ + 'if(x.y) {'+ + ' if(y.y) {'+ + ' return new numeric.T('+cc+');\n'+ + ' }\n'+ + ' return new numeric.T('+cr+');\n'+ + '}\n'+ + 'if(y.y) {\n'+ + ' return new numeric.T('+rc+');\n'+ + '}\n'+ + 'return new numeric.T('+rr+');\n' + ); +} + +numeric.T.prototype.add = numeric.Tbinop( + 'add(x.x,y.x)', + 'add(x.x,y.x),y.y', + 'add(x.x,y.x),x.y', + 'add(x.x,y.x),add(x.y,y.y)'); +numeric.T.prototype.sub = numeric.Tbinop( + 'sub(x.x,y.x)', + 'sub(x.x,y.x),neg(y.y)', + 'sub(x.x,y.x),x.y', + 'sub(x.x,y.x),sub(x.y,y.y)'); +numeric.T.prototype.mul = numeric.Tbinop( + 'mul(x.x,y.x)', + 'mul(x.x,y.x),mul(x.x,y.y)', + 'mul(x.x,y.x),mul(x.y,y.x)', + 'sub(mul(x.x,y.x),mul(x.y,y.y)),add(mul(x.x,y.y),mul(x.y,y.x))'); + +numeric.T.prototype.reciprocal = function reciprocal() { + var mul = numeric.mul, div = numeric.div; + if(this.y) { + var d = numeric.add(mul(this.x,this.x),mul(this.y,this.y)); + return new numeric.T(div(this.x,d),div(numeric.neg(this.y),d)); + } + return new T(div(1,this.x)); +} +numeric.T.prototype.div = function div(y) { + if(!(y instanceof numeric.T)) y = new numeric.T(y); + if(y.y) { return this.mul(y.reciprocal()); } + var div = numeric.div; + if(this.y) { return new numeric.T(div(this.x,y.x),div(this.y,y.x)); } + return new numeric.T(div(this.x,y.x)); +} +numeric.T.prototype.dot = numeric.Tbinop( + 'dot(x.x,y.x)', + 'dot(x.x,y.x),dot(x.x,y.y)', + 'dot(x.x,y.x),dot(x.y,y.x)', + 'sub(dot(x.x,y.x),dot(x.y,y.y)),add(dot(x.x,y.y),dot(x.y,y.x))' + ); +numeric.T.prototype.transpose = function transpose() { + var t = numeric.transpose, x = this.x, y = this.y; + if(y) { return new numeric.T(t(x),t(y)); } + return new numeric.T(t(x)); +} +numeric.T.prototype.transjugate = function transjugate() { + var t = numeric.transpose, x = this.x, y = this.y; + if(y) { return new numeric.T(t(x),numeric.negtranspose(y)); } + return new numeric.T(t(x)); +} +numeric.Tunop = function Tunop(r,c,s) { + if(typeof s !== "string") { s = ''; } + return Function( + 'var x = this;\n'+ + s+'\n'+ + 'if(x.y) {'+ + ' '+c+';\n'+ + '}\n'+ + r+';\n' + ); +} + +numeric.T.prototype.exp = numeric.Tunop( + 'return new numeric.T(ex)', + 'return new numeric.T(mul(cos(x.y),ex),mul(sin(x.y),ex))', + 'var ex = numeric.exp(x.x), cos = numeric.cos, sin = numeric.sin, mul = numeric.mul;'); +numeric.T.prototype.conj = numeric.Tunop( + 'return new numeric.T(x.x);', + 'return new numeric.T(x.x,numeric.neg(x.y));'); +numeric.T.prototype.neg = numeric.Tunop( + 'return new numeric.T(neg(x.x));', + 'return new numeric.T(neg(x.x),neg(x.y));', + 'var neg = numeric.neg;'); +numeric.T.prototype.sin = numeric.Tunop( + 'return new numeric.T(numeric.sin(x.x))', + 'return x.exp().sub(x.neg().exp()).div(new numeric.T(0,2));'); +numeric.T.prototype.cos = numeric.Tunop( + 'return new numeric.T(numeric.cos(x.x))', + 'return x.exp().add(x.neg().exp()).div(2);'); +numeric.T.prototype.abs = numeric.Tunop( + 'return new numeric.T(numeric.abs(x.x));', + 'return new numeric.T(numeric.sqrt(numeric.add(mul(x.x,x.x),mul(x.y,x.y))));', + 'var mul = numeric.mul;'); +numeric.T.prototype.log = numeric.Tunop( + 'return new numeric.T(numeric.log(x.x));', + 'var theta = new numeric.T(numeric.atan2(x.y,x.x)), r = x.abs();\n'+ + 'return new numeric.T(numeric.log(r.x),theta.x);'); +numeric.T.prototype.norm2 = numeric.Tunop( + 'return numeric.norm2(x.x);', + 'var f = numeric.norm2Squared;\n'+ + 'return Math.sqrt(f(x.x)+f(x.y));'); +numeric.T.prototype.inv = function inv() { + var A = this; + if(typeof A.y === "undefined") { return new numeric.T(numeric.inv(A.x)); } + var n = A.x.length, i, j, k; + var Rx = numeric.identity(n),Ry = numeric.rep([n,n],0); + var Ax = numeric.clone(A.x), Ay = numeric.clone(A.y); + var Aix, Aiy, Ajx, Ajy, Rix, Riy, Rjx, Rjy; + var i,j,k,d,d1,ax,ay,bx,by,temp; + for(i=0;i d) { k=j; d = d1; } + } + if(k!==i) { + temp = Ax[i]; Ax[i] = Ax[k]; Ax[k] = temp; + temp = Ay[i]; Ay[i] = Ay[k]; Ay[k] = temp; + temp = Rx[i]; Rx[i] = Rx[k]; Rx[k] = temp; + temp = Ry[i]; Ry[i] = Ry[k]; Ry[k] = temp; + } + Aix = Ax[i]; Aiy = Ay[i]; + Rix = Rx[i]; Riy = Ry[i]; + ax = Aix[i]; ay = Aiy[i]; + for(j=i+1;j0;i--) { + Rix = Rx[i]; Riy = Ry[i]; + for(j=i-1;j>=0;j--) { + Rjx = Rx[j]; Rjy = Ry[j]; + ax = Ax[j][i]; ay = Ay[j][i]; + for(k=n-1;k>=0;k--) { + bx = Rix[k]; by = Riy[k]; + Rjx[k] -= ax*bx - ay*by; + Rjy[k] -= ax*by + ay*bx; + } + } + } + return new numeric.T(Rx,Ry); +} +numeric.T.prototype.get = function get(i) { + var x = this.x, y = this.y, k = 0, ik, n = i.length; + if(y) { + while(k= 0 ? 1 : -1; + var alpha = s*numeric.norm2(x); + v[0] += alpha; + var foo = numeric.norm2(v); + if(foo === 0) { /* this should not happen */ throw new Error('eig: internal error'); } + return numeric.div(v,foo); +} + +numeric.toUpperHessenberg = function toUpperHessenberg(me) { + var s = numeric.dim(me); + if(s.length !== 2 || s[0] !== s[1]) { throw new Error('numeric: toUpperHessenberg() only works on square matrices'); } + var m = s[0], i,j,k,x,v,A = numeric.clone(me),B,C,Ai,Ci,Q = numeric.identity(m),Qi; + for(j=0;j0) { + v = numeric.house(x); + B = numeric.getBlock(A,[j+1,j],[m-1,m-1]); + C = numeric.tensor(v,numeric.dot(v,B)); + for(i=j+1;i=4*det) { + var s1,s2; + s1 = 0.5*(tr+Math.sqrt(tr*tr-4*det)); + s2 = 0.5*(tr-Math.sqrt(tr*tr-4*det)); + Hloc = numeric.add(numeric.sub(numeric.dot(Hloc,Hloc), + numeric.mul(Hloc,s1+s2)), + numeric.diag(numeric.rep([3],s1*s2))); + } else { + Hloc = numeric.add(numeric.sub(numeric.dot(Hloc,Hloc), + numeric.mul(Hloc,tr)), + numeric.diag(numeric.rep([3],det))); + } + x = [Hloc[0][0],Hloc[1][0],Hloc[2][0]]; + v = numeric.house(x); + B = [H[0],H[1],H[2]]; + C = numeric.tensor(v,numeric.dot(v,B)); + for(i=0;i<3;i++) { Hi = H[i]; Ci = C[i]; for(k=0;k=0) { + if(p1<0) x = -0.5*(p1-sqrt(disc)); + else x = -0.5*(p1+sqrt(disc)); + n1 = (a-x)*(a-x)+b*b; + n2 = c*c+(d-x)*(d-x); + if(n1>n2) { + n1 = sqrt(n1); + p = (a-x)/n1; + q = b/n1; + } else { + n2 = sqrt(n2); + p = c/n2; + q = (d-x)/n2; + } + Q0 = new T([[q,-p],[p,q]]); + Q.setRows(i,j,Q0.dot(Q.getRows(i,j))); + } else { + x = -0.5*p1; + y = 0.5*sqrt(-disc); + n1 = (a-x)*(a-x)+b*b; + n2 = c*c+(d-x)*(d-x); + if(n1>n2) { + n1 = sqrt(n1+y*y); + p = (a-x)/n1; + q = b/n1; + x = 0; + y /= n1; + } else { + n2 = sqrt(n2+y*y); + p = c/n2; + q = (d-x)/n2; + x = y/n2; + y = 0; + } + Q0 = new T([[q,-p],[p,q]],[[x,y],[y,-x]]); + Q.setRows(i,j,Q0.dot(Q.getRows(i,j))); + } + } + } + var R = Q.dot(A).dot(Q.transjugate()), n = A.length, E = numeric.T.identity(n); + for(j=0;j0) { + for(k=j-1;k>=0;k--) { + var Rk = R.get([k,k]), Rj = R.get([j,j]); + if(numeric.neq(Rk.x,Rj.x) || numeric.neq(Rk.y,Rj.y)) { + x = R.getRow(k).getBlock([k],[j-1]); + y = E.getRow(j).getBlock([k],[j-1]); + E.set([j,k],(R.get([k,j]).neg().sub(x.dot(y))).div(Rk.sub(Rj))); + } else { + E.setRow(j,E.getRow(k)); + continue; + } + } + } + } + for(j=0;j=counts.length) counts[counts.length] = 0; + if(foo[j]!==0) counts[j]++; + } + } + var n = counts.length; + var Ai = Array(n+1); + Ai[0] = 0; + for(i=0;i= k11) { + xj[n] = j[m]; + if(m===0) return; + ++n; + --m; + km = k[m]; + k11 = k1[m]; + } else { + foo = Pinv[Aj[km]]; + if(x[foo] === 0) { + x[foo] = 1; + k[m] = km; + ++m; + j[m] = foo; + km = Ai[foo]; + k1[m] = k11 = Ai[foo+1]; + } else ++km; + } + } +} +numeric.ccsLPSolve = function ccsLPSolve(A,B,x,xj,I,Pinv,dfs) { + var Ai = A[0], Aj = A[1], Av = A[2],m = Ai.length-1, n=0; + var Bi = B[0], Bj = B[1], Bv = B[2]; + + var i,i0,i1,j,J,j0,j1,k,l,l0,l1,a; + i0 = Bi[I]; + i1 = Bi[I+1]; + xj.length = 0; + for(i=i0;i a) { e = k; a = c; } + } + if(abs(x[i])= k11) { + xj[n] = Pinv[j[m]]; + if(m===0) return; + ++n; + --m; + km = k[m]; + k11 = k1[m]; + } else { + foo = Aj[km]; + if(x[foo] === 0) { + x[foo] = 1; + k[m] = km; + ++m; + j[m] = foo; + foo = Pinv[foo]; + km = Ai[foo]; + k1[m] = k11 = Ai[foo+1]; + } else ++km; + } + } +} +numeric.ccsLPSolve0 = function ccsLPSolve0(A,B,y,xj,I,Pinv,P,dfs) { + var Ai = A[0], Aj = A[1], Av = A[2],m = Ai.length-1, n=0; + var Bi = B[0], Bj = B[1], Bv = B[2]; + + var i,i0,i1,j,J,j0,j1,k,l,l0,l1,a; + i0 = Bi[I]; + i1 = Bi[I+1]; + xj.length = 0; + for(i=i0;i a) { e = k; a = c; } + } + if(abs(y[P[i]]) ret[k]) ret[k] = A.length; + var i; + for(i in A) { + if(A.hasOwnProperty(i)) dim(A[i],ret,k+1); + } + return ret; +}; + +numeric.sclone = function clone(A,k,n) { + if(typeof k === "undefined") { k=0; } + if(typeof n === "undefined") { n = numeric.sdim(A).length; } + var i,ret = Array(A.length); + if(k === n-1) { + for(i in A) { if(A.hasOwnProperty(i)) ret[i] = A[i]; } + return ret; + } + for(i in A) { + if(A.hasOwnProperty(i)) ret[i] = clone(A[i],k+1,n); + } + return ret; +} + +numeric.sdiag = function diag(d) { + var n = d.length,i,ret = Array(n),i1,i2,i3; + for(i=n-1;i>=1;i-=2) { + i1 = i-1; + ret[i] = []; ret[i][i] = d[i]; + ret[i1] = []; ret[i1][i1] = d[i1]; + } + if(i===0) { ret[0] = []; ret[0][0] = d[i]; } + return ret; +} + +numeric.sidentity = function identity(n) { return numeric.sdiag(numeric.rep([n],1)); } + +numeric.stranspose = function transpose(A) { + var ret = [], n = A.length, i,j,Ai; + for(i in A) { + if(!(A.hasOwnProperty(i))) continue; + Ai = A[i]; + for(j in Ai) { + if(!(Ai.hasOwnProperty(j))) continue; + if(typeof ret[j] !== "object") { ret[j] = []; } + ret[j][i] = Ai[j]; + } + } + return ret; +} + +numeric.sLUP = function LUP(A,tol) { + throw new Error("The function numeric.sLUP had a bug in it and has been removed. Please use the new numeric.ccsLUP function instead."); +}; + +numeric.sdotMM = function dotMM(A,B) { + var p = A.length, q = B.length, BT = numeric.stranspose(B), r = BT.length, Ai, BTk; + var i,j,k,accum; + var ret = Array(p),reti; + for(i=p-1;i>=0;i--) { + reti = []; + Ai = A[i]; + for(k=r-1;k>=0;k--) { + accum = 0; + BTk = BT[k]; + for(j in Ai) { + if(!(Ai.hasOwnProperty(j))) continue; + if(j in BTk) { accum += Ai[j]*BTk[j]; } + } + if(accum) reti[k] = accum; + } + ret[i] = reti; + } + return ret; +} + +numeric.sdotMV = function dotMV(A,x) { + var p = A.length, Ai, i,j; + var ret = Array(p), accum; + for(i=p-1;i>=0;i--) { + Ai = A[i]; + accum = 0; + for(j in Ai) { + if(!(Ai.hasOwnProperty(j))) continue; + if(x[j]) accum += Ai[j]*x[j]; + } + if(accum) ret[i] = accum; + } + return ret; +} + +numeric.sdotVM = function dotMV(x,A) { + var i,j,Ai,alpha; + var ret = [], accum; + for(i in x) { + if(!x.hasOwnProperty(i)) continue; + Ai = A[i]; + alpha = x[i]; + for(j in Ai) { + if(!Ai.hasOwnProperty(j)) continue; + if(!ret[j]) { ret[j] = 0; } + ret[j] += alpha*Ai[j]; + } + } + return ret; +} + +numeric.sdotVV = function dotVV(x,y) { + var i,ret=0; + for(i in x) { if(x[i] && y[i]) ret+= x[i]*y[i]; } + return ret; +} + +numeric.sdot = function dot(A,B) { + var m = numeric.sdim(A).length, n = numeric.sdim(B).length; + var k = m*1000+n; + switch(k) { + case 0: return A*B; + case 1001: return numeric.sdotVV(A,B); + case 2001: return numeric.sdotMV(A,B); + case 1002: return numeric.sdotVM(A,B); + case 2002: return numeric.sdotMM(A,B); + default: throw new Error('numeric.sdot not implemented for tensors of order '+m+' and '+n); + } +} + +numeric.sscatter = function scatter(V) { + var n = V[0].length, Vij, i, j, m = V.length, A = [], Aj; + for(i=n-1;i>=0;--i) { + if(!V[m-1][i]) continue; + Aj = A; + for(j=0;j=0;--i) ret[i] = []; + } + for(i=n;i>=0;--i) ret[i].push(k[i]); + ret[n+1].push(Ai); + } + } else gather(Ai,ret,k); + } + } + if(k.length>n) k.pop(); + return ret; +} + +// 6. Coordinate matrices +numeric.cLU = function LU(A) { + var I = A[0], J = A[1], V = A[2]; + var p = I.length, m=0, i,j,k,a,b,c; + for(i=0;im) m=I[i]; + m++; + var L = Array(m), U = Array(m), left = numeric.rep([m],Infinity), right = numeric.rep([m],-Infinity); + var Ui, Uj,alpha; + for(k=0;kright[i]) right[i] = j; + } + for(i=0;i right[i+1]) right[i+1] = right[i]; } + for(i=m-1;i>=1;i--) { if(left[i]=0;i--) { + while(Uj[k] > i) { + ret[i] -= Uv[k]*ret[Uj[k]]; + k--; + } + ret[i] /= Uv[k]; + k--; + } + return ret; +}; + +numeric.cgrid = function grid(n,shape) { + if(typeof n === "number") n = [n,n]; + var ret = numeric.rep(n,-1); + var i,j,count; + if(typeof shape !== "function") { + switch(shape) { + case 'L': + shape = function(i,j) { return (i>=n[0]/2 || jN) N = Ai[k]; } + N++; + ret = numeric.rep([N],0); + for(k=0;k1) { + mid = floor((p+q)/2); + if(x[mid] <= x0) p = mid; + else q = mid; + } + return this._at(x0,p); + } + var n = x0.length, i, ret = Array(n); + for(i=n-1;i!==-1;--i) ret[i] = this.at(x0[i]); + return ret; +} +numeric.Spline.prototype.diff = function diff() { + var x = this.x; + var yl = this.yl; + var yr = this.yr; + var kl = this.kl; + var kr = this.kr; + var n = yl.length; + var i,dx,dy; + var zl = kl, zr = kr, pl = Array(n), pr = Array(n); + var add = numeric.add, mul = numeric.mul, div = numeric.div, sub = numeric.sub; + for(i=n-1;i!==-1;--i) { + dx = x[i+1]-x[i]; + dy = sub(yr[i+1],yl[i]); + pl[i] = div(add(mul(dy, 6),mul(kl[i],-4*dx),mul(kr[i+1],-2*dx)),dx*dx); + pr[i+1] = div(add(mul(dy,-6),mul(kl[i], 2*dx),mul(kr[i+1], 4*dx)),dx*dx); + } + return new numeric.Spline(x,zl,zr,pl,pr); +} +numeric.Spline.prototype.roots = function roots() { + function sqr(x) { return x*x; } + function heval(y0,y1,k0,k1,x) { + var A = k0*2-(y1-y0); + var B = -k1*2+(y1-y0); + var t = (x+1)*0.5; + var s = t*(1-t); + return (1-t)*y0+t*y1+A*s*(1-t)+B*s*t; + } + var ret = []; + var x = this.x, yl = this.yl, yr = this.yr, kl = this.kl, kr = this.kr; + if(typeof yl[0] === "number") { + yl = [yl]; + yr = [yr]; + kl = [kl]; + kr = [kr]; + } + var m = yl.length,n=x.length-1,i,j,k,y,s,t; + var ai,bi,ci,di, ret = Array(m),ri,k0,k1,y0,y1,A,B,D,dx,cx,stops,z0,z1,zm,t0,t1,tm; + var sqrt = Math.sqrt; + for(i=0;i!==m;++i) { + ai = yl[i]; + bi = yr[i]; + ci = kl[i]; + di = kr[i]; + ri = []; + for(j=0;j!==n;j++) { + if(j>0 && bi[j]*ai[j]<0) ri.push(x[j]); + dx = (x[j+1]-x[j]); + cx = x[j]; + y0 = ai[j]; + y1 = bi[j+1]; + k0 = ci[j]/dx; + k1 = di[j+1]/dx; + D = sqr(k0-k1+3*(y0-y1)) + 12*k1*y0; + A = k1+3*y0+2*k0-3*y1; + B = 3*(k1+k0+2*(y0-y1)); + if(D<=0) { + z0 = A/B; + if(z0>x[j] && z0x[j] && z0x[j] && z10) { + t0 = t1; + z0 = z1; + continue; + } + var side = 0; + while(1) { + tm = (z0*t1-z1*t0)/(z0-z1); + if(tm <= t0 || tm >= t1) { break; } + zm = this._at(tm,j); + if(zm*z1>0) { + t1 = tm; + z1 = zm; + if(side === -1) z0*=0.5; + side = -1; + } else if(zm*z0>0) { + t0 = tm; + z0 = zm; + if(side === 1) z1*=0.5; + side = 1; + } else break; + } + ri.push(tm); + t0 = stops[k+1]; + z0 = this._at(t0, j); + } + if(z1 === 0) ri.push(t1); + } + ret[i] = ri; + } + if(typeof this.yl[0] === "number") return ret[0]; + return ret; +} +numeric.spline = function spline(x,y,k1,kn) { + var n = x.length, b = [], dx = [], dy = []; + var i; + var sub = numeric.sub,mul = numeric.mul,add = numeric.add; + for(i=n-2;i>=0;i--) { dx[i] = x[i+1]-x[i]; dy[i] = sub(y[i+1],y[i]); } + if(typeof k1 === "string" || typeof kn === "string") { + k1 = kn = "periodic"; + } + // Build sparse tridiagonal system + var T = [[],[],[]]; + switch(typeof k1) { + case "undefined": + b[0] = mul(3/(dx[0]*dx[0]),dy[0]); + T[0].push(0,0); + T[1].push(0,1); + T[2].push(2/dx[0],1/dx[0]); + break; + case "string": + b[0] = add(mul(3/(dx[n-2]*dx[n-2]),dy[n-2]),mul(3/(dx[0]*dx[0]),dy[0])); + T[0].push(0,0,0); + T[1].push(n-2,0,1); + T[2].push(1/dx[n-2],2/dx[n-2]+2/dx[0],1/dx[0]); + break; + default: + b[0] = k1; + T[0].push(0); + T[1].push(0); + T[2].push(1); + break; + } + for(i=1;i20) { throw new Error("Numerical gradient fails"); } + x0[i] = x[i]+h; + f1 = f(x0); + x0[i] = x[i]-h; + f2 = f(x0); + x0[i] = x[i]; + if(isNaN(f1) || isNaN(f2)) { h/=16; continue; } + J[i] = (f1-f2)/(2*h); + t0 = x[i]-h; + t1 = x[i]; + t2 = x[i]+h; + d1 = (f1-f0)/h; + d2 = (f0-f2)/h; + N = max(abs(J[i]),abs(f0),abs(f1),abs(f2),abs(t0),abs(t1),abs(t2),1e-8); + errest = min(max(abs(d1-J[i]),abs(d2-J[i]),abs(d1-d2))/N,h/N); + if(errest>eps) { h/=16; } + else break; + } + } + return J; +} + +numeric.uncmin = function uncmin(f,x0,tol,gradient,maxit,callback,options) { + var grad = numeric.gradient; + if(typeof options === "undefined") { options = {}; } + if(typeof tol === "undefined") { tol = 1e-8; } + if(typeof gradient === "undefined") { gradient = function(x) { return grad(f,x); }; } + if(typeof maxit === "undefined") maxit = 1000; + x0 = numeric.clone(x0); + var n = x0.length; + var f0 = f(x0),f1,df0; + if(isNaN(f0)) throw new Error('uncmin: f(x0) is a NaN!'); + var max = Math.max, norm2 = numeric.norm2; + tol = max(tol,numeric.epsilon); + var step,g0,g1,H1 = options.Hinv || numeric.identity(n); + var dot = numeric.dot, inv = numeric.inv, sub = numeric.sub, add = numeric.add, ten = numeric.tensor, div = numeric.div, mul = numeric.mul; + var all = numeric.all, isfinite = numeric.isFinite, neg = numeric.neg; + var it=0,i,s,x1,y,Hy,Hs,ys,i0,t,nstep,t1,t2; + var msg = ""; + g0 = gradient(x0); + while(it= 0.1*t*df0 || isNaN(f1)) { + t *= 0.5; + ++it; + continue; + } + break; + } + if(t*nstep < tol) { msg = "Line search step size smaller than tol"; break; } + if(it === maxit) { msg = "maxit reached during line search"; break; } + g1 = gradient(x1); + y = sub(g1,g0); + ys = dot(y,s); + Hy = dot(H1,y); + H1 = sub(add(H1, + mul( + (ys+dot(y,Hy))/(ys*ys), + ten(s,s) )), + div(add(ten(Hy,s),ten(s,Hy)),ys)); + x0 = x1; + f0 = f1; + g0 = g1; + ++it; + } + return {solution: x0, f: f0, gradient: g0, invHessian: H1, iterations:it, message: msg}; +} + +// 10. Ode solver (Dormand-Prince) +numeric.Dopri = function Dopri(x,y,f,ymid,iterations,msg,events) { + this.x = x; + this.y = y; + this.f = f; + this.ymid = ymid; + this.iterations = iterations; + this.events = events; + this.message = msg; +} +numeric.Dopri.prototype._at = function _at(xi,j) { + function sqr(x) { return x*x; } + var sol = this; + var xs = sol.x; + var ys = sol.y; + var k1 = sol.f; + var ymid = sol.ymid; + var n = xs.length; + var x0,x1,xh,y0,y1,yh,xi; + var floor = Math.floor,h; + var c = 0.5; + var add = numeric.add, mul = numeric.mul,sub = numeric.sub, p,q,w; + x0 = xs[j]; + x1 = xs[j+1]; + y0 = ys[j]; + y1 = ys[j+1]; + h = x1-x0; + xh = x0+c*h; + yh = ymid[j]; + p = sub(k1[j ],mul(y0,1/(x0-xh)+2/(x0-x1))); + q = sub(k1[j+1],mul(y1,1/(x1-xh)+2/(x1-x0))); + w = [sqr(xi - x1) * (xi - xh) / sqr(x0 - x1) / (x0 - xh), + sqr(xi - x0) * sqr(xi - x1) / sqr(x0 - xh) / sqr(x1 - xh), + sqr(xi - x0) * (xi - xh) / sqr(x1 - x0) / (x1 - xh), + (xi - x0) * sqr(xi - x1) * (xi - xh) / sqr(x0-x1) / (x0 - xh), + (xi - x1) * sqr(xi - x0) * (xi - xh) / sqr(x0-x1) / (x1 - xh)]; + return add(add(add(add(mul(y0,w[0]), + mul(yh,w[1])), + mul(y1,w[2])), + mul( p,w[3])), + mul( q,w[4])); +} +numeric.Dopri.prototype.at = function at(x) { + var i,j,k,floor = Math.floor; + if(typeof x !== "number") { + var n = x.length, ret = Array(n); + for(i=n-1;i!==-1;--i) { + ret[i] = this.at(x[i]); + } + return ret; + } + var x0 = this.x; + i = 0; j = x0.length-1; + while(j-i>1) { + k = floor(0.5*(i+j)); + if(x0[k] <= x) i = k; + else j = k; + } + return this._at(x,i); +} + +numeric.dopri = function dopri(x0,x1,y0,f,tol,maxit,event) { + if(typeof tol === "undefined") { tol = 1e-6; } + if(typeof maxit === "undefined") { maxit = 1000; } + var xs = [x0], ys = [y0], k1 = [f(x0,y0)], k2,k3,k4,k5,k6,k7, ymid = []; + var A2 = 1/5; + var A3 = [3/40,9/40]; + var A4 = [44/45,-56/15,32/9]; + var A5 = [19372/6561,-25360/2187,64448/6561,-212/729]; + var A6 = [9017/3168,-355/33,46732/5247,49/176,-5103/18656]; + var b = [35/384,0,500/1113,125/192,-2187/6784,11/84]; + var bm = [0.5*6025192743/30085553152, + 0, + 0.5*51252292925/65400821598, + 0.5*-2691868925/45128329728, + 0.5*187940372067/1594534317056, + 0.5*-1776094331/19743644256, + 0.5*11237099/235043384]; + var c = [1/5,3/10,4/5,8/9,1,1]; + var e = [-71/57600,0,71/16695,-71/1920,17253/339200,-22/525,1/40]; + var i = 0,er,j; + var h = (x1-x0)/10; + var it = 0; + var add = numeric.add, mul = numeric.mul, y1,erinf; + var max = Math.max, min = Math.min, abs = Math.abs, norminf = numeric.norminf,pow = Math.pow; + var any = numeric.any, lt = numeric.lt, and = numeric.and, sub = numeric.sub; + var e0, e1, ev; + var ret = new numeric.Dopri(xs,ys,k1,ymid,-1,""); + if(typeof event === "function") e0 = event(x0,y0); + while(x0x1) h = x1-x0; + k2 = f(x0+c[0]*h, add(y0,mul( A2*h,k1[i]))); + k3 = f(x0+c[1]*h, add(add(y0,mul(A3[0]*h,k1[i])),mul(A3[1]*h,k2))); + k4 = f(x0+c[2]*h, add(add(add(y0,mul(A4[0]*h,k1[i])),mul(A4[1]*h,k2)),mul(A4[2]*h,k3))); + k5 = f(x0+c[3]*h, add(add(add(add(y0,mul(A5[0]*h,k1[i])),mul(A5[1]*h,k2)),mul(A5[2]*h,k3)),mul(A5[3]*h,k4))); + k6 = f(x0+c[4]*h,add(add(add(add(add(y0,mul(A6[0]*h,k1[i])),mul(A6[1]*h,k2)),mul(A6[2]*h,k3)),mul(A6[3]*h,k4)),mul(A6[4]*h,k5))); + y1 = add(add(add(add(add(y0,mul(k1[i],h*b[0])),mul(k3,h*b[2])),mul(k4,h*b[3])),mul(k5,h*b[4])),mul(k6,h*b[5])); + k7 = f(x0+h,y1); + er = add(add(add(add(add(mul(k1[i],h*e[0]),mul(k3,h*e[2])),mul(k4,h*e[3])),mul(k5,h*e[4])),mul(k6,h*e[5])),mul(k7,h*e[6])); + if(typeof er === "number") erinf = abs(er); + else erinf = norminf(er); + if(erinf > tol) { // reject + h = 0.2*h*pow(tol/erinf,0.25); + if(x0+h === x0) { + ret.msg = "Step size became too small"; + break; + } + continue; + } + ymid[i] = add(add(add(add(add(add(y0, + mul(k1[i],h*bm[0])), + mul(k3 ,h*bm[2])), + mul(k4 ,h*bm[3])), + mul(k5 ,h*bm[4])), + mul(k6 ,h*bm[5])), + mul(k7 ,h*bm[6])); + ++i; + xs[i] = x0+h; + ys[i] = y1; + k1[i] = k7; + if(typeof event === "function") { + var yi,xl = x0,xr = x0+0.5*h,xi; + e1 = event(xr,ymid[i-1]); + ev = and(lt(e0,0),lt(0,e1)); + if(!any(ev)) { xl = xr; xr = x0+h; e0 = e1; e1 = event(xr,y1); ev = and(lt(e0,0),lt(0,e1)); } + if(any(ev)) { + var xc, yc, en,ei; + var side=0, sl = 1.0, sr = 1.0; + while(1) { + if(typeof e0 === "number") xi = (sr*e1*xl-sl*e0*xr)/(sr*e1-sl*e0); + else { + xi = xr; + for(j=e0.length-1;j!==-1;--j) { + if(e0[j]<0 && e1[j]>0) xi = min(xi,(sr*e1[j]*xl-sl*e0[j]*xr)/(sr*e1[j]-sl*e0[j])); + } + } + if(xi <= xl || xi >= xr) break; + yi = ret._at(xi, i-1); + ei = event(xi,yi); + en = and(lt(e0,0),lt(0,ei)); + if(any(en)) { + xr = xi; + e1 = ei; + ev = en; + sr = 1.0; + if(side === -1) sl *= 0.5; + else sl = 1.0; + side = -1; + } else { + xl = xi; + e0 = ei; + sl = 1.0; + if(side === 1) sr *= 0.5; + else sr = 1.0; + side = 1; + } + } + y1 = ret._at(0.5*(x0+xi),i-1); + ret.f[i] = f(xi,yi); + ret.x[i] = xi; + ret.y[i] = yi; + ret.ymid[i-1] = y1; + ret.events = ev; + ret.iterations = it; + return ret; + } + } + x0 += h; + y0 = y1; + e0 = e1; + h = min(0.8*h*pow(tol/erinf,0.25),4*h); + } + ret.iterations = it; + return ret; +} + +// 11. Ax = b +numeric.LU = function(A, fast) { + fast = fast || false; + + var abs = Math.abs; + var i, j, k, absAjk, Akk, Ak, Pk, Ai; + var max; + var n = A.length, n1 = n-1; + var P = new Array(n); + if(!fast) A = numeric.clone(A); + + for (k = 0; k < n; ++k) { + Pk = k; + Ak = A[k]; + max = abs(Ak[k]); + for (j = k + 1; j < n; ++j) { + absAjk = abs(A[j][k]); + if (max < absAjk) { + max = absAjk; + Pk = j; + } + } + P[k] = Pk; + + if (Pk != k) { + A[k] = A[Pk]; + A[Pk] = Ak; + Ak = A[k]; + } + + Akk = Ak[k]; + + for (i = k + 1; i < n; ++i) { + A[i][k] /= Akk; + } + + for (i = k + 1; i < n; ++i) { + Ai = A[i]; + for (j = k + 1; j < n1; ++j) { + Ai[j] -= Ai[k] * Ak[j]; + ++j; + Ai[j] -= Ai[k] * Ak[j]; + } + if(j===n1) Ai[j] -= Ai[k] * Ak[j]; + } + } + + return { + LU: A, + P: P + }; +} + +numeric.LUsolve = function LUsolve(LUP, b) { + var i, j; + var LU = LUP.LU; + var n = LU.length; + var x = numeric.clone(b); + var P = LUP.P; + var Pi, LUi, LUii, tmp; + + for (i=n-1;i!==-1;--i) x[i] = b[i]; + for (i = 0; i < n; ++i) { + Pi = P[i]; + if (P[i] !== i) { + tmp = x[i]; + x[i] = x[Pi]; + x[Pi] = tmp; + } + + LUi = LU[i]; + for (j = 0; j < i; ++j) { + x[i] -= x[j] * LUi[j]; + } + } + + for (i = n - 1; i >= 0; --i) { + LUi = LU[i]; + for (j = i + 1; j < n; ++j) { + x[i] -= x[j] * LUi[j]; + } + + x[i] /= LUi[i]; + } + + return x; +} + +numeric.solve = function solve(A,b,fast) { return numeric.LUsolve(numeric.LU(A,fast), b); } + +// 12. Linear programming +numeric.echelonize = function echelonize(A) { + var s = numeric.dim(A), m = s[0], n = s[1]; + var I = numeric.identity(m); + var P = Array(m); + var i,j,k,l,Ai,Ii,Z,a; + var abs = Math.abs; + var diveq = numeric.diveq; + A = numeric.clone(A); + for(i=0;ia1) alpha = a1; + g = add(c,mul(alpha,p)); + H = dot(A1,A0); + for(i=m-1;i!==-1;--i) H[i][i] += 1; + d = solve(H,div(g,alpha),true); + var t0 = div(z,dot(A,d)); + var t = 1.0; + for(i=n-1;i!==-1;--i) if(t0[i]<0) t = min(t,-0.999*t0[i]); + y = sub(x,mul(d,t)); + z = sub(b,dot(A,y)); + if(!all(gt(z,0))) return { solution: x, message: "", iterations: count }; + x = y; + if(alpha=0) unbounded = false; + else unbounded = true; + } + if(unbounded) return { solution: y, message: "Unbounded", iterations: count }; + } + return { solution: x, message: "maximum iteration count exceeded", iterations:count }; +} + +numeric._solveLP = function _solveLP(c,A,b,tol,maxit) { + var m = c.length, n = b.length,y; + var sum = numeric.sum, log = numeric.log, mul = numeric.mul, sub = numeric.sub, dot = numeric.dot, div = numeric.div, add = numeric.add; + var c0 = numeric.rep([m],0).concat([1]); + var J = numeric.rep([n,1],-1); + var A0 = numeric.blockMatrix([[A , J ]]); + var b0 = b; + var y = numeric.rep([m],0).concat(Math.max(0,numeric.sup(numeric.neg(b)))+1); + var x0 = numeric.__solveLP(c0,A0,b0,tol,maxit,y,false); + var x = numeric.clone(x0.solution); + x.length = m; + var foo = numeric.inf(sub(b,dot(A,x))); + if(foo<0) { return { solution: NaN, message: "Infeasible", iterations: x0.iterations }; } + var ret = numeric.__solveLP(c, A, b, tol, maxit-x0.iterations, x, true); + ret.iterations += x0.iterations; + return ret; +}; + +numeric.solveLP = function solveLP(c,A,b,Aeq,beq,tol,maxit) { + if(typeof maxit === "undefined") maxit = 1000; + if(typeof tol === "undefined") tol = numeric.epsilon; + if(typeof Aeq === "undefined") return numeric._solveLP(c,A,b,tol,maxit); + var m = Aeq.length, n = Aeq[0].length, o = A.length; + var B = numeric.echelonize(Aeq); + var flags = numeric.rep([n],0); + var P = B.P; + var Q = []; + var i; + for(i=P.length-1;i!==-1;--i) flags[P[i]] = 1; + for(i=n-1;i!==-1;--i) if(flags[i]===0) Q.push(i); + var g = numeric.getRange; + var I = numeric.linspace(0,m-1), J = numeric.linspace(0,o-1); + var Aeq2 = g(Aeq,I,Q), A1 = g(A,J,P), A2 = g(A,J,Q), dot = numeric.dot, sub = numeric.sub; + var A3 = dot(A1,B.I); + var A4 = sub(A2,dot(A3,Aeq2)), b4 = sub(b,dot(A3,beq)); + var c1 = Array(P.length), c2 = Array(Q.length); + for(i=P.length-1;i!==-1;--i) c1[i] = c[P[i]]; + for(i=Q.length-1;i!==-1;--i) c2[i] = c[Q[i]]; + var c4 = sub(c2,dot(c1,dot(B.I,Aeq2))); + var S = numeric._solveLP(c4,A4,b4,tol,maxit); + var x2 = S.solution; + if(x2!==x2) return S; + var x1 = dot(B.I,sub(beq,dot(Aeq2,x2))); + var x = Array(c.length); + for(i=P.length-1;i!==-1;--i) x[P[i]] = x1[i]; + for(i=Q.length-1;i!==-1;--i) x[Q[i]] = x2[i]; + return { solution: x, message:S.message, iterations: S.iterations }; +} + +numeric.MPStoLP = function MPStoLP(MPS) { + if(MPS instanceof String) { MPS.split('\n'); } + var state = 0; + var states = ['Initial state','NAME','ROWS','COLUMNS','RHS','BOUNDS','ENDATA']; + var n = MPS.length; + var i,j,z,N=0,rows = {}, sign = [], rl = 0, vars = {}, nv = 0; + var name; + var c = [], A = [], b = []; + function err(e) { throw new Error('MPStoLP: '+e+'\nLine '+i+': '+MPS[i]+'\nCurrent state: '+states[state]+'\n'); } + for(i=0;i +// +// Math.seedrandom('yipee'); Sets Math.random to a function that is +// initialized using the given explicit seed. +// +// Math.seedrandom(); Sets Math.random to a function that is +// seeded using the current time, dom state, +// and other accumulated local entropy. +// The generated seed string is returned. +// +// Math.seedrandom('yowza', true); +// Seeds using the given explicit seed mixed +// together with accumulated entropy. +// +// +// Seeds using physical random bits downloaded +// from random.org. +// +// Seeds using urandom bits from call.jsonlib.com, +// which is faster than random.org. +// +// Examples: +// +// Math.seedrandom("hello"); // Use "hello" as the seed. +// document.write(Math.random()); // Always 0.5463663768140734 +// document.write(Math.random()); // Always 0.43973793770592234 +// var rng1 = Math.random; // Remember the current prng. +// +// var autoseed = Math.seedrandom(); // New prng with an automatic seed. +// document.write(Math.random()); // Pretty much unpredictable. +// +// Math.random = rng1; // Continue "hello" prng sequence. +// document.write(Math.random()); // Always 0.554769432473455 +// +// Math.seedrandom(autoseed); // Restart at the previous seed. +// document.write(Math.random()); // Repeat the 'unpredictable' value. +// +// Notes: +// +// Each time seedrandom('arg') is called, entropy from the passed seed +// is accumulated in a pool to help generate future seeds for the +// zero-argument form of Math.seedrandom, so entropy can be injected over +// time by calling seedrandom with explicit data repeatedly. +// +// On speed - This javascript implementation of Math.random() is about +// 3-10x slower than the built-in Math.random() because it is not native +// code, but this is typically fast enough anyway. Seeding is more expensive, +// especially if you use auto-seeding. Some details (timings on Chrome 4): +// +// Our Math.random() - avg less than 0.002 milliseconds per call +// seedrandom('explicit') - avg less than 0.5 milliseconds per call +// seedrandom('explicit', true) - avg less than 2 milliseconds per call +// seedrandom() - avg about 38 milliseconds per call +// +// LICENSE (BSD): +// +// Copyright 2010 David Bau, all rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// 2. 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. +// +// 3. Neither the name of this module 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. +// +/** + * All code is in an anonymous closure to keep the global namespace clean. + * + * @param {number=} overflow + * @param {number=} startdenom + */ + +// Patched by Seb so that seedrandom.js does not pollute the Math object. +// My tests suggest that doing Math.trouble = 1 makes Math lookups about 5% +// slower. +numeric.seedrandom = { pow:Math.pow, random:Math.random }; + +(function (pool, math, width, chunks, significance, overflow, startdenom) { + + +// +// seedrandom() +// This is the seedrandom function described above. +// +math['seedrandom'] = function seedrandom(seed, use_entropy) { + var key = []; + var arc4; + + // Flatten the seed string or build one from local entropy if needed. + seed = mixkey(flatten( + use_entropy ? [seed, pool] : + arguments.length ? seed : + [new Date().getTime(), pool, window], 3), key); + + // Use the seed to initialize an ARC4 generator. + arc4 = new ARC4(key); + + // Mix the randomness into accumulated entropy. + mixkey(arc4.S, pool); + + // Override Math.random + + // This function returns a random double in [0, 1) that contains + // randomness in every bit of the mantissa of the IEEE 754 value. + + math['random'] = function random() { // Closure to return a random double: + var n = arc4.g(chunks); // Start with a numerator n < 2 ^ 48 + var d = startdenom; // and denominator d = 2 ^ 48. + var x = 0; // and no 'extra last byte'. + while (n < significance) { // Fill up all significant digits by + n = (n + x) * width; // shifting numerator and + d *= width; // denominator and generating a + x = arc4.g(1); // new least-significant-byte. + } + while (n >= overflow) { // To avoid rounding up, before adding + n /= 2; // last byte, shift everything + d /= 2; // right using integer math until + x >>>= 1; // we have exactly the desired bits. + } + return (n + x) / d; // Form the number within [0, 1). + }; + + // Return the seed that was used + return seed; +}; + +// +// ARC4 +// +// An ARC4 implementation. The constructor takes a key in the form of +// an array of at most (width) integers that should be 0 <= x < (width). +// +// The g(count) method returns a pseudorandom integer that concatenates +// the next (count) outputs from ARC4. Its return value is a number x +// that is in the range 0 <= x < (width ^ count). +// +/** @constructor */ +function ARC4(key) { + var t, u, me = this, keylen = key.length; + var i = 0, j = me.i = me.j = me.m = 0; + me.S = []; + me.c = []; + + // The empty key [] is treated as [0]. + if (!keylen) { key = [keylen++]; } + + // Set up S using the standard key scheduling algorithm. + while (i < width) { me.S[i] = i++; } + for (i = 0; i < width; i++) { + t = me.S[i]; + j = lowbits(j + t + key[i % keylen]); + u = me.S[j]; + me.S[i] = u; + me.S[j] = t; + } + + // The "g" method returns the next (count) outputs as one number. + me.g = function getnext(count) { + var s = me.S; + var i = lowbits(me.i + 1); var t = s[i]; + var j = lowbits(me.j + t); var u = s[j]; + s[i] = u; + s[j] = t; + var r = s[lowbits(t + u)]; + while (--count) { + i = lowbits(i + 1); t = s[i]; + j = lowbits(j + t); u = s[j]; + s[i] = u; + s[j] = t; + r = r * width + s[lowbits(t + u)]; + } + me.i = i; + me.j = j; + return r; + }; + // For robust unpredictability discard an initial batch of values. + // See http://www.rsa.com/rsalabs/node.asp?id=2009 + me.g(width); +} + +// +// flatten() +// Converts an object tree to nested arrays of strings. +// +/** @param {Object=} result + * @param {string=} prop + * @param {string=} typ */ +function flatten(obj, depth, result, prop, typ) { + result = []; + typ = typeof(obj); + if (depth && typ == 'object') { + for (prop in obj) { + if (prop.indexOf('S') < 5) { // Avoid FF3 bug (local/sessionStorage) + try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {} + } + } + } + return (result.length ? result : obj + (typ != 'string' ? '\0' : '')); +} + +// +// mixkey() +// Mixes a string seed into a key that is an array of integers, and +// returns a shortened string seed that is equivalent to the result key. +// +/** @param {number=} smear + * @param {number=} j */ +function mixkey(seed, key, smear, j) { + seed += ''; // Ensure the seed is a string + smear = 0; + for (j = 0; j < seed.length; j++) { + key[lowbits(j)] = + lowbits((smear ^= key[lowbits(j)] * 19) + seed.charCodeAt(j)); + } + seed = ''; + for (j in key) { seed += String.fromCharCode(key[j]); } + return seed; +} + +// +// lowbits() +// A quick "n mod width" for width a power of 2. +// +function lowbits(n) { return n & (width - 1); } + +// +// The following constants are related to IEEE 754 limits. +// +startdenom = math.pow(width, chunks); +significance = math.pow(2, significance); +overflow = significance * 2; + +// +// When seedrandom.js is loaded, we immediately mix a few bits +// from the built-in RNG into the entropy pool. Because we do +// not want to intefere with determinstic PRNG state later, +// seedrandom will not call math.random on its own again after +// initialization. +// +mixkey(math.random(), pool); + +// End anonymous scope, and pass initial values. +}( + [], // pool: entropy pool starts empty + numeric.seedrandom, // math: package containing random, pow, and seedrandom + 256, // width: each RC4 output is 0 <= x < 256 + 6, // chunks: at least six RC4 outputs for each double + 52 // significance: there are 52 significant digits in a double + )); +/* This file is a slightly modified version of quadprog.js from Alberto Santini. + * It has been slightly modified by Sébastien Loisel to make sure that it handles + * 0-based Arrays instead of 1-based Arrays. + * License is in resources/LICENSE.quadprog */ +(function(exports) { + +function base0to1(A) { + if(typeof A !== "object") { return A; } + var ret = [], i,n=A.length; + for(i=0;i meq) { + work[l] = sum; + } else { + work[l] = -Math.abs(sum); + if (sum > 0) { + for (j = 1; j <= n; j = j + 1) { + amat[j][i] = -amat[j][i]; + } + bvec[i] = -bvec[i]; + } + } + } + + for (i = 1; i <= nact; i = i + 1) { + work[iwsv + iact[i]] = 0; + } + + nvl = 0; + temp = 0; + for (i = 1; i <= q; i = i + 1) { + if (work[iwsv + i] < temp * work[iwnbv + i]) { + nvl = i; + temp = work[iwsv + i] / work[iwnbv + i]; + } + } + if (nvl === 0) { + return 999; + } + + return 0; + } + + function fn_goto_55() { + for (i = 1; i <= n; i = i + 1) { + sum = 0; + for (j = 1; j <= n; j = j + 1) { + sum = sum + dmat[j][i] * amat[j][nvl]; + } + work[i] = sum; + } + + l1 = iwzv; + for (i = 1; i <= n; i = i + 1) { + work[l1 + i] = 0; + } + for (j = nact + 1; j <= n; j = j + 1) { + for (i = 1; i <= n; i = i + 1) { + work[l1 + i] = work[l1 + i] + dmat[i][j] * work[j]; + } + } + + t1inf = true; + for (i = nact; i >= 1; i = i - 1) { + sum = work[i]; + l = iwrm + (i * (i + 3)) / 2; + l1 = l - i; + for (j = i + 1; j <= nact; j = j + 1) { + sum = sum - work[l] * work[iwrv + j]; + l = l + j; + } + sum = sum / work[l1]; + work[iwrv + i] = sum; + if (iact[i] < meq) { + // continue; + break; + } + if (sum < 0) { + // continue; + break; + } + t1inf = false; + it1 = i; + } + + if (!t1inf) { + t1 = work[iwuv + it1] / work[iwrv + it1]; + for (i = 1; i <= nact; i = i + 1) { + if (iact[i] < meq) { + // continue; + break; + } + if (work[iwrv + i] < 0) { + // continue; + break; + } + temp = work[iwuv + i] / work[iwrv + i]; + if (temp < t1) { + t1 = temp; + it1 = i; + } + } + } + + sum = 0; + for (i = iwzv + 1; i <= iwzv + n; i = i + 1) { + sum = sum + work[i] * work[i]; + } + if (Math.abs(sum) <= vsmall) { + if (t1inf) { + ierr[1] = 1; + // GOTO 999 + return 999; + } else { + for (i = 1; i <= nact; i = i + 1) { + work[iwuv + i] = work[iwuv + i] - t1 * work[iwrv + i]; + } + work[iwuv + nact + 1] = work[iwuv + nact + 1] + t1; + // GOTO 700 + return 700; + } + } else { + sum = 0; + for (i = 1; i <= n; i = i + 1) { + sum = sum + work[iwzv + i] * amat[i][nvl]; + } + tt = -work[iwsv + nvl] / sum; + t2min = true; + if (!t1inf) { + if (t1 < tt) { + tt = t1; + t2min = false; + } + } + + for (i = 1; i <= n; i = i + 1) { + sol[i] = sol[i] + tt * work[iwzv + i]; + if (Math.abs(sol[i]) < vsmall) { + sol[i] = 0; + } + } + + crval[1] = crval[1] + tt * sum * (tt / 2 + work[iwuv + nact + 1]); + for (i = 1; i <= nact; i = i + 1) { + work[iwuv + i] = work[iwuv + i] - tt * work[iwrv + i]; + } + work[iwuv + nact + 1] = work[iwuv + nact + 1] + tt; + + if (t2min) { + nact = nact + 1; + iact[nact] = nvl; + + l = iwrm + ((nact - 1) * nact) / 2 + 1; + for (i = 1; i <= nact - 1; i = i + 1) { + work[l] = work[i]; + l = l + 1; + } + + if (nact === n) { + work[l] = work[n]; + } else { + for (i = n; i >= nact + 1; i = i - 1) { + if (work[i] === 0) { + // continue; + break; + } + gc = Math.max(Math.abs(work[i - 1]), Math.abs(work[i])); + gs = Math.min(Math.abs(work[i - 1]), Math.abs(work[i])); + if (work[i - 1] >= 0) { + temp = Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc))); + } else { + temp = -Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc))); + } + gc = work[i - 1] / temp; + gs = work[i] / temp; + + if (gc === 1) { + // continue; + break; + } + if (gc === 0) { + work[i - 1] = gs * temp; + for (j = 1; j <= n; j = j + 1) { + temp = dmat[j][i - 1]; + dmat[j][i - 1] = dmat[j][i]; + dmat[j][i] = temp; + } + } else { + work[i - 1] = temp; + nu = gs / (1 + gc); + for (j = 1; j <= n; j = j + 1) { + temp = gc * dmat[j][i - 1] + gs * dmat[j][i]; + dmat[j][i] = nu * (dmat[j][i - 1] + temp) - dmat[j][i]; + dmat[j][i - 1] = temp; + + } + } + } + work[l] = work[nact]; + } + } else { + sum = -bvec[nvl]; + for (j = 1; j <= n; j = j + 1) { + sum = sum + sol[j] * amat[j][nvl]; + } + if (nvl > meq) { + work[iwsv + nvl] = sum; + } else { + work[iwsv + nvl] = -Math.abs(sum); + if (sum > 0) { + for (j = 1; j <= n; j = j + 1) { + amat[j][nvl] = -amat[j][nvl]; + } + bvec[nvl] = -bvec[nvl]; + } + } + // GOTO 700 + return 700; + } + } + + return 0; + } + + function fn_goto_797() { + l = iwrm + (it1 * (it1 + 1)) / 2 + 1; + l1 = l + it1; + if (work[l1] === 0) { + // GOTO 798 + return 798; + } + gc = Math.max(Math.abs(work[l1 - 1]), Math.abs(work[l1])); + gs = Math.min(Math.abs(work[l1 - 1]), Math.abs(work[l1])); + if (work[l1 - 1] >= 0) { + temp = Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc))); + } else { + temp = -Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc))); + } + gc = work[l1 - 1] / temp; + gs = work[l1] / temp; + + if (gc === 1) { + // GOTO 798 + return 798; + } + if (gc === 0) { + for (i = it1 + 1; i <= nact; i = i + 1) { + temp = work[l1 - 1]; + work[l1 - 1] = work[l1]; + work[l1] = temp; + l1 = l1 + i; + } + for (i = 1; i <= n; i = i + 1) { + temp = dmat[i][it1]; + dmat[i][it1] = dmat[i][it1 + 1]; + dmat[i][it1 + 1] = temp; + } + } else { + nu = gs / (1 + gc); + for (i = it1 + 1; i <= nact; i = i + 1) { + temp = gc * work[l1 - 1] + gs * work[l1]; + work[l1] = nu * (work[l1 - 1] + temp) - work[l1]; + work[l1 - 1] = temp; + l1 = l1 + i; + } + for (i = 1; i <= n; i = i + 1) { + temp = gc * dmat[i][it1] + gs * dmat[i][it1 + 1]; + dmat[i][it1 + 1] = nu * (dmat[i][it1] + temp) - dmat[i][it1 + 1]; + dmat[i][it1] = temp; + } + } + + return 0; + } + + function fn_goto_798() { + l1 = l - it1; + for (i = 1; i <= it1; i = i + 1) { + work[l1] = work[l]; + l = l + 1; + l1 = l1 + 1; + } + + work[iwuv + it1] = work[iwuv + it1 + 1]; + iact[it1] = iact[it1 + 1]; + it1 = it1 + 1; + if (it1 < nact) { + // GOTO 797 + return 797; + } + + return 0; + } + + function fn_goto_799() { + work[iwuv + nact] = work[iwuv + nact + 1]; + work[iwuv + nact + 1] = 0; + iact[nact] = 0; + nact = nact - 1; + iter[2] = iter[2] + 1; + + return 0; + } + + go = 0; + while (true) { + go = fn_goto_50(); + if (go === 999) { + return; + } + while (true) { + go = fn_goto_55(); + if (go === 0) { + break; + } + if (go === 999) { + return; + } + if (go === 700) { + if (it1 === nact) { + fn_goto_799(); + } else { + while (true) { + fn_goto_797(); + go = fn_goto_798(); + if (go !== 797) { + break; + } + } + fn_goto_799(); + } + } + } + } + +} + +function solveQP(Dmat, dvec, Amat, bvec, meq, factorized) { + Dmat = base0to1(Dmat); + dvec = base0to1(dvec); + Amat = base0to1(Amat); + var i, n, q, + nact, r, + crval = [], iact = [], sol = [], work = [], iter = [], + message; + + meq = meq || 0; + factorized = factorized ? base0to1(factorized) : [undefined, 0]; + bvec = bvec ? base0to1(bvec) : []; + + // In Fortran the array index starts from 1 + n = Dmat.length - 1; + q = Amat[1].length - 1; + + if (!bvec) { + for (i = 1; i <= q; i = i + 1) { + bvec[i] = 0; + } + } + for (i = 1; i <= q; i = i + 1) { + iact[i] = 0; + } + nact = 0; + r = Math.min(n, q); + for (i = 1; i <= n; i = i + 1) { + sol[i] = 0; + } + crval[1] = 0; + for (i = 1; i <= (2 * n + (r * (r + 5)) / 2 + 2 * q + 1); i = i + 1) { + work[i] = 0; + } + for (i = 1; i <= 2; i = i + 1) { + iter[i] = 0; + } + + qpgen2(Dmat, dvec, n, n, sol, crval, Amat, + bvec, n, q, meq, iact, nact, iter, work, factorized); + + message = ""; + if (factorized[1] === 1) { + message = "constraints are inconsistent, no solution!"; + } + if (factorized[1] === 2) { + message = "matrix D in quadratic function is not positive definite!"; + } + + return { + solution: base1to0(sol), + value: base1to0(crval), + unconstrained_solution: base1to0(dvec), + iterations: base1to0(iter), + iact: base1to0(iact), + message: message + }; +} +exports.solveQP = solveQP; +}(numeric)); +/* +Shanti Rao sent me this routine by private email. I had to modify it +slightly to work on Arrays instead of using a Matrix object. +It is apparently translated from http://stitchpanorama.sourceforge.net/Python/svd.py +*/ + +numeric.svd= function svd(A) { + var temp; +//Compute the thin SVD from G. H. Golub and C. Reinsch, Numer. Math. 14, 403-420 (1970) + var prec= numeric.epsilon; //Math.pow(2,-52) // assumes double prec + var tolerance= 1.e-64/prec; + var itmax= 50; + var c=0; + var i=0; + var j=0; + var k=0; + var l=0; + + var u= numeric.clone(A); + var m= u.length; + + var n= u[0].length; + + if (m < n) throw "Need more rows than columns" + + var e = new Array(n); + var q = new Array(n); + for (i=0; i b) + return a*Math.sqrt(1.0+(b*b/a/a)) + else if (b == 0.0) + return a + return b*Math.sqrt(1.0+(a*a/b/b)) + } + + //Householder's reduction to bidiagonal form + + var f= 0.0; + var g= 0.0; + var h= 0.0; + var x= 0.0; + var y= 0.0; + var z= 0.0; + var s= 0.0; + + for (i=0; i < n; i++) + { + e[i]= g; + s= 0.0; + l= i+1; + for (j=i; j < m; j++) + s += (u[j][i]*u[j][i]); + if (s <= tolerance) + g= 0.0; + else + { + f= u[i][i]; + g= Math.sqrt(s); + if (f >= 0.0) g= -g; + h= f*g-s + u[i][i]=f-g; + for (j=l; j < n; j++) + { + s= 0.0 + for (k=i; k < m; k++) + s += u[k][i]*u[k][j] + f= s/h + for (k=i; k < m; k++) + u[k][j]+=f*u[k][i] + } + } + q[i]= g + s= 0.0 + for (j=l; j < n; j++) + s= s + u[i][j]*u[i][j] + if (s <= tolerance) + g= 0.0 + else + { + f= u[i][i+1] + g= Math.sqrt(s) + if (f >= 0.0) g= -g + h= f*g - s + u[i][i+1] = f-g; + for (j=l; j < n; j++) e[j]= u[i][j]/h + for (j=l; j < m; j++) + { + s=0.0 + for (k=l; k < n; k++) + s += (u[j][k]*u[i][k]) + for (k=l; k < n; k++) + u[j][k]+=s*e[k] + } + } + y= Math.abs(q[i])+Math.abs(e[i]) + if (y>x) + x=y + } + + // accumulation of right hand gtransformations + for (i=n-1; i != -1; i+= -1) + { + if (g != 0.0) + { + h= g*u[i][i+1] + for (j=l; j < n; j++) + v[j][i]=u[i][j]/h + for (j=l; j < n; j++) + { + s=0.0 + for (k=l; k < n; k++) + s += u[i][k]*v[k][j] + for (k=l; k < n; k++) + v[k][j]+=(s*v[k][i]) + } + } + for (j=l; j < n; j++) + { + v[i][j] = 0; + v[j][i] = 0; + } + v[i][i] = 1; + g= e[i] + l= i + } + + // accumulation of left hand transformations + for (i=n-1; i != -1; i+= -1) + { + l= i+1 + g= q[i] + for (j=l; j < n; j++) + u[i][j] = 0; + if (g != 0.0) + { + h= u[i][i]*g + for (j=l; j < n; j++) + { + s=0.0 + for (k=l; k < m; k++) s += u[k][i]*u[k][j]; + f= s/h + for (k=i; k < m; k++) u[k][j]+=f*u[k][i]; + } + for (j=i; j < m; j++) u[j][i] = u[j][i]/g; + } + else + for (j=i; j < m; j++) u[j][i] = 0; + u[i][i] += 1; + } + + // diagonalization of the bidiagonal form + prec= prec*x + for (k=n-1; k != -1; k+= -1) + { + for (var iteration=0; iteration < itmax; iteration++) + { // test f splitting + var test_convergence = false + for (l=k; l != -1; l+= -1) + { + if (Math.abs(e[l]) <= prec) + { test_convergence= true + break + } + if (Math.abs(q[l-1]) <= prec) + break + } + if (!test_convergence) + { // cancellation of e[l] if l>0 + c= 0.0 + s= 1.0 + var l1= l-1 + for (i =l; i= itmax-1) + throw 'Error: no convergence.' + // shift from bottom 2x2 minor + x= q[l] + y= q[k-1] + g= e[k-1] + h= e[k] + f= ((y-z)*(y+z)+(g-h)*(g+h))/(2.0*h*y) + g= pythag(f,1.0) + if (f < 0.0) + f= ((x-z)*(x+z)+h*(y/(f-g)-h))/x + else + f= ((x-z)*(x+z)+h*(y/(f+g)-h))/x + // next QR transformation + c= 1.0 + s= 1.0 + for (i=l+1; i< k+1; i++) + { + g= e[i] + y= q[i] + h= s*g + g= c*g + z= pythag(f,h) + e[i-1]= z + c= f/z + s= h/z + f= x*c+g*s + g= -x*s+g*c + h= y*s + y= y*c + for (j=0; j < n; j++) + { + x= v[j][i-1] + z= v[j][i] + v[j][i-1] = x*c+z*s + v[j][i] = -x*s+z*c + } + z= pythag(f,h) + q[i-1]= z + c= f/z + s= h/z + f= c*g+s*y + x= -s*g+c*y + for (j=0; j < m; j++) + { + y= u[j][i-1] + z= u[j][i] + u[j][i-1] = y*c+z*s + u[j][i] = -y*s+z*c + } + } + e[l]= 0.0 + e[k]= f + q[k]= x + } + } + + //vt= transpose(v) + //return (u,q,vt) + for (i=0;i= 0; j--) + { + if (q[j] < q[i]) + { + // writeln(i,'-',j) + c = q[j] + q[j] = q[i] + q[i] = c + for(k=0;k 1) { + x = p2.x; + y = p2.y; + + } else if (t > 0) { + x += dx * t; + y += dy * t; + } + } + + dx = p.x - x; + dy = p.y - y; + + return dx * dx + dy * dy; +} +// rest of the code doesn't care about point format + +// basic distance-based simplification +function simplifyRadialDist(points, sqTolerance) { + + var prevPoint = points[0], + newPoints = [prevPoint], + point; + + for (var i = 1, len = points.length; i < len; i++) { + point = points[i]; + + if (getSqDist(point, prevPoint) > sqTolerance) { + newPoints.push(point); + prevPoint = point; + } + } + + if (prevPoint !== point) newPoints.push(point); + + return newPoints; +} + +// simplification using optimized Douglas-Peucker algorithm with recursion elimination +function simplifyDouglasPeucker(points, sqTolerance) { + + var len = points.length, + MarkerArray = typeof Uint8Array !== 'undefined' ? Uint8Array : Array, + markers = new MarkerArray(len), + first = 0, + last = len - 1, + stack = [], + newPoints = [], + i, maxSqDist, sqDist, index; + + markers[first] = markers[last] = 1; + + while (last) { + + maxSqDist = 0; + + for (i = first + 1; i < last; i++) { + sqDist = getSqSegDist(points[i], points[first], points[last]); + + if (sqDist > maxSqDist) { + index = i; + maxSqDist = sqDist; + } + } + + if (maxSqDist > sqTolerance) { + markers[index] = 1; + stack.push(first, index, index, last); + } + + last = stack.pop(); + first = stack.pop(); + } + + for (i = 0; i < len; i++) { + if (markers[i]) newPoints.push(points[i]); + } + + return newPoints; +} + +// both algorithms combined for awesome performance +function simplify(points, tolerance, highestQuality) { + + var sqTolerance = tolerance !== undefined ? tolerance * tolerance : 1; + + points = highestQuality ? points : simplifyRadialDist(points, sqTolerance); + points = simplifyDouglasPeucker(points, sqTolerance); + + return points; +} + +// export as AMD module / Node module / browser or worker variable +if (typeof define === 'function' && define.amd) define(function() { return simplify; }); +else if (typeof module !== 'undefined') module.exports = simplify; +else if (typeof self !== 'undefined') self.simplify = simplify; +else window.simplify = simplify; + +})(); + +},{}],10:[function(require,module,exports){ +"use strict" + +module.exports = createKDTree +module.exports.deserialize = deserializeKDTree + +var ndarray = require("ndarray") +var ndselect = require("ndarray-select") +var pack = require("ndarray-pack") +var ops = require("ndarray-ops") +var ndscratch = require("ndarray-scratch") +var pool = require("typedarray-pool") +var inorderTree = require("inorder-tree-layout") +var bits = require("bit-twiddle") +var KDTHeap = require("./lib/heap.js") + +function KDTree(points, ids, n, d) { + this.points = points + this.ids = ids + this.dimension = d + this.length = n +} + +var proto = KDTree.prototype + +proto.serialize = function() { + if(this.length > 0) { + return { + p: Array.prototype.slice.call(this.points.data, 0, this.length*this.dimension), + i: Array.prototype.slice.call(this.ids, 0, this.length) + } + } else { + return { d: this.dimension } + } +} + +//Range query +proto.range = function kdtRangeQuery(lo, hi, visit) { + var n = this.length + if(n < 1) { + return + } + + //Check degenerate case + var d = this.dimension + for(var i=0; i 0) { + if(data[0] >= nearestD) { + break + } + + var idx = index[0] + var pidx = points.index(idx, 0) + var d2 = 0.0 + for(var i=0; i 0) { + if(data[0] >= nearestD) { + break + } + + var idx = index[0] + var pidx = points.index(idx, 0) + var d2 = 0.0 + for(var i=0; i= maxPoints) { + closestPoints.pop() + } + var pcount = closestPoints.count + cl_index[pcount] = idx + cl_data[pcount] = -d2 + closestPoints.push() + if(closestPoints.count >= maxPoints) { + nearestD = -cl_data[0] + } + } + + //Compute distance bounds for children + var k = bits.log2(idx+1)%d + var ds = 0 + for(var i=0; i=0; --i) { + result[i] = ids[cl_index[0]] + closestPoints.pop() + } + closestPoints.dispose() + + return result +} + +proto.dispose = function kdtDispose() { + pool.free(this.points.data) + pool.freeInt32(this.ids) + this.points = null + this.ids = null + this.length = 0 +} + +function createKDTree(points) { + var n, d, indexed + if(Array.isArray(points)) { + n = points.length + if(n === 0) { + return new KDTree(null, null, 0, 0) + } + d = points[0].length + indexed = ndarray(pool.mallocDouble(n*(d+1)), [n, d+1]) + pack(points, indexed.hi(n, d)) + } else { + n = points.shape[0] + d = points.shape[1] + + //Round up data type size + var type = points.dtype + if(type === "int8" || + type === "int16" || + type === "int32" ) { + type = "int32" + } else if(type === "uint8" || + type === "uint8_clamped" || + type === "buffer" || + type === "uint16" || + type === "uint32") { + type = "uint32" + } else if(type === "float32") { + type = "float32" + } else { + type = "float64" + } + indexed = ndarray(pool.malloc(n*(d+1)), [n, d+1]) + ops.assign(indexed.hi(n,d), points) + } + for(var i=0; i 1) { + var k = bits.log2(pointer+1)%d + var median + var n_2 = inorderTree.root(nn) + median = sel_cmp(array, n_2, function(a,b) { + return a.get(k) - b.get(k) + }) + + //Copy into new array + var pptr = pointArray.index(pointer, 0) + var mptr = median.offset + for(var i=0; i 2) { + toVisit.push(array.lo(n_2+1)) + } + } else { + //Copy into new array + var mptr = array.offset + var pptr = pointArray.index(pointer, 0) + for(var i=0; i> 1 + } + return (i >> 1) - 1 +} + +function KDTHeap(n, d) { + this.count = 0 + this.dataSize = d + this.index = pool.mallocInt32(n) + this.data = pool.mallocFloat64(n*d) +} + +var proto = KDTHeap.prototype + +proto.heapSwap = function(_i,_j) { + var data = this.data + var index = this.index + var d = this.dataSize + var tmp = index[_i] + index[_i] = index[_j] + index[_j] = tmp + var aptr = d*_i + var bptr = d*_j + for(var _k=0; _k0) { + var parent = heapParent(i) + if(parent >= 0) { + var pw = data[d*parent] + if(w < pw) { + this.heapSwap(i, parent) + i = parent + continue + } + } + break + } +} + +proto.heapDown = function(i) { + var d = this.dataSize + var index = this.index + var data = this.data + var count = this.count + var w = data[d*i] + while(true) { + var tw = w + var left = 2*i + 1 + var right = 2*(i + 1) + var next = i + if(left < count) { + var lw = data[d*left] + if(lw < tw) { + next = left + tw = lw + } + } + if(right < count) { + var rw = data[d*right] + if(rw < tw) { + next = right + } + } + if(next === i) { + break + } + this.heapSwap(i, next) + i = next + } +} + +//Clear item from top of heap +proto.pop = function() { + this.count -= 1 + this.heapSwap(0, this.count) + this.heapDown(0) +} + +//Assume object already written to data +proto.push = function() { + this.heapUp(this.count) + this.count += 1 +} + +proto.dispose = function() { + pool.freeInt32(this.index) + pool.freeFloat64(this.data) +} +},{"typedarray-pool":32}],12:[function(require,module,exports){ +/** + * Bit twiddling hacks for JavaScript. + * + * Author: Mikola Lysenko + * + * Ported from Stanford bit twiddling hack library: + * http://graphics.stanford.edu/~seander/bithacks.html + */ + +"use strict"; "use restrict"; + +//Number of bits in an integer +var INT_BITS = 32; + +//Constants +exports.INT_BITS = INT_BITS; +exports.INT_MAX = 0x7fffffff; +exports.INT_MIN = -1<<(INT_BITS-1); + +//Returns -1, 0, +1 depending on sign of x +exports.sign = function(v) { + return (v > 0) - (v < 0); +} + +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; +} + +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} + +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} + +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} + +//Computes log base 2 of v +exports.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} + +//Computes log base 10 of v +exports.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} + +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} + +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +exports.countTrailingZeros = countTrailingZeros; + +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} + +//Rounds down to previous power of 2 +exports.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} + +//Computes parity of word +exports.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} + +var REVERSE_TABLE = new Array(256); + +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; + } + tab[i] = (r << s) & 0xff; + } +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; +} + +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +//Extracts the nth interleaved component +exports.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} + + +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; + + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} + +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} + +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +} + + +},{}],13:[function(require,module,exports){ +"use strict" + +var bits = require("bit-twiddle") + +function rootInorder(n) { + var ptree = (bits.nextPow2(n+1)>>>1) - 1 + var f = n - ptree + if(bits.nextPow2(f)-1 >= ptree) { + return ptree + } + return (ptree>>>1)+f +} +exports.root = rootInorder + +function beginInorder(n) { + return 0 +} +exports.begin = beginInorder + +function endInorder(n) { + return n-1 +} +exports.end = endInorder + + +//This is really horrible because n is not necessarily a power of 2 +// If it was, we could just do: +// +// height = bits.countTrailingZeros(~x) +// +// Instead, we just binary search because doing the right thing here is way too complicated. +function heightInorder(n, x) { + if(n <= 0) { + return 0 + } + var r = rootInorder(n) + if(x > r) { + return heightInorder(n-r-1, x-r-1) + } else if(x === r) { + return bits.log2(n) + } + return heightInorder(r, x) +} +exports.height = heightInorder + +function prevInorder(n, x) { + return Math.max(x-1,0) +} +exports.prev = prevInorder + +function nextInorder(n, x) { + return Math.min(x+1,n-1) +} +exports.next = nextInorder + + +//The version for n = (1< r) { + var q = parentInorder(n-r-1, x-r-1) + if(q < 0) { + return r + } else { + return q + r + 1 + } + } else if(x === r) { + return -1 + } + var q = parentInorder(r, x) + if(q < 0) { + return r + } + return q +} +exports.parent = parentInorder + + +//Again, we get screwed because n is not a power of two -1. If it was, we could do: +// +// left = x - (1 << (h-1) ) +// +// Where h is the height of the node +// +function leftInorder(n, x) { + if(n <= 0) { + return 0 + } + var r = rootInorder(n) + if(x > r) { + return leftInorder(n-r-1, x-r-1) + r + 1 + } else if(x === r) { + return rootInorder(x) + } + return leftInorder(r, x) + +} +exports.left = leftInorder + +//for power of two minus one: +// +// right = x + (1<<(h-1)) +// +function rightInorder(n, x) { + if(n <= 0) { + return 0 + } + var r = rootInorder(n) + if(x > r) { + return rightInorder(n-r-1, x-r-1) + r + 1 + } else if(x === r) { + return rootInorder(n-r-1) + r + 1 + } + return rightInorder(r, x) +} +exports.right = rightInorder + + +function leafInorder(n, x) { + return heightInorder(n, x) === 0 +} +exports.leaf = leafInorder + + +function loInorder(n, x) { + n |= 0 + x |= 0 + var l = 0 + while(n > 1) { + var r = rootInorder(n) + if(x > r) { + l += r + 1 + n -= r + 1 + x -= r + 1 + } else if(x === r) { + break + } else { + n = r + } + } + return l +} +exports.lo = loInorder + +function hiInorder(n, x) { + n |= 0 + x |= 0 + var l = 0 + while(n > 1) { + var r = rootInorder(n) + if(x > r) { + l += r + 1 + n -= r + 1 + x -= r + 1 + } else if(x === r) { + l += n-1 + break + } else { + n = r + } + } + return l +} +exports.hi = hiInorder + +},{"bit-twiddle":14}],14:[function(require,module,exports){ +arguments[4][12][0].apply(exports,arguments) +},{"dup":12}],15:[function(require,module,exports){ +"use strict" + +var compile = require("cwise-compiler") + +var EmptyProc = { + body: "", + args: [], + thisVars: [], + localVars: [] +} + +function fixup(x) { + if(!x) { + return EmptyProc + } + for(var i=0; i>", + rrshift: ">>>" +} +;(function(){ + for(var id in assign_ops) { + var op = assign_ops[id] + exports[id] = makeOp({ + args: ["array","array","array"], + body: {args:["a","b","c"], + body: "a=b"+op+"c"}, + funcName: id + }) + exports[id+"eq"] = makeOp({ + args: ["array","array"], + body: {args:["a","b"], + body:"a"+op+"=b"}, + rvalue: true, + funcName: id+"eq" + }) + exports[id+"s"] = makeOp({ + args: ["array", "array", "scalar"], + body: {args:["a","b","s"], + body:"a=b"+op+"s"}, + funcName: id+"s" + }) + exports[id+"seq"] = makeOp({ + args: ["array","scalar"], + body: {args:["a","s"], + body:"a"+op+"=s"}, + rvalue: true, + funcName: id+"seq" + }) + } +})(); + +var unary_ops = { + not: "!", + bnot: "~", + neg: "-", + recip: "1.0/" +} +;(function(){ + for(var id in unary_ops) { + var op = unary_ops[id] + exports[id] = makeOp({ + args: ["array", "array"], + body: {args:["a","b"], + body:"a="+op+"b"}, + funcName: id + }) + exports[id+"eq"] = makeOp({ + args: ["array"], + body: {args:["a"], + body:"a="+op+"a"}, + rvalue: true, + count: 2, + funcName: id+"eq" + }) + } +})(); + +var binary_ops = { + and: "&&", + or: "||", + eq: "===", + neq: "!==", + lt: "<", + gt: ">", + leq: "<=", + geq: ">=" +} +;(function() { + for(var id in binary_ops) { + var op = binary_ops[id] + exports[id] = makeOp({ + args: ["array","array","array"], + body: {args:["a", "b", "c"], + body:"a=b"+op+"c"}, + funcName: id + }) + exports[id+"s"] = makeOp({ + args: ["array","array","scalar"], + body: {args:["a", "b", "s"], + body:"a=b"+op+"s"}, + funcName: id+"s" + }) + exports[id+"eq"] = makeOp({ + args: ["array", "array"], + body: {args:["a", "b"], + body:"a=a"+op+"b"}, + rvalue:true, + count:2, + funcName: id+"eq" + }) + exports[id+"seq"] = makeOp({ + args: ["array", "scalar"], + body: {args:["a","s"], + body:"a=a"+op+"s"}, + rvalue:true, + count:2, + funcName: id+"seq" + }) + } +})(); + +var math_unary = [ + "abs", + "acos", + "asin", + "atan", + "ceil", + "cos", + "exp", + "floor", + "log", + "round", + "sin", + "sqrt", + "tan" +] +;(function() { + for(var i=0; ithis_s){this_s=-a}else if(a>this_s){this_s=a}", localVars: [], thisVars: ["this_s"]}, + post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, + funcName: "norminf" +}) + +exports.norm1 = compile({ + args:["array"], + pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"}, + body: {args:[{name:"a", lvalue:false, rvalue:true, count:3}], body: "this_s+=a<0?-a:a", localVars: [], thisVars: ["this_s"]}, + post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, + funcName: "norm1" +}) + +exports.sup = compile({ + args: [ "array" ], + pre: + { body: "this_h=-Infinity", + args: [], + thisVars: [ "this_h" ], + localVars: [] }, + body: + { body: "if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_", + args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ], + thisVars: [ "this_h" ], + localVars: [] }, + post: + { body: "return this_h", + args: [], + thisVars: [ "this_h" ], + localVars: [] } + }) + +exports.inf = compile({ + args: [ "array" ], + pre: + { body: "this_h=Infinity", + args: [], + thisVars: [ "this_h" ], + localVars: [] }, + body: + { body: "if(_inline_1_arg0_this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}", + args:[ + {name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2}, + {name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}], + thisVars:["this_i","this_v"], + localVars:["_inline_1_k"]}, + post:{ + body:"{return this_i}", + args:[], + thisVars:["this_i"], + localVars:[]} +}) + +exports.random = makeOp({ + args: ["array"], + pre: {args:[], body:"this_f=Math.random", thisVars:["this_f"]}, + body: {args: ["a"], body:"a=this_f()", thisVars:["this_f"]}, + funcName: "random" +}) + +exports.assign = makeOp({ + args:["array", "array"], + body: {args:["a", "b"], body:"a=b"}, + funcName: "assign" }) + +exports.assigns = makeOp({ + args:["array", "scalar"], + body: {args:["a", "b"], body:"a=b"}, + funcName: "assigns" }) + + +exports.equals = compile({ + args:["array", "array"], + pre: EmptyProc, + body: {args:[{name:"x", lvalue:false, rvalue:true, count:1}, + {name:"y", lvalue:false, rvalue:true, count:1}], + body: "if(x!==y){return false}", + localVars: [], + thisVars: []}, + post: {args:[], localVars:[], thisVars:[], body:"return true"}, + funcName: "equals" +}) + + + +},{"cwise-compiler":16}],16:[function(require,module,exports){ +"use strict" + +var createThunk = require("./lib/thunk.js") + +function Procedure() { + this.argTypes = [] + this.shimArgs = [] + this.arrayArgs = [] + this.arrayBlockIndices = [] + this.scalarArgs = [] + this.offsetArgs = [] + this.offsetArgIndex = [] + this.indexArgs = [] + this.shapeArgs = [] + this.funcName = "" + this.pre = null + this.body = null + this.post = null + this.debug = false +} + +function compileCwise(user_args) { + //Create procedure + var proc = new Procedure() + + //Parse blocks + proc.pre = user_args.pre + proc.body = user_args.body + proc.post = user_args.post + + //Parse arguments + var proc_args = user_args.args.slice(0) + proc.argTypes = proc_args + for(var i=0; i0) { + throw new Error("cwise: pre() block may not reference array args") + } + if(i < proc.post.args.length && proc.post.args[i].count>0) { + throw new Error("cwise: post() block may not reference array args") + } + } else if(arg_type === "scalar") { + proc.scalarArgs.push(i) + proc.shimArgs.push("scalar" + i) + } else if(arg_type === "index") { + proc.indexArgs.push(i) + if(i < proc.pre.args.length && proc.pre.args[i].count > 0) { + throw new Error("cwise: pre() block may not reference array index") + } + if(i < proc.body.args.length && proc.body.args[i].lvalue) { + throw new Error("cwise: body() block may not write to array index") + } + if(i < proc.post.args.length && proc.post.args[i].count > 0) { + throw new Error("cwise: post() block may not reference array index") + } + } else if(arg_type === "shape") { + proc.shapeArgs.push(i) + if(i < proc.pre.args.length && proc.pre.args[i].lvalue) { + throw new Error("cwise: pre() block may not write to array shape") + } + if(i < proc.body.args.length && proc.body.args[i].lvalue) { + throw new Error("cwise: body() block may not write to array shape") + } + if(i < proc.post.args.length && proc.post.args[i].lvalue) { + throw new Error("cwise: post() block may not write to array shape") + } + } else if(typeof arg_type === "object" && arg_type.offset) { + proc.argTypes[i] = "offset" + proc.offsetArgs.push({ array: arg_type.array, offset:arg_type.offset }) + proc.offsetArgIndex.push(i) + } else { + throw new Error("cwise: Unknown argument type " + proc_args[i]) + } + } + + //Make sure at least one array argument was specified + if(proc.arrayArgs.length <= 0) { + throw new Error("cwise: No array arguments specified") + } + + //Make sure arguments are correct + if(proc.pre.args.length > proc_args.length) { + throw new Error("cwise: Too many arguments in pre() block") + } + if(proc.body.args.length > proc_args.length) { + throw new Error("cwise: Too many arguments in body() block") + } + if(proc.post.args.length > proc_args.length) { + throw new Error("cwise: Too many arguments in post() block") + } + + //Check debug flag + proc.debug = !!user_args.printCode || !!user_args.debug + + //Retrieve name + proc.funcName = user_args.funcName || "cwise" + + //Read in block size + proc.blockSize = user_args.blockSize || 64 + + return createThunk(proc) +} + +module.exports = compileCwise + +},{"./lib/thunk.js":18}],17:[function(require,module,exports){ +"use strict" + +var uniq = require("uniq") + +// This function generates very simple loops analogous to how you typically traverse arrays (the outermost loop corresponds to the slowest changing index, the innermost loop to the fastest changing index) +// TODO: If two arrays have the same strides (and offsets) there is potential for decreasing the number of "pointers" and related variables. The drawback is that the type signature would become more specific and that there would thus be less potential for caching, but it might still be worth it, especially when dealing with large numbers of arguments. +function innerFill(order, proc, body) { + var dimension = order.length + , nargs = proc.arrayArgs.length + , has_index = proc.indexArgs.length>0 + , code = [] + , vars = [] + , idx=0, pidx=0, i, j + for(i=0; i=0; --i) { // Start at largest stride and work your way inwards + idx = order[i] + code.push(["for(i",i,"=0;i",i," 0) { + code.push(["index[",pidx,"]-=s",pidx].join("")) + } + code.push(["++index[",idx,"]"].join("")) + } + code.push("}") + } + return code.join("\n") +} + +// Generate "outer" loops that loop over blocks of data, applying "inner" loops to the blocks by manipulating the local variables in such a way that the inner loop only "sees" the current block. +// TODO: If this is used, then the previous declaration (done by generateCwiseOp) of s* is essentially unnecessary. +// I believe the s* are not used elsewhere (in particular, I don't think they're used in the pre/post parts and "shape" is defined independently), so it would be possible to make defining the s* dependent on what loop method is being used. +function outerFill(matched, order, proc, body) { + var dimension = order.length + , nargs = proc.arrayArgs.length + , blockSize = proc.blockSize + , has_index = proc.indexArgs.length > 0 + , code = [] + for(var i=0; i0;){"].join("")) // Iterate back to front + code.push(["if(j",i,"<",blockSize,"){"].join("")) // Either decrease j by blockSize (s = blockSize), or set it to zero (after setting s = j). + code.push(["s",order[i],"=j",i].join("")) + code.push(["j",i,"=0"].join("")) + code.push(["}else{s",order[i],"=",blockSize].join("")) + code.push(["j",i,"-=",blockSize,"}"].join("")) + if(has_index) { + code.push(["index[",order[i],"]=j",i].join("")) + } + } + for(var i=0; i 0) { + allEqual = allEqual && summary[i] === summary[i-1] + } + } + if(allEqual) { + return summary[0] + } + return summary.join("") +} + +//Generates a cwise operator +function generateCWiseOp(proc, typesig) { + + //Compute dimension + // Arrays get put first in typesig, and there are two entries per array (dtype and order), so this gets the number of dimensions in the first array arg. + var dimension = (typesig[1].length - Math.abs(proc.arrayBlockIndices[0]))|0 + var orders = new Array(proc.arrayArgs.length) + var dtypes = new Array(proc.arrayArgs.length) + for(var i=0; i 0) { + vars.push("shape=SS.slice(0)") // Makes the shape over which we iterate available to the user defined functions (so you can use width/height for example) + } + if(proc.indexArgs.length > 0) { + // Prepare an array to keep track of the (logical) indices, initialized to dimension zeroes. + var zeros = new Array(dimension) + for(var i=0; i 3) { + code.push(processBlock(proc.pre, proc, dtypes)) + } + + //Process body + var body = processBlock(proc.body, proc, dtypes) + var matched = countMatches(loopOrders) + if(matched < dimension) { + code.push(outerFill(matched, loopOrders[0], proc, body)) // TODO: Rather than passing loopOrders[0], it might be interesting to look at passing an order that represents the majority of the arguments for example. + } else { + code.push(innerFill(loopOrders[0], proc, body)) + } + + //Inline epilog + if(proc.post.body.length > 3) { + code.push(processBlock(proc.post, proc, dtypes)) + } + + if(proc.debug) { + console.log("-----Generated cwise routine for ", typesig, ":\n" + code.join("\n") + "\n----------") + } + + var loopName = [(proc.funcName||"unnamed"), "_cwise_loop_", orders[0].join("s"),"m",matched,typeSummary(dtypes)].join("") + var f = new Function(["function ",loopName,"(", arglist.join(","),"){", code.join("\n"),"} return ", loopName].join("")) + return f() +} +module.exports = generateCWiseOp + +},{"uniq":19}],18:[function(require,module,exports){ +"use strict" + +// The function below is called when constructing a cwise function object, and does the following: +// A function object is constructed which accepts as argument a compilation function and returns another function. +// It is this other function that is eventually returned by createThunk, and this function is the one that actually +// checks whether a certain pattern of arguments has already been used before and compiles new loops as needed. +// The compilation passed to the first function object is used for compiling new functions. +// Once this function object is created, it is called with compile as argument, where the first argument of compile +// is bound to "proc" (essentially containing a preprocessed version of the user arguments to cwise). +// So createThunk roughly works like this: +// function createThunk(proc) { +// var thunk = function(compileBound) { +// var CACHED = {} +// return function(arrays and scalars) { +// if (dtype and order of arrays in CACHED) { +// var func = CACHED[dtype and order of arrays] +// } else { +// var func = CACHED[dtype and order of arrays] = compileBound(dtype and order of arrays) +// } +// return func(arrays and scalars) +// } +// } +// return thunk(compile.bind1(proc)) +// } + +var compile = require("./compile.js") + +function createThunk(proc) { + var code = ["'use strict'", "var CACHED={}"] + var vars = [] + var thunkName = proc.funcName + "_cwise_thunk" + + //Build thunk + code.push(["return function ", thunkName, "(", proc.shimArgs.join(","), "){"].join("")) + var typesig = [] + var string_typesig = [] + var proc_args = [["array",proc.arrayArgs[0],".shape.slice(", // Slice shape so that we only retain the shape over which we iterate (which gets passed to the cwise operator as SS). + Math.max(0,proc.arrayBlockIndices[0]),proc.arrayBlockIndices[0]<0?(","+proc.arrayBlockIndices[0]+")"):")"].join("")] + var shapeLengthConditions = [], shapeConditions = [] + // Process array arguments + for(var i=0; i0) { // Gather conditions to check for shape equality (ignoring block indices) + shapeLengthConditions.push("array" + proc.arrayArgs[0] + ".shape.length===array" + j + ".shape.length+" + (Math.abs(proc.arrayBlockIndices[0])-Math.abs(proc.arrayBlockIndices[i]))) + shapeConditions.push("array" + proc.arrayArgs[0] + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[0]) + "]===array" + j + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[i]) + "]") + } + } + // Check for shape equality + if (proc.arrayArgs.length > 1) { + code.push("if (!(" + shapeLengthConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same dimensionality!')") + code.push("for(var shapeIndex=array" + proc.arrayArgs[0] + ".shape.length-" + Math.abs(proc.arrayBlockIndices[0]) + "; shapeIndex-->0;) {") + code.push("if (!(" + shapeConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same shape!')") + code.push("}") + } + // Process scalar arguments + for(var i=0; i=0; --i) { + stride[i] = sz + sz *= shape[i] + } + return ndarray(pool.malloc(sz, dtype), shape, stride, 0) +} +exports.malloc = malloc + +function free(array) { + if(array.dtype === "generic" || array.dtype === "array") { + return + } + pool.free(array.data) +} +exports.free = free + +function zeros(shape, dtype) { + if(!dtype) { + dtype = "double" + } + + var sz = 1 + var stride = new Array(shape.length) + for(var i=shape.length-1; i>=0; --i) { + stride[i] = sz + sz *= shape[i] + } + var buf = pool.malloc(sz, dtype) + for(var i=0; i=0; --i) { + stride[i] = sz + sz *= shape[i] + } + var buf = pool.malloc(sz, dtype) + for(var i=0; i=0; --i) { + stride[i] = sz + sz *= shape[i] + } + var buf = pool.malloc(sz, dtype) + for(i=0; i=0; i--) { + offsum += stride[i] + mindim = Math.min(mindim,shape[i]) + } + for(i=0,offset=0; i 1) { + vars.push(STEP_CMP(i) + "=(" + STRIDE(i) + "-" + SHAPE(i-1) + "*" + STRIDE(i-1) + ")|0", + STEP(order[i]) + "=(" + STRIDE(order[i]) + "-" + SHAPE(order[i-1]) + "*" + STRIDE(order[i-1]) + ")|0") + } else { + vars.push(STEP_CMP(i) + "=" + STRIDE(i), + STEP(order[i]) + "=" + STRIDE(order[i])) + } + } + if(useCompare) { + for(var i=0; i<2; ++i) { + vars.push(PICK(i) + "=" + ARRAY + ".pick(0)") + } + } + vars.push( + PIVOT + "=0", + LO + "=0", + HI + "=" + SHAPE(order[0]) + "-1") + + function compare(out, i0, i1) { + if(useCompare) { + code.push( + PICK(0), ".offset=", OFFSET, "+", STRIDE(order[0]), "*(", i0, ");", + PICK(1), ".offset=", OFFSET, "+", STRIDE(order[0]), "*(", i1, ");", + out, "=", CMP, "(", PICK(0), ",", PICK(1), ");") + } else { + code.push( + PTR(0), "=", OFFSET, "+", STRIDE(0), "*(", i0, ");", + PTR(1), "=", OFFSET, "+", STRIDE(0), "*(", i1, ");") + if(dimension > 1) { + code.push("_cmp:") + } + for(var i=dimension-1; i>0; --i) { + code.push("for(", INDEX(i), "=0;", + INDEX(i), "<", SHAPE(i), ";", + INDEX(i), "++){") + } + if(useGetter) { + code.push(out, "=", DATA, ".get(", PTR(0), ")-", + DATA, ".get(", PTR(1), ");") + } else { + code.push(out, "=", DATA, "[", PTR(0), "]-", + DATA, "[", PTR(1), "];") + } + if(dimension > 1) { + code.push("if(", out, ")break _cmp;") + } + for(var i=1; i0; --i) { + code.push("for(", INDEX(order[i]), "=0;", + INDEX(order[i]), "<", SHAPE(order[i]), ";", + INDEX(order[i]), "++){") + } + if(useGetter) { + code.push(TMP, "=", DATA, ".get(", PTR(0), ");", + DATA, ".set(", PTR(0), ",", DATA, ".get(", PTR(1), "));", + DATA, ".set(", PTR(1), ",", TMP, ");") + } else { + code.push(TMP, "=", DATA, "[", PTR(0), "];", + DATA, "[", PTR(0), "]=", DATA, "[", PTR(1), "];", + DATA, "[", PTR(1), "]=", TMP, ";") + } + for(var i=1; i= the pivot are behind the pivot) + + //Check pivot bounds + code.push( + "if(", PIVOT, "===", RANK, "){", + LO, "=", PIVOT, ";", + "break;", + "}else if(", RANK, "<", PIVOT, "){", + HI, "=", PIVOT, "-1;", + "}else{", + LO, "=", PIVOT, "+1;", + "}", + "}") + + if(useCompare) { + code.push(PICK(0), ".offset=", OFFSET, "+", LO, "*", STRIDE(0), ";", + "return ", PICK(0), ";") + } else { + code.push("return ", ARRAY, ".pick(", LO, ");") + } + + //Compile and link js together + var procCode = [ + "'use strict';function ", funcName, "(", args, "){", + "var ", vars.join(), ";", + code.join(""), + "};return ", funcName + ].join("") + + var proc = new Function(procCode) + return proc() +} + +var CACHE = {} + +function lookupCache(order, useCompare, dtype) { + var typesig = order.join() + useCompare + dtype + var proc = CACHE[typesig] + if(proc) { + return proc + } + return CACHE[typesig] = compileQuickSelect(order, useCompare, dtype) +} + +function ndSelect(array, k, compare) { + k |= 0 + if((array.dimension === 0) || + (array.shape[0] <= k) || + (k < 0)) { + return null + } + var useCompare = !!compare + var proc = lookupCache(array.order, useCompare, array.dtype) + if(useCompare) { + return proc(array, k, compare) + } else { + return proc(array, k) + } +} +},{}],28:[function(require,module,exports){ +var iota = require("iota-array") +var isBuffer = require("is-buffer") + +var hasTypedArrays = ((typeof Float64Array) !== "undefined") + +function compare1st(a, b) { + return a[0] - b[0] +} + +function order() { + var stride = this.stride + var terms = new Array(stride.length) + var i + for(i=0; iMath.abs(this.stride[1]))?[1,0]:[0,1]}})") + } else if(dimension === 3) { + code.push( +"var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\ +if(s0>s1){\ +if(s1>s2){\ +return [2,1,0];\ +}else if(s0>s2){\ +return [1,2,0];\ +}else{\ +return [1,0,2];\ +}\ +}else if(s0>s2){\ +return [2,0,1];\ +}else if(s2>s1){\ +return [0,1,2];\ +}else{\ +return [0,2,1];\ +}}})") + } + } else { + code.push("ORDER})") + } + } + + //view.set(i0, ..., v): + code.push( +"proto.set=function "+className+"_set("+args.join(",")+",v){") + if(useGetters) { + code.push("return this.data.set("+index_str+",v)}") + } else { + code.push("return this.data["+index_str+"]=v}") + } + + //view.get(i0, ...): + code.push("proto.get=function "+className+"_get("+args.join(",")+"){") + if(useGetters) { + code.push("return this.data.get("+index_str+")}") + } else { + code.push("return this.data["+index_str+"]}") + } + + //view.index: + code.push( + "proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}") + + //view.hi(): + code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+ + indices.map(function(i) { + return ["(typeof i",i,"!=='number'||i",i,"<0)?this.shape[", i, "]:i", i,"|0"].join("") + }).join(",")+","+ + indices.map(function(i) { + return "this.stride["+i + "]" + }).join(",")+",this.offset)}") + + //view.lo(): + var a_vars = indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" }) + var c_vars = indices.map(function(i) { return "c"+i+"=this.stride["+i+"]" }) + code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(",")) + for(var i=0; i=0){\ +d=i"+i+"|0;\ +b+=c"+i+"*d;\ +a"+i+"-=d}") + } + code.push("return new "+className+"(this.data,"+ + indices.map(function(i) { + return "a"+i + }).join(",")+","+ + indices.map(function(i) { + return "c"+i + }).join(",")+",b)}") + + //view.step(): + code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+ + indices.map(function(i) { + return "a"+i+"=this.shape["+i+"]" + }).join(",")+","+ + indices.map(function(i) { + return "b"+i+"=this.stride["+i+"]" + }).join(",")+",c=this.offset,d=0,ceil=Math.ceil") + for(var i=0; i=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}") + } + code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}") + + //Add return statement + code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+ + indices.map(function(i) { + return "shape["+i+"]" + }).join(",")+","+ + indices.map(function(i) { + return "stride["+i+"]" + }).join(",")+",offset)}") + + //Compile procedure + var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n")) + return procedure(CACHED_CONSTRUCTORS[dtype], order) +} + +function arrayDType(data) { + if(isBuffer(data)) { + return "buffer" + } + if(hasTypedArrays) { + switch(Object.prototype.toString.call(data)) { + case "[object Float64Array]": + return "float64" + case "[object Float32Array]": + return "float32" + case "[object Int8Array]": + return "int8" + case "[object Int16Array]": + return "int16" + case "[object Int32Array]": + return "int32" + case "[object Uint8Array]": + return "uint8" + case "[object Uint16Array]": + return "uint16" + case "[object Uint32Array]": + return "uint32" + case "[object Uint8ClampedArray]": + return "uint8_clamped" + } + } + if(Array.isArray(data)) { + return "array" + } + return "generic" +} + +var CACHED_CONSTRUCTORS = { + "float32":[], + "float64":[], + "int8":[], + "int16":[], + "int32":[], + "uint8":[], + "uint16":[], + "uint32":[], + "array":[], + "uint8_clamped":[], + "buffer":[], + "generic":[] +} + +;(function() { + for(var id in CACHED_CONSTRUCTORS) { + CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1)) + } +}); + +function wrappedNDArrayCtor(data, shape, stride, offset) { + if(data === undefined) { + var ctor = CACHED_CONSTRUCTORS.array[0] + return ctor([]) + } else if(typeof data === "number") { + data = [data] + } + if(shape === undefined) { + shape = [ data.length ] + } + var d = shape.length + if(stride === undefined) { + stride = new Array(d) + for(var i=d-1, sz=1; i>=0; --i) { + stride[i] = sz + sz *= shape[i] + } + } + if(offset === undefined) { + offset = 0 + for(var i=0; i + * License: MIT + * + * `npm install is-buffer` + */ + +module.exports = function (obj) { + return !!(obj != null && + (obj._isBuffer || // For Safari 5-7 (missing Object.prototype.constructor) + (obj.constructor && + typeof obj.constructor.isBuffer === 'function' && + obj.constructor.isBuffer(obj)) + )) +} + +},{}],31:[function(require,module,exports){ +"use strict" + +function dupe_array(count, value, i) { + var c = count[i]|0 + if(c <= 0) { + return [] + } + var result = new Array(c), j + if(i === count.length-1) { + for(j=0; j 0) { + return dupe_number(count|0, value) + } + break + case "object": + if(typeof (count.length) === "number") { + return dupe_array(count, value, 0) + } + break + } + return [] +} + +module.exports = dupe +},{}],32:[function(require,module,exports){ +(function (global,Buffer){ +'use strict' + +var bits = require('bit-twiddle') +var dup = require('dup') + +//Legacy pool support +if(!global.__TYPEDARRAY_POOL) { + global.__TYPEDARRAY_POOL = { + UINT8 : dup([32, 0]) + , UINT16 : dup([32, 0]) + , UINT32 : dup([32, 0]) + , INT8 : dup([32, 0]) + , INT16 : dup([32, 0]) + , INT32 : dup([32, 0]) + , FLOAT : dup([32, 0]) + , DOUBLE : dup([32, 0]) + , DATA : dup([32, 0]) + , UINT8C : dup([32, 0]) + , BUFFER : dup([32, 0]) + } +} + +var hasUint8C = (typeof Uint8ClampedArray) !== 'undefined' +var POOL = global.__TYPEDARRAY_POOL + +//Upgrade pool +if(!POOL.UINT8C) { + POOL.UINT8C = dup([32, 0]) +} +if(!POOL.BUFFER) { + POOL.BUFFER = dup([32, 0]) +} + +//New technique: Only allocate from ArrayBufferView and Buffer +var DATA = POOL.DATA + , BUFFER = POOL.BUFFER + +exports.free = function free(array) { + if(Buffer.isBuffer(array)) { + BUFFER[bits.log2(array.length)].push(array) + } else { + if(Object.prototype.toString.call(array) !== '[object ArrayBuffer]') { + array = array.buffer + } + if(!array) { + return + } + var n = array.length || array.byteLength + var log_n = bits.log2(n)|0 + DATA[log_n].push(array) + } +} + +function freeArrayBuffer(buffer) { + if(!buffer) { + return + } + var n = buffer.length || buffer.byteLength + var log_n = bits.log2(n) + DATA[log_n].push(buffer) +} + +function freeTypedArray(array) { + freeArrayBuffer(array.buffer) +} + +exports.freeUint8 = +exports.freeUint16 = +exports.freeUint32 = +exports.freeInt8 = +exports.freeInt16 = +exports.freeInt32 = +exports.freeFloat32 = +exports.freeFloat = +exports.freeFloat64 = +exports.freeDouble = +exports.freeUint8Clamped = +exports.freeDataView = freeTypedArray + +exports.freeArrayBuffer = freeArrayBuffer + +exports.freeBuffer = function freeBuffer(array) { + BUFFER[bits.log2(array.length)].push(array) +} + +exports.malloc = function malloc(n, dtype) { + if(dtype === undefined || dtype === 'arraybuffer') { + return mallocArrayBuffer(n) + } else { + switch(dtype) { + case 'uint8': + return mallocUint8(n) + case 'uint16': + return mallocUint16(n) + case 'uint32': + return mallocUint32(n) + case 'int8': + return mallocInt8(n) + case 'int16': + return mallocInt16(n) + case 'int32': + return mallocInt32(n) + case 'float': + case 'float32': + return mallocFloat(n) + case 'double': + case 'float64': + return mallocDouble(n) + case 'uint8_clamped': + return mallocUint8Clamped(n) + case 'buffer': + return mallocBuffer(n) + case 'data': + case 'dataview': + return mallocDataView(n) + + default: + return null + } + } + return null +} + +function mallocArrayBuffer(n) { + var n = bits.nextPow2(n) + var log_n = bits.log2(n) + var d = DATA[log_n] + if(d.length > 0) { + return d.pop() + } + return new ArrayBuffer(n) +} +exports.mallocArrayBuffer = mallocArrayBuffer + +function mallocUint8(n) { + return new Uint8Array(mallocArrayBuffer(n), 0, n) +} +exports.mallocUint8 = mallocUint8 + +function mallocUint16(n) { + return new Uint16Array(mallocArrayBuffer(2*n), 0, n) +} +exports.mallocUint16 = mallocUint16 + +function mallocUint32(n) { + return new Uint32Array(mallocArrayBuffer(4*n), 0, n) +} +exports.mallocUint32 = mallocUint32 + +function mallocInt8(n) { + return new Int8Array(mallocArrayBuffer(n), 0, n) +} +exports.mallocInt8 = mallocInt8 + +function mallocInt16(n) { + return new Int16Array(mallocArrayBuffer(2*n), 0, n) +} +exports.mallocInt16 = mallocInt16 + +function mallocInt32(n) { + return new Int32Array(mallocArrayBuffer(4*n), 0, n) +} +exports.mallocInt32 = mallocInt32 + +function mallocFloat(n) { + return new Float32Array(mallocArrayBuffer(4*n), 0, n) +} +exports.mallocFloat32 = exports.mallocFloat = mallocFloat + +function mallocDouble(n) { + return new Float64Array(mallocArrayBuffer(8*n), 0, n) +} +exports.mallocFloat64 = exports.mallocDouble = mallocDouble + +function mallocUint8Clamped(n) { + if(hasUint8C) { + return new Uint8ClampedArray(mallocArrayBuffer(n), 0, n) + } else { + return mallocUint8(n) + } +} +exports.mallocUint8Clamped = mallocUint8Clamped + +function mallocDataView(n) { + return new DataView(mallocArrayBuffer(n), 0, n) +} +exports.mallocDataView = mallocDataView + +function mallocBuffer(n) { + n = bits.nextPow2(n) + var log_n = bits.log2(n) + var cache = BUFFER[log_n] + if(cache.length > 0) { + return cache.pop() + } + return new Buffer(n) +} +exports.mallocBuffer = mallocBuffer + +exports.clearCache = function clearCache() { + for(var i=0; i<32; ++i) { + POOL.UINT8[i].length = 0 + POOL.UINT16[i].length = 0 + POOL.UINT32[i].length = 0 + POOL.INT8[i].length = 0 + POOL.INT16[i].length = 0 + POOL.INT32[i].length = 0 + POOL.FLOAT[i].length = 0 + POOL.DOUBLE[i].length = 0 + POOL.UINT8C[i].length = 0 + DATA[i].length = 0 + BUFFER[i].length = 0 + } +} +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) +},{"bit-twiddle":12,"buffer":2,"dup":31}],33:[function(require,module,exports){ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.topojson = {}))); +}(this, function (exports) { 'use strict'; + + function noop() {} + + function absolute(transform) { + if (!transform) return noop; + var x0, + y0, + kx = transform.scale[0], + ky = transform.scale[1], + dx = transform.translate[0], + dy = transform.translate[1]; + return function(point, i) { + if (!i) x0 = y0 = 0; + point[0] = (x0 += point[0]) * kx + dx; + point[1] = (y0 += point[1]) * ky + dy; + }; + } + + function relative(transform) { + if (!transform) return noop; + var x0, + y0, + kx = transform.scale[0], + ky = transform.scale[1], + dx = transform.translate[0], + dy = transform.translate[1]; + return function(point, i) { + if (!i) x0 = y0 = 0; + var x1 = (point[0] - dx) / kx | 0, + y1 = (point[1] - dy) / ky | 0; + point[0] = x1 - x0; + point[1] = y1 - y0; + x0 = x1; + y0 = y1; + }; + } + + function reverse(array, n) { + var t, j = array.length, i = j - n; + while (i < --j) t = array[i], array[i++] = array[j], array[j] = t; + } + + function bisect(a, x) { + var lo = 0, hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (a[mid] < x) lo = mid + 1; + else hi = mid; + } + return lo; + } + + function feature(topology, o) { + return o.type === "GeometryCollection" ? { + type: "FeatureCollection", + features: o.geometries.map(function(o) { return feature$1(topology, o); }) + } : feature$1(topology, o); + } + + function feature$1(topology, o) { + var f = { + type: "Feature", + id: o.id, + properties: o.properties || {}, + geometry: object(topology, o) + }; + if (o.id == null) delete f.id; + return f; + } + + function object(topology, o) { + var absolute$$ = absolute(topology.transform), + arcs = topology.arcs; + + function arc(i, points) { + if (points.length) points.pop(); + for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length, p; k < n; ++k) { + points.push(p = a[k].slice()); + absolute$$(p, k); + } + if (i < 0) reverse(points, n); + } + + function point(p) { + p = p.slice(); + absolute$$(p, 0); + return p; + } + + function line(arcs) { + var points = []; + for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points); + if (points.length < 2) points.push(points[0].slice()); + return points; + } + + function ring(arcs) { + var points = line(arcs); + while (points.length < 4) points.push(points[0].slice()); + return points; + } + + function polygon(arcs) { + return arcs.map(ring); + } + + function geometry(o) { + var t = o.type; + return t === "GeometryCollection" ? {type: t, geometries: o.geometries.map(geometry)} + : t in geometryType ? {type: t, coordinates: geometryType[t](o)} + : null; + } + + var geometryType = { + Point: function(o) { return point(o.coordinates); }, + MultiPoint: function(o) { return o.coordinates.map(point); }, + LineString: function(o) { return line(o.arcs); }, + MultiLineString: function(o) { return o.arcs.map(line); }, + Polygon: function(o) { return polygon(o.arcs); }, + MultiPolygon: function(o) { return o.arcs.map(polygon); } + }; + + return geometry(o); + } + + function stitchArcs(topology, arcs) { + var stitchedArcs = {}, + fragmentByStart = {}, + fragmentByEnd = {}, + fragments = [], + emptyIndex = -1; + + // Stitch empty arcs first, since they may be subsumed by other arcs. + arcs.forEach(function(i, j) { + var arc = topology.arcs[i < 0 ? ~i : i], t; + if (arc.length < 3 && !arc[1][0] && !arc[1][1]) { + t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t; + } + }); + + arcs.forEach(function(i) { + var e = ends(i), + start = e[0], + end = e[1], + f, g; + + if (f = fragmentByEnd[start]) { + delete fragmentByEnd[f.end]; + f.push(i); + f.end = end; + if (g = fragmentByStart[end]) { + delete fragmentByStart[g.start]; + var fg = g === f ? f : f.concat(g); + fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg; + } else { + fragmentByStart[f.start] = fragmentByEnd[f.end] = f; + } + } else if (f = fragmentByStart[end]) { + delete fragmentByStart[f.start]; + f.unshift(i); + f.start = start; + if (g = fragmentByEnd[start]) { + delete fragmentByEnd[g.end]; + var gf = g === f ? f : g.concat(f); + fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf; + } else { + fragmentByStart[f.start] = fragmentByEnd[f.end] = f; + } + } else { + f = [i]; + fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f; + } + }); + + function ends(i) { + var arc = topology.arcs[i < 0 ? ~i : i], p0 = arc[0], p1; + if (topology.transform) p1 = [0, 0], arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; }); + else p1 = arc[arc.length - 1]; + return i < 0 ? [p1, p0] : [p0, p1]; + } + + function flush(fragmentByEnd, fragmentByStart) { + for (var k in fragmentByEnd) { + var f = fragmentByEnd[k]; + delete fragmentByStart[f.start]; + delete f.start; + delete f.end; + f.forEach(function(i) { stitchedArcs[i < 0 ? ~i : i] = 1; }); + fragments.push(f); + } + } + + flush(fragmentByEnd, fragmentByStart); + flush(fragmentByStart, fragmentByEnd); + arcs.forEach(function(i) { if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]); }); + + return fragments; + } + + function mesh(topology) { + return object(topology, meshArcs.apply(this, arguments)); + } + + function meshArcs(topology, o, filter) { + var arcs = []; + + function arc(i) { + var j = i < 0 ? ~i : i; + (geomsByArc[j] || (geomsByArc[j] = [])).push({i: i, g: geom}); + } + + function line(arcs) { + arcs.forEach(arc); + } + + function polygon(arcs) { + arcs.forEach(line); + } + + function geometry(o) { + if (o.type === "GeometryCollection") o.geometries.forEach(geometry); + else if (o.type in geometryType) geom = o, geometryType[o.type](o.arcs); + } + + if (arguments.length > 1) { + var geomsByArc = [], + geom; + + var geometryType = { + LineString: line, + MultiLineString: polygon, + Polygon: polygon, + MultiPolygon: function(arcs) { arcs.forEach(polygon); } + }; + + geometry(o); + + geomsByArc.forEach(arguments.length < 3 + ? function(geoms) { arcs.push(geoms[0].i); } + : function(geoms) { if (filter(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i); }); + } else { + for (var i = 0, n = topology.arcs.length; i < n; ++i) arcs.push(i); + } + + return {type: "MultiLineString", arcs: stitchArcs(topology, arcs)}; + } + + function triangle(triangle) { + var a = triangle[0], b = triangle[1], c = triangle[2]; + return Math.abs((a[0] - c[0]) * (b[1] - a[1]) - (a[0] - b[0]) * (c[1] - a[1])); + } + + function ring(ring) { + var i = -1, + n = ring.length, + a, + b = ring[n - 1], + area = 0; + + while (++i < n) { + a = b; + b = ring[i]; + area += a[0] * b[1] - a[1] * b[0]; + } + + return area / 2; + } + + function merge(topology) { + return object(topology, mergeArcs.apply(this, arguments)); + } + + function mergeArcs(topology, objects) { + var polygonsByArc = {}, + polygons = [], + components = []; + + objects.forEach(function(o) { + if (o.type === "Polygon") register(o.arcs); + else if (o.type === "MultiPolygon") o.arcs.forEach(register); + }); + + function register(polygon) { + polygon.forEach(function(ring$$) { + ring$$.forEach(function(arc) { + (polygonsByArc[arc = arc < 0 ? ~arc : arc] || (polygonsByArc[arc] = [])).push(polygon); + }); + }); + polygons.push(polygon); + } + + function exterior(ring$$) { + return ring(object(topology, {type: "Polygon", arcs: [ring$$]}).coordinates[0]) > 0; // TODO allow spherical? + } + + polygons.forEach(function(polygon) { + if (!polygon._) { + var component = [], + neighbors = [polygon]; + polygon._ = 1; + components.push(component); + while (polygon = neighbors.pop()) { + component.push(polygon); + polygon.forEach(function(ring$$) { + ring$$.forEach(function(arc) { + polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon) { + if (!polygon._) { + polygon._ = 1; + neighbors.push(polygon); + } + }); + }); + }); + } + } + }); + + polygons.forEach(function(polygon) { + delete polygon._; + }); + + return { + type: "MultiPolygon", + arcs: components.map(function(polygons) { + var arcs = [], n; + + // Extract the exterior (unique) arcs. + polygons.forEach(function(polygon) { + polygon.forEach(function(ring$$) { + ring$$.forEach(function(arc) { + if (polygonsByArc[arc < 0 ? ~arc : arc].length < 2) { + arcs.push(arc); + } + }); + }); + }); + + // Stitch the arcs into one or more rings. + arcs = stitchArcs(topology, arcs); + + // If more than one ring is returned, + // at most one of these rings can be the exterior; + // this exterior ring has the same winding order + // as any exterior ring in the original polygons. + if ((n = arcs.length) > 1) { + var sgn = exterior(polygons[0][0]); + for (var i = 0, t; i < n; ++i) { + if (sgn === exterior(arcs[i])) { + t = arcs[0], arcs[0] = arcs[i], arcs[i] = t; + break; + } + } + } + + return arcs; + }) + }; + } + + function neighbors(objects) { + var indexesByArc = {}, // arc index -> array of object indexes + neighbors = objects.map(function() { return []; }); + + function line(arcs, i) { + arcs.forEach(function(a) { + if (a < 0) a = ~a; + var o = indexesByArc[a]; + if (o) o.push(i); + else indexesByArc[a] = [i]; + }); + } + + function polygon(arcs, i) { + arcs.forEach(function(arc) { line(arc, i); }); + } + + function geometry(o, i) { + if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); }); + else if (o.type in geometryType) geometryType[o.type](o.arcs, i); + } + + var geometryType = { + LineString: line, + MultiLineString: polygon, + Polygon: polygon, + MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); } + }; + + objects.forEach(geometry); + + for (var i in indexesByArc) { + for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) { + for (var k = j + 1; k < m; ++k) { + var ij = indexes[j], ik = indexes[k], n; + if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik); + if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij); + } + } + } + + return neighbors; + } + + function compareArea(a, b) { + return a[1][2] - b[1][2]; + } + + function minAreaHeap() { + var heap = {}, + array = [], + size = 0; + + heap.push = function(object) { + up(array[object._ = size] = object, size++); + return size; + }; + + heap.pop = function() { + if (size <= 0) return; + var removed = array[0], object; + if (--size > 0) object = array[size], down(array[object._ = 0] = object, 0); + return removed; + }; + + heap.remove = function(removed) { + var i = removed._, object; + if (array[i] !== removed) return; // invalid request + if (i !== --size) object = array[size], (compareArea(object, removed) < 0 ? up : down)(array[object._ = i] = object, i); + return i; + }; + + function up(object, i) { + while (i > 0) { + var j = ((i + 1) >> 1) - 1, + parent = array[j]; + if (compareArea(object, parent) >= 0) break; + array[parent._ = i] = parent; + array[object._ = i = j] = object; + } + } + + function down(object, i) { + while (true) { + var r = (i + 1) << 1, + l = r - 1, + j = i, + child = array[j]; + if (l < size && compareArea(array[l], child) < 0) child = array[j = l]; + if (r < size && compareArea(array[r], child) < 0) child = array[j = r]; + if (j === i) break; + array[child._ = i] = child; + array[object._ = i = j] = object; + } + } + + return heap; + } + + function presimplify(topology, triangleArea) { + var absolute$$ = absolute(topology.transform), + relative$$ = relative(topology.transform), + heap = minAreaHeap(); + + if (!triangleArea) triangleArea = triangle; + + topology.arcs.forEach(function(arc) { + var triangles = [], + maxArea = 0, + triangle, + i, + n, + p; + + // To store each point’s effective area, we create a new array rather than + // extending the passed-in point to workaround a Chrome/V8 bug (getting + // stuck in smi mode). For midpoints, the initial effective area of + // Infinity will be computed in the next step. + for (i = 0, n = arc.length; i < n; ++i) { + p = arc[i]; + absolute$$(arc[i] = [p[0], p[1], Infinity], i); + } + + for (i = 1, n = arc.length - 1; i < n; ++i) { + triangle = arc.slice(i - 1, i + 2); + triangle[1][2] = triangleArea(triangle); + triangles.push(triangle); + heap.push(triangle); + } + + for (i = 0, n = triangles.length; i < n; ++i) { + triangle = triangles[i]; + triangle.previous = triangles[i - 1]; + triangle.next = triangles[i + 1]; + } + + while (triangle = heap.pop()) { + var previous = triangle.previous, + next = triangle.next; + + // If the area of the current point is less than that of the previous point + // to be eliminated, use the latter's area instead. This ensures that the + // current point cannot be eliminated without eliminating previously- + // eliminated points. + if (triangle[1][2] < maxArea) triangle[1][2] = maxArea; + else maxArea = triangle[1][2]; + + if (previous) { + previous.next = next; + previous[2] = triangle[2]; + update(previous); + } + + if (next) { + next.previous = previous; + next[0] = triangle[0]; + update(next); + } + } + + arc.forEach(relative$$); + }); + + function update(triangle) { + heap.remove(triangle); + triangle[1][2] = triangleArea(triangle); + heap.push(triangle); + } + + return topology; + } + + var version = "1.6.24"; + + exports.version = version; + exports.mesh = mesh; + exports.meshArcs = meshArcs; + exports.merge = merge; + exports.mergeArcs = mergeArcs; + exports.feature = feature; + exports.neighbors = neighbors; + exports.presimplify = presimplify; + +})); +},{}],34:[function(require,module,exports){ +var colorSort; + +colorSort = require("../color/sort.coffee"); + +module.exports = function(a, b, keys, sort, colors, vars, depth) { + var i, k, retVal; + if (!sort) { + sort = "asc"; + } + if (!(colors instanceof Array)) { + colors = [colors]; + } + if (!(keys instanceof Array)) { + keys = [keys]; + } + if (vars && depth !== void 0 && typeof depth !== "number") { + depth = vars.id.nesting.indexOf(depth); + } + retVal = 0; + i = 0; + while (i < keys.length) { + k = keys[i]; + a = vars && a.d3plus && a.d3plus.sortKeys ? a.d3plus.sortKeys[k] : a[k]; + b = vars && b.d3plus && b.d3plus.sortKeys ? b.d3plus.sortKeys[k] : b[k]; + if (vars && colors.indexOf(k) >= 0) { + retVal = colorSort(a, b); + } else { + retVal = a < b ? -1 : 1; + } + if (retVal !== 0 || i === keys.length - 1) { + break; + } + i++; + } + if (sort === "asc") { + return retVal; + } else { + return -retVal; + } +}; + + +},{"../color/sort.coffee":51}],35:[function(require,module,exports){ +module.exports = function(arr, value) { + var constructor; + if (arr instanceof Array) { + constructor = value === void 0 || value === null ? value : value.constructor; + return arr.indexOf(value) >= 0 || arr.indexOf(constructor) >= 0; + } else { + return false; + } +}; + + +},{}],36:[function(require,module,exports){ +var comparator, fetchSort; + +comparator = require("./comparator.coffee"); + +fetchSort = require("../core/fetch/sort.coffee"); + +module.exports = function(arr, keys, sort, colors, vars, depth) { + var d, data, i, len; + if (!arr || arr.length <= 1) { + return arr || []; + } else { + if (vars) { + if (!keys) { + keys = vars.order.value || vars.size.value || vars.id.value; + } + if (!sort) { + sort = vars.order.sort.value; + } + if (!colors) { + colors = vars.color.value || []; + } + for (i = 0, len = arr.length; i < len; i++) { + d = arr[i]; + if (!d.d3plus) { + d.d3plus = {}; + } + data = "d3plus" in d && "d3plus" in d.d3plus ? d.d3plus : d; + d.d3plus.sortKeys = fetchSort(vars, data, keys, colors, depth); + } + } + return arr.sort(function(a, b) { + return comparator(a, b, keys, sort, colors, vars, depth); + }); + } +}; + + +},{"../core/fetch/sort.coffee":67,"./comparator.coffee":34}],37:[function(require,module,exports){ +module.exports = function(arr, x) { + if (x === void 0) { + return arr; + } + if (x === false) { + return []; + } + if (x instanceof Array) { + return x; + } + if (!(arr instanceof Array)) { + arr = []; + } + if (arr.indexOf(x) >= 0) { + arr.splice(arr.indexOf(x), 1); + } else { + arr.push(x); + } + return arr; +}; + + +},{}],38:[function(require,module,exports){ +var sheet; + +sheet = function(name) { + var css, i, returnBoolean, tested; + tested = sheet.tested; + if (name in tested) { + return tested[name]; + } + i = 0; + returnBoolean = false; + while (i < document.styleSheets.length) { + css = document.styleSheets[i]; + if (css.href && css.href.indexOf(name) >= 0) { + returnBoolean = true; + break; + } + i++; + } + return returnBoolean; +}; + +sheet.tested = {}; + +module.exports = sheet; + + +},{}],39:[function(require,module,exports){ +// Determines if the current browser is Internet Explorer. +module.exports = /(MSIE|Trident\/|Edge\/)/i.test(navigator.userAgent); + +},{}],40:[function(require,module,exports){ +var ie, touch; + +ie = require("./ie.js"); + +touch = require("./touch.coffee"); + +if (touch) { + module.exports = { + click: "click", + down: "touchstart", + up: "touchend", + over: ie ? "mouseenter" : "mouseover", + out: ie ? "mouseleave" : "mouseout", + move: "mousemove" + }; +} else { + module.exports = { + click: "click", + down: "mousedown", + up: "mouseup", + over: ie ? "mouseenter" : "mouseover", + out: ie ? "mouseleave" : "mouseout", + move: "mousemove" + }; +} + + +},{"./ie.js":39,"./touch.coffee":45}],41:[function(require,module,exports){ +var prefix; + +prefix = function() { + var val; + if ("-webkit-transform" in document.body.style) { + val = "-webkit-"; + } else if ("-moz-transform" in document.body.style) { + val = "-moz-"; + } else if ("-ms-transform" in document.body.style) { + val = "-ms-"; + } else if ("-o-transform" in document.body.style) { + val = "-o-"; + } else { + val = ""; + } + prefix = function() { + return val; + }; + return val; +}; + +module.exports = prefix; + + +},{}],42:[function(require,module,exports){ +module.exports = d3.select("html").attr("dir") === "rtl"; + + +},{}],43:[function(require,module,exports){ +module.exports = { + "y": function() { + return (window.pageYOffset !== undefined) ? window.pageYOffset : + (document.documentElement || document.body.parentNode || document.body).scrollTop + }, + "x": function() { + return (window.pageXOffset !== undefined) ? window.pageXOffset : + (document.documentElement || document.body.parentNode || document.body).scrollLeft + } +} + +},{}],44:[function(require,module,exports){ +var scrollbar; + +scrollbar = function() { + var inner, outer, val, w1, w2; + inner = document.createElement("p"); + inner.style.width = "100%"; + inner.style.height = "200px"; + outer = document.createElement("div"); + outer.style.position = "absolute"; + outer.style.top = "0px"; + outer.style.left = "0px"; + outer.style.visibility = "hidden"; + outer.style.width = "200px"; + outer.style.height = "150px"; + outer.style.overflow = "hidden"; + outer.appendChild(inner); + document.body.appendChild(outer); + w1 = inner.offsetWidth; + outer.style.overflow = "scroll"; + w2 = inner.offsetWidth; + if (w1 === w2) { + w2 = outer.clientWidth; + } + document.body.removeChild(outer); + val = w1 - w2; + scrollbar = function() { + return val; + }; + return val; +}; + +module.exports = scrollbar; + + +},{}],45:[function(require,module,exports){ +module.exports = ("ontouchstart" in window) || window.DocumentTouch && document instanceof DocumentTouch ? true : false; + + +},{}],46:[function(require,module,exports){ +module.exports = function(color) { + var hsl; + hsl = d3.hsl(color); + if (hsl.l > .45) { + if (hsl.s > .8) { + hsl.s = 0.8; + } + hsl.l = 0.45; + } + return hsl.toString(); +}; + + +},{}],47:[function(require,module,exports){ +module.exports = function(color, increment) { + var c; + if (increment === void 0) { + increment = 0.5; + } + c = d3.hsl(color); + increment = (1 - c.l) * increment; + c.l += increment; + c.s -= increment; + return c.toString(); +}; + + +},{}],48:[function(require,module,exports){ +module.exports = function(c1, c2, o1, o2) { + var b, g, r; + if (!o1) { + o1 = 1; + } + if (!o2) { + o2 = 1; + } + c1 = d3.rgb(c1); + c2 = d3.rgb(c2); + r = (o1 * c1.r + o2 * c2.r - o1 * o2 * c2.r) / (o1 + o2 - o1 * o2); + g = (o1 * c1.g + o2 * c2.g - o1 * o2 * c2.g) / (o1 + o2 - o1 * o2); + b = (o1 * c1.b + o2 * c2.b - o1 * o2 * c2.b) / (o1 + o2 - o1 * o2); + return d3.rgb(r, g, b).toString(); +}; + + +},{}],49:[function(require,module,exports){ +var defaultScale; + +defaultScale = require("./scale.coffee"); + +module.exports = function(x, scale) { + var rand_int; + rand_int = x || Math.floor(Math.random() * 20); + scale = scale || defaultScale; + return scale(rand_int); +}; + + +},{"./scale.coffee":50}],50:[function(require,module,exports){ +module.exports = d3.scale.ordinal().range(["#b22200", "#282F6B", "#EACE3F", "#B35C1E", "#224F20", "#5F487C", "#759143", "#419391", "#993F88", "#e89c89", "#ffee8d", "#afd5e8", "#f7ba77", "#a5c697", "#c5b5e5", "#d1d392", "#bbefd0", "#e099cf"]); + + +},{}],51:[function(require,module,exports){ +module.exports = function(a, b) { + var aHSL, bHSL; + aHSL = d3.hsl(a); + bHSL = d3.hsl(b); + a = aHSL.s === 0 ? 361 : aHSL.h; + b = bHSL.s === 0 ? 361 : bHSL.h; + if (a === b) { + return aHSL.l - bHSL.l; + } else { + return a - b; + } +}; + + +},{}],52:[function(require,module,exports){ +module.exports = function(color) { + var b, g, r, rgbColor, yiq; + rgbColor = d3.rgb(color); + r = rgbColor.r; + g = rgbColor.g; + b = rgbColor.b; + yiq = (r * 299 + g * 587 + b * 114) / 1000; + if (yiq >= 128) { + return "#444444"; + } else { + return "#f7f7f7"; + } +}; + + +},{}],53:[function(require,module,exports){ +module.exports = function(color) { + var blackColors, testColor, userBlack; + color = color + ""; + color = color.replace(RegExp(" ", "g"), ""); + if (color.indexOf("rgb") === 0) { + color = color.split("(")[1].split(")")[0].split(",").slice(0, 3).join(","); + } + if (color.indexOf("hsl") === 0) { + color = color.split(",")[2].split(")")[0]; + } + testColor = d3.rgb(color).toString(); + blackColors = ["black", "#000", "#000000", "0%", "0,0,0"]; + userBlack = blackColors.indexOf(color) >= 0; + return testColor !== "#000000" || userBlack; +}; + + +},{}],54:[function(require,module,exports){ +var ie, print, wiki; + +ie = require("../../client/ie.js"); + +wiki = require("./wiki.coffee"); + +print = function(type, message, style) { + style = style || ""; + if (ie || typeof InstallTrigger !== 'undefined') { + console.log("[ D3plus ] " + message); + } else if (type.indexOf("group") === 0) { + console[type]("%c[ D3plus ]%c " + message, "font-weight: 800;" + "color: #b35c1e;" + "margin-left: 0px;", "font-weight:200;" + style); + } else { + console[type]("%c" + message, style + "font-weight:200;"); + } +}; + +print.comment = function(message) { + this("log", message, "color:#aaa;"); +}; + +print.error = function(message, url) { + this("groupCollapsed", "ERROR: " + message, "font-weight:800;color:#D74B03;"); + this.stack(); + this.wiki(url); + this.groupEnd(); +}; + +print.group = function(message) { + this("group", message, "color:#888;"); +}; + +print.groupCollapsed = function(message) { + this("groupCollapsed", message, "color:#888;"); +}; + +print.groupEnd = function() { + if (!ie) { + console.groupEnd(); + } +}; + +print.log = function(message) { + this("log", message, "color:#444444;"); +}; + +print.stack = function() { + var err, line, message, page, splitter, stack, url; + if (!ie) { + err = new Error(); + if (err.stack) { + stack = err.stack.split("\n"); + stack = stack.filter(function(e) { + return e.indexOf("Error") !== 0 && e.indexOf("d3plus.js:") < 0 && e.indexOf("d3plus.min.js:") < 0; + }); + if (stack.length && stack[0].length) { + splitter = window.chrome ? "at " : "@"; + url = stack[0]; + if (url.indexOf(splitter) >= 0) { + url = url.split(splitter)[1]; + } + stack = url.split(":"); + if (stack.length === 3) { + stack.pop(); + } + line = stack.pop(); + page = stack.join(":").split("/"); + page = page[page.length - 1]; + message = "line " + line + " of " + page + ": " + url; + this("log", message, "color:#D74B03;"); + } + } + } +}; + +print.time = function(message) { + if (!ie) { + console.time(message); + } +}; + +print.timeEnd = function(message) { + if (!ie) { + console.timeEnd(message); + } +}; + +print.warning = function(message, url) { + this("groupCollapsed", message, "color:#888;"); + this.stack(); + this.wiki(url); + this.groupEnd(); +}; + +print.wiki = function(url) { + if (url) { + if (url in wiki) { + url = d3plus.repo + "wiki/" + wiki[url]; + } + this("log", "documentation: " + url, "color:#aaa;"); + } +}; + +module.exports = print; + + +},{"../../client/ie.js":39,"./wiki.coffee":55}],55:[function(require,module,exports){ +module.exports = { + active: "Visualizations#active", + aggs: "Visualizations#aggs", + alt: "Forms#alt", + attrs: "Visualizations#attrs", + axes: "Visualizations#axes", + background: "Visualizations#background", + color: "Visualizations#color", + cols: "Visualizations#cols", + config: "Visualizations#config", + container: "Visualizations#container", + coords: "Visualizations#coords", + csv: "Visualizations#csv", + data: "Visualizations#data", + depth: "Visualizations#depth", + descs: "Visualizations#descs", + dev: "Visualizations#dev", + draw: "Visualizations#draw", + edges: "Visualizations#edges", + error: "Visualizations#error", + focus: "Visualizations#focus", + font: "Visualizations#font", + footer: "Visualizations#footer", + format: "Visualizations#format", + height: "Visualizations#height", + history: "Visualizations#history", + hover: "Forms#hover", + icon: "Visualizations#icon", + id: "Visualizations#id", + keywords: "Forms#keywords", + labels: "Visualizations#labels", + legend: "Visualizations#legend", + links: "Visualizations#links", + margin: "Visualizations#margin", + messages: "Visualizations#messages", + method: "Methods", + mouse: "Visualizations#mouse", + nodes: "Visualizations#nodes", + open: "Forms#open", + order: "Visualizations#order", + remove: "Forms#remove", + search: "Forms#search", + select: "Forms#select", + selectAll: "Forms#selectAll", + shape: "Visualizations#shape", + size: "Visualizations#size", + temp: "Visualizations#temp", + text: "Visualizations#text", + time: "Visualizations#time", + timeline: "Visualizations#timeline", + timing: "Visualizations#timing", + title: "Visualizations#title", + tooltip: "Visualizations#tooltip", + total: "Visualizations#total", + type: "Visualizations#type", + ui: "Visualizations#ui", + width: "Visualizations#width", + x: "Visualizations#x", + y: "Visualizations#y", + zoom: "Visualizations#zoom" +}; + + +},{}],56:[function(require,module,exports){ +var buckets = require("../../util/buckets.coffee"), + fetchValue = require("../fetch/value.coffee"), + print = require("../console/print.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Sets color range of data, if applicable +//------------------------------------------------------------------- +module.exports = function(vars) { + + if ( vars.dev.value ) print.time("getting color data range") + + if (vars.color.domain.value) { + var data_range = vars.color.domain.value; + } + else { + var data_range = [] + vars.data.pool.forEach(function(d){ + var val = parseFloat(fetchValue(vars,d,vars.color.value)) + if (typeof val == "number" && !isNaN(val) && data_range.indexOf(val) < 0) data_range.push(val) + }) + } + + if ( vars.dev.value ) print.timeEnd("getting color data range") + + if (data_range.length > 1) { + + var data_domain = null + + if ( vars.dev.value ) print.time("calculating color scale") + + data_range = d3.extent(data_range); + + if (data_range[0] < 0 && data_range[1] > 0) { + var color_range = vars.color.range + if (color_range.length == 3) { + data_range.push(data_range[1]) + data_range[1] = 0 + } + } + else if (data_range[1] > 0 && data_range[0] >= 0) { + var color_range = vars.color.heatmap + data_range = buckets(data_range,color_range.length) + } + else { + var color_range = vars.color.range.slice(0) + if (data_range[0] < 0) { + color_range.pop() + } + else { + color_range.shift() + } + } + + vars.color.valueScale = d3.scale.sqrt() + .domain(data_range) + .range(color_range) + .interpolate(d3.interpolateRgb) + + if ( vars.dev.value ) print.timeEnd("calculating color scale") + + } + else { + vars.color.valueScale = null + } + +} + +},{"../../util/buckets.coffee":207,"../console/print.coffee":54,"../fetch/value.coffee":69}],57:[function(require,module,exports){ +var fetchValue = require("../fetch/value.coffee"), + print = require("../console/print.coffee"), + validObject = require("../../object/validate.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Restricts data based on Solo/Mute filters +//------------------------------------------------------------------------------ +module.exports = function( vars , data ) { + + if ( vars.dev.value ) print.time("filtering data") + + var availableKeys = d3.keys(vars.data.keys || {}) + + if ( "attrs" in vars ) { + availableKeys = availableKeys.concat(d3.keys(vars.attrs.keys || {})) + } + + data = data.filter(function(d){ + var val = fetchValue(vars, d, vars.id.value); + return val !== null; + }); + + var typeReqs = vars.types[vars.type.value].requirements || []; + + vars.data.filters.forEach( function( key ) { + + if (availableKeys.indexOf(vars[key].value) >= 0 && + typeReqs.indexOf(key) >= 0) { + + data = data.filter( function( d ) { + + var val = fetchValue(vars,d,vars[key].value); + + if (key === "y" && vars.y2.value && val === null) { + val = fetchValue(vars,d,vars.y2.value); + } + else if (key === "x" && vars.x2.value && val === null) { + val = fetchValue(vars,d,vars.x2.value); + } + + if ( key === "size" ) { + return typeof val === "number" + } + else { + return val !== null + } + + }) + + } + + }); + + // if "solo", only check against "solo" (disregard "mute") + var key = vars.data.solo.length ? "solo" : "mute"; + + if (vars.data[key].length) { + + vars.data[key].forEach(function(v) { + + function test_value(val) { + + var arr = vars[v][key].value; + + var match = false; + arr.forEach(function(f){ + if (typeof f === "function") { + match = f(val); + } + else if (f === val) { + match = true; + } + + }) + + return key === "solo" ? match : !match; + + } + + function filter_data(d, flat) { + if (!flat && vars[v].nesting) { + var nesting = vars[v].nesting; + if (validObject(nesting)) { + nesting = d3.values(nesting); + } + for (var n = 0; n < nesting.length; n++) { + var new_data = d.filter(function(dd){ + return test_value(fetchValue(vars, dd, nesting[n])); + }); + if (new_data.length) d = new_data; + } + } + else { + d = d.filter(function(dd){ + return test_value(fetchValue(vars, dd, vars[v].value)); + }); + } + return d; + } + + data = filter_data(data); + + if ( v === "id" ) { + + if ("nodes" in vars && vars.nodes.value) { + if ( vars.dev.value ) print.time("filtering nodes") + vars.nodes.restricted = filter_data(vars.nodes.value); + if ( vars.dev.value ) print.timeEnd("filtering nodes") + } + + if ("edges" in vars && vars.edges.value) { + if ( vars.dev.value ) print.time("filtering edges") + vars.edges.restricted = vars.edges.value.filter(function(d){ + var points = filter_data([d[vars.edges.source], d[vars.edges.target]]); + return points.length === 2; + }) + if ( vars.dev.value ) print.timeEnd("filtering edges") + } + + } + + }) + + } + else if ("nodes" in vars) { + vars.nodes.restricted = undefined; + vars.edges.restricted = undefined; + } + + if ( vars.dev.value ) print.timeEnd("filtering data") + + return data + +} + +},{"../../object/validate.coffee":175,"../console/print.coffee":54,"../fetch/value.coffee":69}],58:[function(require,module,exports){ +var dataNest = require("./nest.js"), + fetchValue = require("../fetch/value.coffee"), + print = require("../console/print.coffee"), + uniques = require("../../util/uniques.coffee"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Formats raw data by time and nesting +//------------------------------------------------------------------------------ +module.exports = function( vars ) { + + var timerString; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Gets all unique time values + //---------------------------------------------------------------------------- + vars.data.time = {"values": []}; + if (vars.time && vars.time.value) { + + if ( vars.dev.value ) { + timerString = "analyzing time periods"; + print.time( timerString ); + } + + vars.data.time.values = uniques(vars.data.value, vars.time.value, fetchValue, vars); + + vars.data.time.values.sort(function(a,b){ return a-b; }); + + var step = []; + vars.data.time.values.forEach(function(y,i){ + if (i !== 0) { + var prev = vars.data.time.values[i-1]; + step.push(y-prev); + if (i === vars.data.time.values.length - 1) { + vars.data.time.total = y - vars.data.time.values[0]; + } + } + }); + + step = d3.min(step); + vars.data.time.step = step; + + var periods = ["Milliseconds","Seconds","Minutes","Hours","Date","Month","FullYear"], + conversions = [1000,60,60,24,30,12,1]; + + vars.data.time.periods = periods; + + var getDiff = function(start,end,i) { + + if (!vars.data.time.stepDivider) { + arr = conversions.slice(0,i); + if (arr.length) { + vars.data.time.stepDivider = arr.reduce(function(a,b){ return a*b; }); + } + else { + vars.data.time.stepDivider = 1; + } + } + + return Math.round(Math.floor(end-start)/vars.data.time.stepDivider); + + }; + + var total = vars.data.time.total; + periods.forEach(function(p,i){ + var c = p === "Date" ? 28 : conversions[i]; + if (!vars.data.time.stepType && (i === periods.length-1 || Math.round(step) < c)) { + vars.data.time.stepType = p; + var start = vars.data.time.values[0], + end = vars.data.time.values[vars.data.time.values.length-1]; + vars.data.time.stepIntervals = getDiff(start,end,i); + } + + if (!vars.data.time.totalType && (i === periods.length-1 || Math.round(total) < c)) { + vars.data.time.totalType = p; + } + + step = step/c; + total = total/c; + }); + + vars.data.time.values.forEach(function(y,i){ + if (i !== 0) { + var prev = vars.data.time.values[0]; + vars.data.time.dataSteps.push(getDiff(prev,y,periods.indexOf(vars.data.time.stepType))); + } + else { + vars.data.time.dataSteps = [0]; + } + }); + + var userFormat = vars.time.format.value, + locale = vars.format.locale.value, + functions = [ + function(d) { return d.getMilliseconds(); }, + function(d) { return d.getSeconds(); }, + function(d) { return d.getMinutes(); }, + function(d) { return d.getHours(); }, + function(d) { return d.getDate() != 1; }, + function(d) { return d.getMonth(); }, + function(d) { return true; } + ]; + + vars.data.time.functions = functions; + + var getFormat = function(s,t,small) { + + if (s === t) { + return small && locale.timeFormat[s+"Small"] ? locale.timeFormat[s+"Small"] : locale.timeFormat[s]; + } + else { + if (periods.indexOf(s) >= 4 || periods.indexOf(t) <= 3) { + return locale.timeFormat[t+"-"+s]; + } + else { + + var format; + + if (t === "Date") { + format = locale.timeFormat[t]; + } + else { + format = locale.timeFormat[t+"-Date"]; + } + + if (s === "Hours") { + return format +" "+ locale.timeFormat[s]; + } + else { + return format +" "+ locale.timeFormat["Hours-"+s]; + } + + } + } + + }; + + vars.data.time.getFormat = getFormat; + + if (userFormat) { + + if (typeof userFormat === "string") { + vars.data.time.format = d3.locale(locale.format).timeFormat(userFormat); + } + else if (typeof userFormat === "function") { + vars.data.time.format = userFormat; + } + else if (userFormat instanceof Array) { + vars.data.time.format = d3.locale(locale.format).timeFormat.multi(userFormat); + } + vars.data.time.multiFormat = vars.data.time.format; + + } + else { + + var stepType = vars.data.time.stepType, + totalType = vars.data.time.totalType; + + var multi = []; + + for (var p = periods.indexOf(stepType); p <= periods.indexOf(totalType); p++) { + var prev = p-1 < periods.indexOf(stepType) ? periods[p] : periods[p-1]; + var small = periods[p] === prev && stepType !== totalType; + var format = getFormat(prev,periods[p],small); + multi.push([format,functions[p]]); + } + + vars.data.time.format = d3.locale(locale.format).timeFormat(getFormat(stepType,totalType)); + if (multi.length > 1) { + multi[multi.length-1][1] = function (d) { return true; } + vars.data.time.multiFormat = d3.locale(locale.format).timeFormat.multi(multi); + } + else { + vars.data.time.multiFormat = vars.data.time.format; + } + + } + + vars.data.time.ticks = []; + var min = d3.min(vars.data.time.values); + var max = d3.max(vars.data.time.values); + for (var s = 0; s <= vars.data.time.stepIntervals; s++) { + var m = new Date(min); + m["set"+vars.data.time.stepType](m["get"+vars.data.time.stepType]() + s); + if (m <= max) vars.data.time.ticks.push(m); + } + + if ( vars.dev.value ) print.timeEnd( timerString ); + + } + + if ( vars.dev.value ) { + timerString = "nesting data by time and depths"; + print.time( timerString ); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Gets all unique time values + //---------------------------------------------------------------------------- + vars.data.nested = {}; + if (vars.data.time.values.length === 0) { + + vars.data.nested.all = {}; + vars.id.nesting.forEach( function( depth , i ) { + + var nestingDepth = vars.id.nesting.slice( 0 , i + 1 ); + vars.data.nested.all[ depth ] = dataNest(vars, vars.data.value, nestingDepth); + + }); + + } + else { + + var timeData = vars.data.value.reduce(function(o, d){ + var ms = fetchValue(vars, d, vars.time.value).getTime(); + if (!(ms in o)) o[ms] = []; + o[ms].push(d); + return o; + }, {}); + + vars.data.time.values.forEach( function( t ) { + + var ms = t.getTime(); + + vars.data.nested[ms] = {}; + + vars.id.nesting.forEach( function( depth , i ) { + var nestingDepth = vars.id.nesting.slice(0, i + 1); + vars.data.nested[ ms ][ depth ] = dataNest(vars, timeData[ms], nestingDepth); + }); + + }); + + } + + if ( vars.dev.value ) print.timeEnd( timerString ); + +}; + +},{"../../util/uniques.coffee":213,"../console/print.coffee":54,"../fetch/value.coffee":69,"./nest.js":62}],59:[function(require,module,exports){ +var fetchValue; + +fetchValue = require("../fetch/value.coffee"); + +module.exports = function(vars, data, nesting) { + var d, groupedData, i, j, k, len, len1, n, strippedData, val; + groupedData = d3.nest(); + if (vars.id.grouping.value) { + if (nesting === void 0) { + nesting = vars.id.nesting; + } + for (i = j = 0, len = nesting.length; j < len; i = ++j) { + n = nesting[i]; + if (i < vars.depth.value) { + (function(n) { + return groupedData.key(function(d) { + return fetchValue(vars, d.d3plus, n); + }); + })(n); + } + } + } + strippedData = []; + for (k = 0, len1 = data.length; k < len1; k++) { + d = data[k]; + val = vars.size.value ? fetchValue(vars, d, vars.size.value) : 1; + if (val && typeof val === "number" && val > 0) { + delete d.d3plus.r; + delete d.d3plus.x; + delete d.d3plus.y; + strippedData.push({ + d3plus: d, + id: d[vars.id.value], + value: val + }); + } + } + return groupedData.entries(strippedData); +}; + + +},{"../fetch/value.coffee":69}],60:[function(require,module,exports){ +var print, validObject, + indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; + +print = require("../console/print.coffee"); + +validObject = require("../../object/validate.coffee"); + +module.exports = function(vars, type) { + var get_keys, k, kk, lengthMatch, ref, ref1, timerString, v, vv; + timerString = type + " key analysis"; + if (vars.dev.value) { + print.time(timerString); + } + vars[type].keys = {}; + get_keys = function(arr) { + var a, i, k, len, results, results1, v; + if (arr instanceof Array) { + results = []; + for (i = 0, len = arr.length; i < len; i++) { + a = arr[i]; + results.push(get_keys(a)); + } + return results; + } else if (validObject(arr)) { + results1 = []; + for (k in arr) { + v = arr[k]; + if (k.indexOf("d3plus") !== 0 && !(indexOf.call(vars[type].keys, k) >= 0) && v !== null) { + results1.push(vars[type].keys[k] = typeof v); + } else { + results1.push(void 0); + } + } + return results1; + } + }; + if (validObject(vars[type].value)) { + lengthMatch = d3.keys(vars[type].value).length === vars.id.nesting.length; + ref = vars[type].value; + for (k in ref) { + v = ref[k]; + if (lengthMatch && vars.id.nesting.indexOf(k) >= 0 && validObject(v)) { + for (kk in v) { + vv = v[kk]; + get_keys(vv); + } + } else { + get_keys(v); + } + } + } else { + ref1 = vars[type].value; + for (k in ref1) { + v = ref1[k]; + get_keys(v); + } + } + if (vars.dev.value) { + return print.time(timerString); + } +}; + + +},{"../../object/validate.coffee":175,"../console/print.coffee":54}],61:[function(require,module,exports){ +var print, validObject; + +print = require("../console/print.coffee"); + +validObject = require("../../object/validate.coffee"); + +module.exports = function(vars, key, next) { + var consoleMessage, fileType, parser, url; + consoleMessage = vars.dev.value; + if (consoleMessage) { + print.time("loading " + key); + } + url = vars[key].url; + if (!vars[key].filetype.value) { + fileType = url.slice(url.length - 5).split("."); + if (fileType.length > 1) { + fileType = fileType[1]; + } else { + fileType = false; + } + if (fileType) { + if (fileType === "txt") { + fileType = "text"; + } + if (vars[key].filetype.accepted.indexOf(fileType) < 0) { + fileType = "json"; + } + } else { + fileType = "json"; + } + } else { + fileType = vars[key].filetype.value; + } + if (fileType === "dsv") { + parser = d3.dsv(vars[key].delimiter.value, "text/plain"); + } else { + parser = d3[fileType]; + } + return parser(url, function(error, data) { + var k, ret; + if (!error && data) { + if (typeof vars[key].callback === "function") { + ret = vars[key].callback(data); + if (ret) { + if (validObject(ret) && key in ret) { + for (k in ret) { + if (k in vars) { + vars[k].value = ret[k]; + } + } + } else { + vars[key].value = ret; + } + } + } else { + vars[key].value = data; + } + if (["json"].indexOf(fileType) < 0) { + vars[key].value.forEach(function(d) { + var results; + results = []; + for (k in d) { + if (!isNaN(d[k])) { + results.push(d[k] = parseFloat(d[k])); + } else if (d[k].toLowerCase() === "false") { + results.push(d[k] = false); + } else if (d[k].toLowerCase() === "true") { + results.push(d[k] = true); + } else if (d[k].toLowerCase() === "null") { + results.push(d[k] = null); + } else { + if (d[k].toLowerCase() === "undefined") { + results.push(d[k] = void 0); + } else { + results.push(void 0); + } + } + } + return results; + }); + } + vars[key].changed = true; + vars[key].loaded = true; + } else { + vars.error.internal = "Could not load data from: \"" + url + "\""; + } + if (consoleMessage) { + print.timeEnd("loading " + key); + } + return next(); + }); +}; + + +},{"../../object/validate.coffee":175,"../console/print.coffee":54}],62:[function(require,module,exports){ +var fetchValue = require("../fetch/value.coffee"), + validObject = require("../../object/validate.coffee"), + uniqueValues = require("../../util/uniques.coffee"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Nests and groups the data. +//------------------------------------------------------------------------------ +var dataNest = function(vars, flatData, nestingLevels, discrete) { + + if (discrete === undefined) discrete = true; + + var nestedData = d3.nest(), + groupedData = [], + segments = "temp" in vars ? [ "active" , "temp" , "total" ] : []; + + if (!nestingLevels.length) { + nestedData.key(function(d){ return true; }); + } + else { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Loop through each nesting level. + //---------------------------------------------------------------------------- + nestingLevels.forEach(function(level, i){ + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create a nest key for the current level. + //-------------------------------------------------------------------------- + nestedData.key(function(d){ return fetchValue(vars, d, level); }); + + }); + + } + + if (discrete && vars.axes && vars.axes.discrete && (!vars.time || vars[vars.axes.discrete].value !== vars.time.value)) { + nestedData.key(function(d){ + return fetchValue(vars, d, vars[vars.axes.discrete].value); + }); + } + + var deepest_is_id = nestingLevels.length && vars.id.nesting.indexOf(nestingLevels[nestingLevels.length - 1]) >= 0; + var i = nestingLevels.length && deepest_is_id ? nestingLevels.length - 1 : 0; + var depthKey = deepest_is_id ? vars.id.nesting[i] : vars.depth.value; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If we're at the deepest level, create the rollup function. + //---------------------------------------------------------------------------- + nestedData.rollup(function(leaves) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If there's only 1 leaf, and it's been processed, return it as-is. + //-------------------------------------------------------------------------- + if (leaves.length === 1 && ("d3plus" in leaves[0])) { + groupedData.push(leaves[0]); + return leaves[0]; + } + + leaves = leaves.reduce(function(arr, ll){ + if (ll.values instanceof Array) { + return arr.concat(ll.values); + } + arr.push(ll); + return arr; + }, []); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create the "d3plus" object for the return variable, starting with + // just the current depth. + //-------------------------------------------------------------------------- + var returnObj = { + "d3plus": { + "data": {}, + "depth": i + } + }; + + var merged = d3.sum(leaves, function(ll){ return "d3plus" in ll && ll.d3plus.merged ? 1 : 0; }); + + if (merged === leaves.length) { + for (var ll = 0; ll < leaves.length; ll++) { + var l = leaves[ll]; + if (!returnObj.d3plus.merged) returnObj.d3plus.merged = []; + returnObj.d3plus.merged = returnObj.d3plus.merged.concat(l.d3plus.merged); + if (l.d3plus.text) returnObj.d3plus.text = l.d3plus.text; + } + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create a reference sum for the 3 different "segment" variables. + //-------------------------------------------------------------------------- + for (var s = 0; s < segments.length; s++) { + + var c = segments[s]; + var segmentAgg = vars.aggs && vars.aggs.value[key] ? vars.aggs.value[key] : "sum"; + + if ("d3plus" in leaves[0] && c in leaves[0].d3plus) { + returnObj.d3plus[c] = d3.sum(leaves, function(d){ + return d.d3plus[c]; + }); + } + else if (typeof segmentAgg === "function") { + returnObj.d3plus[c] = segmentAgg(leaves); + } + else { + + returnObj.d3plus[c] = d3[segmentAgg](leaves, function(d) { + + var a = c === "total" ? 1 : 0; + if (vars[c].value) { + a = fetchValue(vars, d, vars[c].value); + if (typeof a !== "number") a = a ? 1 : 0; + } + return a; + + }); + + } + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Aggregate all values detected in the data. + //-------------------------------------------------------------------------- + for (var key in vars.data.keys) { + + if (key in returnObj.d3plus.data) { + returnObj[key] = returnObj.d3plus[key]; + } + else { + + var agg = vars.aggs && vars.aggs.value[key] ? vars.aggs.value[key] : "sum", + aggType = typeof agg, + keyType = vars.data.keys[key], + idKey = vars.id.nesting.indexOf(key) >= 0, + timeKey = "time" in vars && key === vars.time.value; + + if (key in returnObj.d3plus.data) { + returnObj[key] = returnObj.d3plus[key]; + } + else if (aggType === "function") { + returnObj[key] = vars.aggs.value[key](leaves); + } + else if (timeKey) { + returnObj[key] = parseDates(uniqueValues(leaves, key)); + } + else if (vars.axes && vars.axes.discrete && vars[vars.axes.discrete].value === key) { + returnObj[key] = uniqueValues(leaves, key); + } + else if (keyType === "number" && aggType === "string" && !idKey) { + var vals = leaves.map(function(d){ return d[key]; }); + vals = vals.filter(function(d){ return typeof d === keyType; }); + if (vals.length) returnObj[key] = d3[agg](vals); + } + else { + + var testVals = checkVal(leaves, key); + var keyValues = testVals.length === 1 ? testVals[0][key] + : uniqueValues(testVals, key); + + if (testVals.length === 1) { + returnObj[key] = keyValues; + } + else if (keyValues && keyValues.length) { + + if (!(keyValues instanceof Array)) { + keyValues = [keyValues]; + } + + if (idKey && vars.id.nesting.indexOf(key) > i) { + // if (idKey && vars.id.nesting.indexOf(key) > i && keyValues.length > 1) { + // if (nestingLevels.length == 1 && testVals.length > leaves.length) { + // var newNesting = nestingLevels.concat(key); + // testVals = dataNest(vars,testVals,newNesting); + // } + returnObj[key] = testVals; + } + else { + + returnObj[key] = keyValues; + + } + + } + else if (idKey) { + var endPoint = vars.id.nesting.indexOf(key) - 1; + if (endPoint >= i && (!("endPoint" in returnObj.d3plus) || returnObj.d3plus.endPoint > i)) { + returnObj.d3plus.endPoint = i; + } + } + + } + + } + + if (key in returnObj && returnObj[key] instanceof Array && returnObj[key].length === 1) { + returnObj[key] = returnObj[key][0]; + } + + } + + for (var lll = 0; lll < nestingLevels.length; lll++) { + var level = nestingLevels[lll]; + if (!(level in returnObj)) { + returnObj[level] = fetchValue(vars, leaves[0], level); + } + } + + groupedData.push(returnObj); + + return returnObj; + + }); + + var find_keys = function(obj,depth,keys) { + if (obj.children) { + if (vars.data.keys[nestingLevels[depth]] == "number") { + obj.key = parseFloat(obj.key); + } + keys[nestingLevels[depth]] = obj.key; + delete obj.key; + for ( var k in keys ) { + obj[k] = keys[k]; + } + depth++; + obj.children.forEach(function(c){ + find_keys(c,depth,keys); + }); + } + }; + + nestedData = nestedData + .entries(flatData) + .map(rename_key_value) + .map(function(obj){ + find_keys(obj,0,{}); + return obj; + }); + + return groupedData; + +}; + +var checkVal = function(leaves, key) { + + var returnVals = []; + + function run(obj) { + if (obj instanceof Array) { + obj.forEach(run); + } + else if (validObject(obj) && key in obj) { + if (obj[key] instanceof Array) { + obj[key].forEach(run); + } + else { + returnVals.push(obj); + } + } + } + + run(leaves); + + return returnVals; + +}; + +var parseDates = function(dateArray) { + + var dates = []; + + function checkDate(arr) { + + for (var i = 0; i < arr.length; i++) { + var d = arr[i]; + if (d) { + if (d.constructor === Array) { + checkDate(d); + } + else { + dates.push(d); + } + // if (d.constructor === Date) dates.push(d); + // else if (d.constructor === Array) { + // checkDate(d); + // } + // else { + // d = new Date(d.toString()); + // if (d !== "Invalid Date") { + // d.setTime( d.getTime() + d.getTimezoneOffset() * 60 * 1000 ); + // dates.push(d); + // } + // } + } + } + + } + + checkDate(dateArray); + + return uniqueValues(dates); + +}; + +var rename_key_value = function(obj) { + if (obj.values && obj.values.length) { + obj.children = obj.values.map(function(obj) { + return rename_key_value(obj); + }); + delete obj.values; + return obj; + } + else if(obj.values) { + return obj.values; + } + else { + return obj; + } +}; + +module.exports = dataNest; + +},{"../../object/validate.coffee":175,"../../util/uniques.coffee":213,"../fetch/value.coffee":69}],63:[function(require,module,exports){ +var arraySort = require("../../array/sort.coffee"), + dataNest = require("./nest.js"), + fetchValue = require("../fetch/value.coffee"), + fetchColor = require("../fetch/color.coffee"), + fetchText = require("../fetch/text.js"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Merges data underneath the size threshold +//------------------------------------------------------------------- +module.exports = function( vars , rawData , split ) { + + var threshold; + if ( vars.size.threshold.value === false ) { + threshold = 0; + } + else if (typeof vars.size.threshold.value === "number") { + threshold = vars.size.threshold.value; + } + else if (typeof vars.size.threshold.value === "function") { + threshold = vars.size.threshold.value(vars); + } + else if (typeof vars.types[vars.type.value].threshold === "number") { + threshold = vars.types[vars.type.value].threshold; + } + else if (typeof vars.types[vars.type.value].threshold === "function") { + threshold = vars.types[vars.type.value].threshold(vars); + } + else { + threshold = 0.02; + } + + if (typeof threshold == "number" && threshold > 0) { + + var largeEnough = [], + cutoff = vars.depth.value === 0 ? 0 : {}, + removed = [], + parents = [], + labelException = [], + largest = {}; + + var nest = d3.nest(); + + if (split) { + nest + .key(function(d){ + return fetchValue(vars, d, split); + }); + } + + nest + .rollup(function(leaves){ + var total = leaves.length; + if (vars.aggs.value[vars.size.value]) { + if (typeof vars.aggs.value[vars.size.value] == "function") { + total = vars.aggs.value[vars.size.value](leaves); + } + else if (typeof vars.aggs.value[vars.size.value] == "string") { + total = d3[vars.aggs.value[vars.size.value]](leaves,function(l){ + return fetchValue(vars,l,vars.size.value); + }); + } + } + else { + total = d3.sum(leaves,function(l){ + return fetchValue(vars,l,vars.size.value); + }); + } + var x = split ? fetchValue(vars,leaves[0],split) : "all"; + largest[x] = total; + return total; + }) + .entries(rawData); + + rawData.forEach(function(d){ + var id = fetchValue(vars, d, vars.id.value), + val = fetchValue(vars, d, vars.size.value), + x = split ? fetchValue(vars, d, split) : "all", + allowed = val/largest[x] >= threshold; + + if (allowed && largeEnough.indexOf(id) < 0) { + largeEnough.push(id); + if (vars.depth.value) { + var p = fetchValue(vars, d, vars.id.nesting[vars.depth.value-1]); + if (parents.indexOf(p) < 0) { + parents.push(p); + } + } + } + + }); + + var filteredData = rawData.filter(function(d){ + + var id = fetchValue(vars, d, vars.id.value), + allowed = largeEnough.indexOf(id) >= 0; + + var p = vars.depth.value ? + fetchValue(vars, d, vars.id.nesting[vars.depth.value-1]) : + null; + + if (p !== null && parents.indexOf(p) < 0 && labelException.indexOf(p) < 0) { + labelException.push(p); + } + + if (!allowed) { + var val = fetchValue(vars, d, vars.size.value); + if (val > 0) { + if (vars.depth.value === 0) { + if (val > cutoff) cutoff = val; + } + else { + if (!(p in cutoff)) cutoff[p] = 0; + if (val > cutoff[p]) cutoff[p] = val; + } + removed.push(d); + } + } + return allowed; + + }); + + if ( removed.length > 1 ) { + + removed = arraySort( removed , vars.size.value , "desc" , [] , vars ); + + var levels = vars.id.nesting.slice(0,vars.depth.value); + if (vars.types[vars.type.value].requirements.indexOf(vars.axes.discrete) >= 0) { + levels.push(vars[vars.axes.discrete].value); + } + var merged = dataNest(vars, removed, levels); + + merged.forEach(function(m){ + + var parent = vars.id.nesting[vars.depth.value-1]; + var p_id = fetchValue(vars, m, parent); + children = parent ? removed.filter(function(r){ + return fetchValue(vars, r, parent) === p_id; + }) : removed; + + if (children.length > 1) { + + vars.id.nesting.forEach(function(d,i){ + + if (vars.depth.value == i) { + var prev = m[d]; + if ( typeof prev === "string" ) { + m[d] = "d3plus_other_"+prev; + } + else { + m[d] = "d3plus_other"; + } + } + else if (i > vars.depth.value) { + delete m[d]; + } + }); + + if (vars.color.value && vars.color.type === "string") { + if (vars.depth.value === 0) { + m[vars.color.value] = vars.color.missing; + } + else { + m[vars.color.value] = fetchValue(vars,p_id,vars.color.value,parent); + } + } + + if (vars.icon.value) { + m[vars.icon.value] = fetchValue(vars,p_id,vars.icon.value,parent); + } + + if (p_id) { + m.d3plus.depth = vars.depth.value; + } + + var textLabel; + if (vars.depth.value === 0) { + textLabel = vars.format.value(vars.format.locale.value.ui.values, {"key": "threshold", "vars": vars}); + textLabel += " < "+vars.format.value(cutoff, {"key": vars.size.value, "vars": vars}); + } + else { + textLabel = fetchText(vars,m,vars.depth.value-1); + textLabel = textLabel.length ? textLabel[0].split(" < ")[0] : vars.format.value(vars.format.locale.value.ui.values, {"key": "threshold", "vars": vars}); + if (p_id, labelException.indexOf(p_id) < 0) { + textLabel += " < "+vars.format.value(cutoff[p_id], {"key": vars.size.value, "vars": vars}); + } + } + if (p_id, labelException.indexOf(p_id) < 0) { + textLabel += " ("+vars.format.value(threshold*100, {"key": "share", "vars": vars})+")"; + } + + m.d3plus.threshold = cutoff; + m.d3plus.merged = children; + + if (vars.text.value) { + m[vars.text.value] = textLabel; + } + m.d3plus.text = textLabel; + + } + + }); + + } + else { + merged = removed; + } + + return filteredData.concat(merged); + + } + + return rawData; + +}; + +},{"../../array/sort.coffee":36,"../fetch/color.coffee":65,"../fetch/text.js":68,"../fetch/value.coffee":69,"./nest.js":62}],64:[function(require,module,exports){ +var sizes; + +sizes = require("../../font/sizes.coffee"); + +module.exports = function(vars, opts) { + var f, format, func, getFormat, limit, locale, p, periods, pp, prev, render, small, step, style, time, total, vals, values; + values = opts.values || vars.data.time.ticks; + style = opts.style || {}; + limit = opts.limit || vars.width.value; + time = {}; + periods = vars.data.time.periods; + step = vars.data.time.stepType; + total = vars.data.time.totalType; + func = vars.data.time.functions; + getFormat = vars.data.time.getFormat; + locale = vars.format.locale.value.format; + if (vars.time.format.value) { + time.format = vars.data.time.format; + time.values = values; + time.sizes = sizes(values.map(function(v) { + return time.format(v); + }), style); + } else { + p = periods.indexOf(step); + while (p <= periods.indexOf(total)) { + vals = values.filter(function(t) { + var match, pp; + if (p === periods.indexOf(step)) { + return true; + } + match = true; + pp = p - 1; + if (p < 0) { + return true; + } + while (pp >= periods.indexOf(step)) { + if (!match) { + break; + } + match = !func[pp](t); + pp--; + } + return match; + }); + if (periods[p] === total) { + format = d3.locale(locale).timeFormat(getFormat(periods[p], total)); + } else { + pp = p; + format = []; + while (pp <= periods.indexOf(total)) { + prev = pp - 1 < periods.indexOf(step) ? pp : pp - 1; + prev = periods[prev]; + small = periods[pp] === prev && step !== total; + f = getFormat(prev, periods[pp], small); + format.push([f, func[pp]]); + pp++; + } + format[format.length - 1][1] = function() { + return true; + }; + format = d3.locale(locale).timeFormat.multi(format); + } + render = sizes(vals.map(function(v) { + return format(v); + }), style); + if (d3.sum(render, function(r) { + return r.width; + }) < limit || p === periods.indexOf(total)) { + time.format = format; + time.values = vals; + time.sizes = render; + break; + } + p++; + } + } + return time; +}; + + +},{"../../font/sizes.coffee":104}],65:[function(require,module,exports){ +var fetchValue, getColor, getRandom, randomColor, uniques, validColor, validObject; + +fetchValue = require("./value.coffee"); + +randomColor = require("../../color/random.coffee"); + +validColor = require("../../color/validate.coffee"); + +validObject = require("../../object/validate.coffee"); + +uniques = require("../../util/uniques.coffee"); + +module.exports = function(vars, id, level) { + var color, colorLevel, colors, i, obj, value; + obj = validObject(id); + if (obj && "d3plus" in id && "color" in id.d3plus) { + return id.d3plus.color; + } + if (level === void 0) { + level = vars.id.value; + } + if (typeof level === "number") { + level = vars.id.nesting[level]; + } + if (!vars.color.value) { + return getRandom(vars, id, level); + } else { + colors = []; + i = vars.id.nesting.indexOf(level); + while (i >= 0) { + colorLevel = vars.id.nesting[i]; + value = uniques(id, vars.color.value, fetchValue, vars, colorLevel); + if (value.length === 1) { + value = value[0]; + } + if (!(value instanceof Array) && value !== void 0 && value !== null) { + color = getColor(vars, id, value, level); + if (colors.indexOf(color) < 0) { + colors.push(color); + } + break; + } + i--; + } + if (colors.length === 1) { + return colors[0]; + } else { + return vars.color.missing; + } + } +}; + +getColor = function(vars, id, color, level) { + if (!color) { + if (vars.color.value && typeof vars.color.valueScale === "function") { + return vars.color.valueScale(0); + } + return getRandom(vars, id, level); + } else if (!vars.color.valueScale) { + if (validColor(color)) { + return color; + } else { + return getRandom(vars, color, level); + } + } else { + return vars.color.valueScale(color); + } +}; + +getRandom = function(vars, c, level) { + if (validObject(c)) { + c = fetchValue(vars, c, level); + } + if (c instanceof Array) { + c = c[0]; + } + return randomColor(c, vars.color.scale.value); +}; + + +},{"../../color/random.coffee":49,"../../color/validate.coffee":53,"../../object/validate.coffee":175,"../../util/uniques.coffee":213,"./value.coffee":69}],66:[function(require,module,exports){ +var dataFilter = require("../data/filter.js"), + dataNest = require("../data/nest.js"), + print = require("../console/print.coffee"), + stringFormat = require("../../string/format.js"), + stringList = require("../../string/list.coffee"); + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Fetches specific years of data +//------------------------------------------------------------------- +module.exports = function(vars, years, depth) { + + if (!vars.data.value) return []; + + if (depth === undefined) depth = vars.depth.value; + var nestLevel = vars.id.nesting[depth]; + + if (years && !(years instanceof Array)) years = [years]; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If "years" have not been requested, determine the years using .time() + // solo and mute + //---------------------------------------------------------------------------- + if (!years && "time" in vars) { + + years = []; + + var key = vars.time.solo.value.length ? "solo" : "mute", + filterList = vars.time[key].value; + + if (filterList.length) { + + years = []; + for (var yi = 0; yi < filterList.length; yi++) { + var y = filterList[yi]; + + if (typeof y === "function") { + for (var ti = 0; ti < vars.data.time.values.length; ti++) { + var ms = vars.data.time.values[ti].getTime(); + if (y(ms)) years.push(ms); + } + } + else if (y.constructor === Date) { + years.push(new Date(y).getTime()); + } + else { + y += ""; + if (y.length === 4 && parseInt(y)+"" === y) y = y + "/01/01"; + var d = new Date(y); + if (d !== "Invalid Date") { + // d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000); + years.push(d.getTime()); + } + } + + } + + if ( key === "mute" ) { + years = vars.data.time.values.filter(function( t ){ + return years.indexOf(t.getTime()) < 0; + }); + } + + } + else years.push("all"); + + } + else { + years = ["all"]; + } + + if (years.indexOf("all") >= 0 && vars.data.time.values.length) { + years = vars.data.time.values.slice(0); + for (var i = 0; i < years.length; i++) { + years[i] = years[i].getTime(); + } + } + + var cacheID = [ vars.type.value , nestLevel , depth ] + .concat( vars.data.filters ) + .concat( years ), + filter = vars.data.solo.length ? "solo" : "mute", + cacheKeys = d3.keys(vars.data.cache), + vizFilter = vars.types[vars.type.value].filter || undefined; + + if ( vars.data[filter].length ) { + for (var di = 0; di < vars.data[filter].length; di++) { + var f = vars.data[filter][di]; + var vals = vars[f][filter].value.slice(0); + vals.unshift(f); + vals.unshift(filter); + cacheID = cacheID.concat(vals); + } + } + + if (vars.axes && vars.axes.discrete) cacheID.push(vars.axes.discrete); + + cacheID = cacheID.join("_"); + vars.data.cacheID = cacheID; + + var match = false; + + for (var c = 0 ; c < cacheKeys.length ; c++) { + + var matchKey = cacheKeys[c].split("_").slice(1).join("_"); + + if ( matchKey === cacheID ) { + cacheID = new Date().getTime() + "_" + cacheID; + vars.data.cache[cacheID] = vars.data.cache[cacheKeys[c]]; + delete vars.data.cache[cacheKeys[c]]; + break; + } + + } + + var returnData; + + if ( vars.data.cache[cacheID] ) { + + if ( vars.dev.value ) print.comment("data already cached"); + + returnData = vars.data.cache[cacheID].data; + if ("nodes" in vars) { + vars.nodes.restricted = vars.data.cache[cacheID].nodes; + vars.edges.restricted = vars.data.cache[cacheID].edges; + } + + if ( typeof vizFilter === "function" ) { + returnData = vizFilter( vars , returnData ); + } + + return returnData; + + } + else { + + var missing = []; + returnData = []; + + if (vars.data.value && vars.data.value.length) { + + for (var yz = 0; yz < years.length; yz++) { + var year = years[yz]; + if (vars.data.nested[year]) { + returnData = returnData.concat(vars.data.nested[year][nestLevel]); + } + else { + missing.push(year); + } + } + + } + + if (returnData.length === 0 && missing.length && !vars.error.internal) { + + if (missing.length > 1) { + missing = d3.extent(missing); + } + + missing = missing.map(function(m){ + return vars.data.time.format(new Date(m)); + }); + missing = missing.join(" - "); + + var str = vars.format.locale.value.error.dataYear, + and = vars.format.locale.value.ui.and; + missing = stringList(missing,and); + vars.error.internal = stringFormat(str,missing); + vars.time.missing = true; + + } + else { + + if (vars.time) vars.time.missing = false; + + if ( years.length > 1 ) { + + var separated = false; + ["x", "y", "x2", "y2"].forEach(function(a){ + if (vars[a].value === vars.time.value && + vars[a].scale.value === "discrete" ) { + separated = true; + } + }); + + if (!separated) { + var nested = vars.id.nesting.slice(0,depth+1); + returnData = dataNest(vars, returnData, nested); + } + + } + + if (!returnData) { + returnData = []; + } + else { + returnData = dataFilter(vars, returnData); + } + + if ( cacheKeys.length === 20 ) { + cacheKeys.sort(); + delete vars.data.cache[cacheKeys[0]]; + } + + cacheID = new Date().getTime() + "_" + cacheID; + vars.data.cache[cacheID] = {"data": returnData}; + if ("nodes" in vars) { + vars.data.cache[cacheID].nodes = vars.nodes.restricted; + vars.data.cache[cacheID].edges = vars.edges.restricted; + } + + if ( typeof vizFilter === "function" ) { + returnData = vizFilter( vars , returnData ); + } + + if ( vars.dev.value ) print.comment("storing data in cache"); + + } + + return returnData; + + } + +}; + +},{"../../string/format.js":176,"../../string/list.coffee":177,"../console/print.coffee":54,"../data/filter.js":57,"../data/nest.js":62}],67:[function(require,module,exports){ +var fetchColor, fetchText, fetchValue; + +fetchValue = require("./value.coffee"); + +fetchColor = require("./color.coffee"); + +fetchText = require("./text.js"); + +module.exports = function(vars, d, keys, colors, depth) { + var agg, i, key, len, obj, value; + if (!(keys instanceof Array)) { + keys = [keys]; + } + if (!(colors instanceof Array)) { + colors = [colors]; + } + if (vars) { + if (depth === void 0) { + depth = vars.id.value; + } else if (typeof depth !== "number") { + depth = vars.id.nesting.indexOf(depth); + } + } + obj = {}; + for (i = 0, len = keys.length; i < len; i++) { + key = keys[i]; + if (vars) { + if (colors.indexOf(key) >= 0) { + value = fetchColor(vars, d, depth); + } else if (key === vars.text.value) { + value = fetchText(vars, d, depth); + } else if (d3.keys(d).length === 3 && d["d3plus"] && d["key"] && d["values"]) { + value = fetchValue(vars, d.values.map(function(dd) { + return dd.d3plus; + }), key, depth); + } else { + value = fetchValue(vars, d, key, depth); + } + } else { + value = d[key]; + } + if ([vars.data.keys[key], vars.attrs.keys[key]].indexOf("number") >= 0) { + agg = vars.order.agg.value || vars.aggs.value[key] || "sum"; + if (agg.constructor === String) { + agg = d3[agg]; + } + if (!(value instanceof Array)) { + value = [value]; + } + value = agg(value); + } else { + if (value instanceof Array) { + value = value[0]; + } + value = typeof value === "string" ? value.toLowerCase() : value; + } + obj[key] = value; + } + return obj; +}; + + +},{"./color.coffee":65,"./text.js":68,"./value.coffee":69}],68:[function(require,module,exports){ +var fetchValue = require("./value.coffee"), + validObject = require("../../object/validate.coffee"), + uniques = require("../../util/uniques.coffee"); + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Get array of available text values +//------------------------------------------------------------------------------ +module.exports = function(vars, obj, depth) { + + if (typeof depth !== "number") depth = vars.depth.value; + + var key = vars.id.nesting[depth], textKeys; + + if ( vars.text.nesting && validObject(vars.text.nesting) ) { + if ( vars.text.nesting[key] ) { + textKeys = vars.text.nesting[key]; + } + else { + textKeys = vars.text.value; + } + } + else { + textKeys = []; + if (vars.text.value && depth === vars.depth.value) textKeys.push(vars.text.value); + textKeys.push(key); + } + + if ( !(textKeys instanceof Array) ) { + textKeys = [ textKeys ]; + } + + var names = []; + + if (validObject(obj) && "d3plus" in obj && obj.d3plus.text) { + names.push(obj.d3plus.text.toString()); + names.push(vars.format.value(obj.d3plus.text.toString(), {"vars": vars, "data": obj})); + } + else { + + var formatObj = validObject(obj) ? obj : undefined; + + if (formatObj && obj[vars.id.value] instanceof Array) { + obj = obj[vars.id.value]; + } + else if (!(obj instanceof Array)) { + obj = [obj]; + } + + textKeys.forEach(function( t ){ + + var name = uniques(obj, t, fetchValue, vars, key); + + if ( name.length ) { + if (name.length > 1) { + name = name.filter(function(n){ + return (n instanceof Array) || (typeof n === "string" && n.indexOf(" < ") < 0); + }); + } + name = name.map(function(n){ + if (n instanceof Array) { + n = n.filter(function(nn){ return nn; }); + return n.map(function(nn){ + return vars.format.value(nn.toString(), {"vars": vars, "data": formatObj, "key": t}); + }); + } + else if (n) { + return vars.format.value(n.toString(), {"vars": vars, "data": formatObj, "key": t}); + } + }); + if (name.length === 1) name = name[0]; + names.push(name); + } + + }); + + } + + return names; + +}; + +},{"../../object/validate.coffee":175,"../../util/uniques.coffee":213,"./value.coffee":69}],69:[function(require,module,exports){ +var cacheInit, checkAttrs, checkData, fetch, fetchArray, filterArray, find, uniqueValues, validObject, valueParse; + +validObject = require("../../object/validate.coffee"); + +uniqueValues = require("../../util/uniques.coffee"); + +find = function(vars, node, variable, depth) { + var cache, nodeObject, returned, val; + nodeObject = validObject(node); + if (typeof variable === "function" && nodeObject) { + return variable(node, vars); + } + if (nodeObject) { + if (variable in node) { + return node[variable]; + } + cache = vars.data.cacheID + "_" + depth; + cacheInit(node, cache, vars); + if (variable in node.d3plus.data[cache]) { + return node.d3plus.data[cache][variable]; + } + if (depth in node) { + node = node[depth]; + } else if (vars.id.value in node) { + node = node[vars.id.value]; + if (depth !== variable) { + returned = checkData(vars, node, depth, vars.id.value); + } + if (returned === null || returned === void 0) { + returned = checkAttrs(vars, node, depth, vars.id.value); + } + if (returned === null || returned === void 0) { + return null; + } else if (depth === variable) { + return returned; + } + node = returned; + } else { + return null; + } + } + if (node instanceof Array && !validObject(node[0])) { + node = uniqueValues(node); + } + if (node instanceof Array && validObject(node[0])) { + val = uniqueValues(node, variable); + if (val.length) { + return val; + } + } + val = checkData(vars, node, variable, depth); + if (val) { + return val; + } + val = checkAttrs(vars, node, variable, depth); + return val; +}; + +checkData = function(vars, node, variable, depth) { + var val; + if (vars.data.viz instanceof Array && variable in vars.data.keys) { + val = uniqueValues(filterArray(vars.data.viz, node, depth), variable); + } + if (val && val.length) { + return val; + } else { + return null; + } +}; + +checkAttrs = function(vars, node, variable, depth) { + var attrList, n, val, vals; + if ("attrs" in vars && vars.attrs.value && variable in vars.attrs.keys) { + if (validObject(vars.attrs.value) && depth in vars.attrs.value) { + attrList = vars.attrs.value[depth]; + } else { + attrList = vars.attrs.value; + } + if (attrList instanceof Array) { + val = uniqueValues(filterArray(attrList, node, depth), variable); + if (val.length) { + return val; + } + } else if (node instanceof Array) { + attrList = [ + (function() { + var j, len, results; + if (n in attrList) { + results = []; + for (j = 0, len = node.length; j < len; j++) { + n = node[j]; + results.push(attrList[n]); + } + return results; + } + })() + ]; + if (attrList.length) { + vals = uniqueValues(attrList, variable); + if (vals.length) { + return vals; + } + } + } else if (node in attrList) { + return attrList[node][variable]; + } + } + return null; +}; + +filterArray = function(arr, node, depth) { + if (node instanceof Array) { + return arr.filter(function(d) { + return node.indexOf(d[depth]) >= 0; + }); + } else { + return arr.filter(function(d) { + return d[depth] === node; + }); + } +}; + +cacheInit = function(node, cache, vars) { + if (!("d3plus" in node)) { + node.d3plus = {}; + } + if (!("data" in node.d3plus)) { + node.d3plus.data = {}; + } + if (vars.data.changed || (vars.attrs && vars.attrs.changed) || !(cache in node.d3plus.data)) { + node.d3plus.data[cache] = {}; + } + return node; +}; + +valueParse = function(vars, node, depth, variable, val) { + var cache, d, i, j, len, timeVar, v; + if (val === null) { + return val; + } + timeVar = "time" in vars && vars.time.value === variable; + if (!(val instanceof Array)) { + val = [val]; + } + for (i = j = 0, len = val.length; j < len; i = ++j) { + v = val[i]; + if (timeVar && v !== null && v.constructor !== Date) { + v = v + ""; + if (v.length === 4 && parseInt(v) + "" === v) { + v += "/01/01"; + } + d = new Date(v); + if (d !== "Invalid Date") { + val[i] = d; + } + } + } + if (val.length === 1) { + val = val[0]; + } + if (val !== null && validObject(node) && typeof variable === "string" && !(variable in node)) { + cache = vars.data.cacheID + "_" + depth; + node.d3plus.data[cache][variable] = val; + } + return val; +}; + +fetchArray = function(vars, arr, variable, depth) { + var item, j, len, v, val; + val = []; + for (j = 0, len = arr.length; j < len; j++) { + item = arr[j]; + if (validObject(item)) { + v = find(vars, item, variable, depth); + val.push(valueParse(vars, item, depth, variable, v)); + } else { + val.push(item); + } + } + if (typeof val[0] !== "number") { + val = uniqueValues(val); + } + if (val.length === 1) { + return val[0]; + } else { + return val; + } +}; + +fetch = function(vars, node, variable, depth) { + var nodeObject, val; + if (!variable) { + return null; + } + if (typeof variable === "number") { + return variable; + } + nodeObject = validObject(node); + if (!depth) { + depth = vars.id.value; + } + if (nodeObject && node.values instanceof Array) { + val = fetchArray(vars, node.values, variable, depth); + } else if (nodeObject && node[variable] instanceof Array) { + val = fetchArray(vars, node[variable], variable, depth); + } else if (node instanceof Array) { + val = fetchArray(vars, node, variable, depth); + } else { + val = find(vars, node, variable, depth); + val = valueParse(vars, node, depth, variable, val); + } + return val; +}; + +module.exports = fetch; + + +},{"../../object/validate.coffee":175,"../../util/uniques.coffee":213}],70:[function(require,module,exports){ +module.exports = function(type) { + var attrs, styles, tester; + if (["div", "svg"].indexOf(type) < 0) { + type = "div"; + } + styles = { + position: "absolute", + left: "-9999px", + top: "-9999px", + visibility: "hidden", + display: "block" + }; + attrs = type === "div" ? {} : { + position: "absolute" + }; + tester = d3.select("body").selectAll(type + ".d3plus_tester").data([0]); + tester.enter().append(type).attr("class", "d3plus_tester").style(styles).attr(attrs); + return tester; +}; + + +},{}],71:[function(require,module,exports){ +module.exports = { + "format": { + "decimal": ",", + "thousands": ".", + "grouping": [3], + "currency": ["", " €"], + "dateTime": "%A, der %e. %B %Y, %X", + "date": "%d.%m.%Y", + "time": "%H:%M:%S", + "periods": ["AM", "PM"], // unused + "days": ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"], + "shortDays": ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"], + "months": ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"], + "shortMonths": ["Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"] + }, + "error": { + "accepted": "{0} ist kein gültiger {1} für {2}-Darstellungen. Benutzen Sie bitte: {3}.", + "connections": "Keine Verbindungen verfügbar für {0}.", + "data": "Keine Daten verfügbar", + "dataYear": "Für {0} sind keine Daten verfügbar.", + "lib": "{0}-Darstellungen erfordern das Laden der Bibliothek {1}.", + "libs": "{0}-Darstellungen erfordern das Laden folgender Bibliotheken: {1}.", + "method": "{0}-Darstellungen erfordern die Methode {1}.", + "methods": "Weitere Einstellungen für folgende Methoden {1} sind bei {0}-Darstellungen erforderlich." + }, + "lowercase": [ + "ein", + "ein", + "und", + "wie", + "bei", + "aber", + "durch", + "für", + "von", + "wenn", + "in", + "in", + "in der Nähe", + "noch", + "von", + "auf", + "auf", + "oder", + "pro", + "das", + "die", + "zu", + "mit", + "über", + "gegen", + "gegen." + ], + "method": { + "active": "aktive Segmente", + "color": "Farbe", + "depth": "Tiefe", + "dev": "ausführlich", + "focus": "Fokus", + "icon": "Symbol", + "id": "Kennung", + "height": "Höhe", + "labels": "Beschriftungen", + "legend": "Legende", + "margin": "Rand", + "messages": "Statusmeldungen", + "order": "Reihenfolge", + "search": "Suche", + "shape": "Form", + "size": "Größe", + "style": "Stil", + "temp": "temporäre Segmente", + "text": "Text", + "time": "Zeit", + "timeline": "Zeitleiste", + "total": "Segmente gesamt", + "type": "Typ", + "width": "Breite", + "x": "x-Achse", + "y": "y-Achse", + "zoom": "Zoom", + "mode": "Modus", + "mute": "ausblenden", + "solo": "isolieren" + }, + "time": [ + "Datum", + "Tag", + "Monat", + "Zeit", + "Jahr" + ], + "visualization": { + "bubbles": "Blasen", + "chart": "Diagramm", + "geo_map": "Karte", + "line": "Liniendiagramm", + "network": "Netzwerk", + "rings": "Ringe", + "scatter": "Punktdiagramm", + "stacked": "Gestapelte Fläche", + "tree_map": "Baumdiagramm", + "bar": "Balkendiagramm", + "box": "Boxplot", + "paths": "Pfade", + "pie": "Kreisdiagramm", + "table": "Tabelle" + }, + "ui": { + "and": "und", + "back": "zurück", + "collapse": "Zum Ausblenden klicken", + "error": "Fehler", + "expand": "Zum Einblenden klicken", + "loading": "Lade...", + "more": "{0} weitere", + "moreInfo": "Für zusätzliche Informationen klicken", + "noResults": "Keine Ergebnisse für {0} gefunden.", + "primary": "Primäre Verbindungen", + "share": "teilen", + "total": "gesamt", + "values": "Werte", + "including": "einschließlich", + "or": "oder", + "iqr": "Interquartilsabstände {0}", + "max": "Maximalwert", + "min": "Minimalwert", + "percentile": "Perzentil P{0}", + "tukey_bottom": "Unterer Ausreißer", + "tukey_top": "Oberer Ausreißer", + "quartile_first": "Unteres Quartil Q1", + "quartile_third": "Oberes Quartil Q3", + "median": "Medianwert" + }, + "message": { + "data": "analysiere Daten", + "draw": "Darstellung wird gerendert", + "initializing": "initialisiere {0}", + "loading": "Daten werden geladen", + "tooltipReset": "Tooltips zurücksetzen", + "ui": "aktualisiere Oberfläche" + }, + "uppercase": [ + "CEO", + "CEOs", + "CFO", + "CFOs", + "CNC", + "COO", + "COOs", + "CPU", + "CPUs", + "BIP", + "HVAC", + "ID", + "IT", + "FuE", + "TV", + "UI" + ] +} + +},{}],72:[function(require,module,exports){ +module.exports = { + dev: { + accepted: "{0} is not an accepted value for {1}, please use one of the following: {2}.", + deprecated: "the {0} method has been removed, please update your code to use {1}.", + noChange: "{0} was not updated because it did not change.", + noContainer: "cannot find a container on the page matching {0}.", + of: "of", + oldStyle: "style properties for {0} have now been embedded directly into .{1}().", + sameEdge: "edges cannot link to themselves. automatically removing self-referencing edge {0}.", + set: "{0} has been set.", + setLong: "{0} has been set to {1}.", + setContainer: "please define a container div using .container()" + }, + error: { + accepted: "{0} is not an accepted {1} for {2} visualizations, please use one of the following: {3}.", + connections: "no connections available for {0}.", + data: "no data available", + dataYear: "no data available for {0}.", + lib: "{0} visualizations require loading the {1} library.", + libs: "{0} visualizations require loading the following libraries: {1}.", + method: "{0} visualizations require setting the {1} method.", + methods: "{0} visualizations require setting the following methods: {1}." + }, + format: { + decimal: ".", + thousands: ",", + grouping: [3], + currency: ["$", ""], + dateTime: "%A, %B %-d, %Y %X", + date: "%-m/%-d/%Y", + time: "%I:%M:%S %p", + 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"] + }, + lowercase: ["a", "an", "and", "as", "at", "but", "by", "for", "from", "if", "in", "into", "near", "nor", "of", "on", "onto", "or", "per", "that", "the", "to", "with", "via", "vs", "vs."], + message: { + data: "analyzing data", + draw: "drawing visualization", + initializing: "initializing {0}", + loading: "loading data", + tooltipReset: "resetting tooltips", + ui: "updating ui" + }, + method: { + active: "active segments", + color: "color", + depth: "depth", + dev: "verbose", + focus: "focus", + icon: "icon", + id: "id", + height: "height", + labels: "labels", + legend: "legend", + margin: "margin", + messages: "status messages", + mode: "mode", + mute: "hide", + order: "order", + search: "search", + shape: "shape", + size: "size", + solo: "isolate", + style: "style", + temp: "temporary segments", + text: "text", + time: "time", + timeline: "timeline", + total: "total segments", + type: "type", + width: "width", + x: "x axis", + y: "y axis", + zoom: "zoom" + }, + time: ["date", "day", "month", "time", "year"], + timeFormat: { + FullYear: "%Y", + Month: "%B", + MonthSmall: "%b", + Date: "%A %-d", + DateSmall: "%-d", + Hours: "%I %p", + Minutes: "%I:%M", + Seconds: "%Ss", + Milliseconds: "%Lms", + "FullYear-Month": "%b %Y", + "FullYear-Date": "%-m/%-d/%Y", + "Month-Date": "%b %-d", + "Hours-Minutes": "%I:%M %p", + "Hours-Seconds": "%I:%M:%S %p", + "Hours-Milliseconds": "%H:%M:%S.%L", + "Minutes-Seconds": "%I:%M:%S %p", + "Minutes-Milliseconds": "%H:%M:%S.%L", + "Seconds-Milliseconds": "%H:%M:%S.%L" + }, + ui: { + and: "and", + back: "back", + collapse: "click to collapse", + error: "error", + expand: "click to expand", + including: "including", + iqr: "interquartile range for {0}", + loading: "loading...", + max: "maximum", + median: "median", + min: "minimum", + more: "{0} more", + moreInfo: "click for more info", + or: "or", + noResults: "no results matching {0}.", + percentile: "{0} percentile", + primary: "primary connections", + quartile_first: "first quartile", + quartile_third: "third quartile", + share: "share", + total: "total", + tukey_bottom: "bottom tukey", + tukey_top: "top tukey", + values: "values" + }, + uppercase: ["CEO", "CEOs", "CFO", "CFOs", "CNC", "COO", "COOs", "CPU", "CPUs", "GDP", "HVAC", "ID", "IT", "R&D", "TV", "UI"], + visualization: { + bar: "Bar Chart", + box: "Box Plot", + bubbles: "Bubbles", + chart: "Chart", + geo_map: "Geo Map", + line: "Line Plot", + network: "Network", + paths: "Paths", + pie: "Pie Chart", + rings: "Rings", + scatter: "Scatter Plot", + stacked: "Stacked Area", + table: "Table", + tree_map: "Tree Map" + } +}; + + +},{}],73:[function(require,module,exports){ +module.exports = { + "format": { + "decimal": ",", + "thousands": ".", + "grouping": [3], + "currency": ["", " €"], + "dateTime": "%A, %e de %B de %Y, %X", + "date": "%d/%m/%Y", + "time": "%H:%M:%S", + "periods": ["AM", "PM"], + "days": ["domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"], + "shortDays": ["dom", "lun", "mar", "mié", "jue", "vie", "sáb"], + "months": ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"], + "shortMonths": ["ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"] + }, + "dev": { + "accepted": "{0} no es un valor aceptado para {1}, por favor utilice uno de los siguientes: {2}.", + "deprecated": "el método {0} ha sido eliminado, por favor, actualiza tu código para utilizar {1}.", + "noChange": "{0} no se actualiza porque no cambió.", + "noContainer": "no se puede encontrar un contenedor en la página correspondiente a {0}.", + "of": "de", + "oldStyle": "propiedades de estilo para {0} ahora se han incorporado directamente en. {1} ().", + "sameEdge": "los vínculos no se pueden enlazar con si mismos. eliminando automáticamente el vínculo {0} que se autorreferencia.", + "set": "{0} se ha establecido.", + "setLong": "{0} ha sido establecido a {1}.", + "setContainer": "defina un div contenedor utilizando .container ()" + }, + "error": { + "accepted": "{0} no es un {1} aceptado para visualizaciones de {2}, por favor utilice uno de los siguientes: {3}.", + "connections": "no hay conexiones disponibles para {0}.", + "data": "No hay datos disponibles", + "dataYear": "no hay datos disponibles para {0}.", + "lib": "{0} visualizaciones requieren cargar las siguientes librerías: {1}.", + "libs": "{0} visualizaciones requieren cargar las siguientes librerías: {1}.", + "method": "{0} visualizaciones requieren establecer el ​​método {1}.", + "methods": "{0} visualizaciones requieren establecer los siguientes métodos: {1}." + }, + "lowercase": [ + "una", + "y", + "en", + "pero", + "en", + "de", + "o", + "el", + "la", + "los", + "las", + "para", + "a", + "con" + ], + "method": { + "active": "segmentos activos", + "color": "color", + "depth": "profundidad", + "dev": "detallado", + "focus": "foco", + "icon": "ícono", + "id": "id", + "height": "alto", + "labels": "rótulo", + "legend": "leyenda", + "margin": "margen", + "messages": "mensajes de estado", + "order": "orden", + "search": "búsqueda", + "shape": "forma", + "size": "tamaño", + "style": "estilo", + "temp": "segmentos temporales", + "text": "texto", + "time": "tiempo", + "timeline": "línea de tiempo", + "total": "segmentos totales", + "type": "tipo", + "width": "anchura", + "x": "eje x", + "y": "eje Y", + "zoom": "zoom", + "mode": "modo", + "mute": "ocultar", + "solo": "aislar" + }, + "time": [ + "fecha", + "día", + "mes", + "hora", + "año" + ], + "visualization": { + "bubbles": "Burbujas", + "chart": "Gráfico", + "geo_map": "Mapa", + "line": "Gráfico de linea", + "network": "Red", + "rings": "Anillos", + "scatter": "Gráfico De Dispersión", + "stacked": "Área Apilada", + "tree_map": "Tree Map", + "bar": "Gráfico De Barras", + "box": "Diagrama de Cajas", + "paths": "Caminos", + "pie": "Gráfico de Pastel", + "table": "Tabla" + }, + "ui": { + "and": "y", + "back": "atrás", + "collapse": "click para cerrar", + "error": "error", + "expand": "haga clic para ampliar", + "loading": "Cargando ...", + "more": "{0} más", + "moreInfo": "clic para más información", + "noResults": "no se encontraron resultados para {0}.", + "primary": "relaciones principales", + "share": "porcentaje", + "total": "total", + "values": "valores", + "including": "Incluyendo", + "or": "o", + "iqr": "rango intercuartil para {0}", + "max": "máximo", + "min": "mínimo", + "percentile": "{0} percentil", + "tukey_bottom": "Tukey inferior", + "tukey_top": "la parte superior de Tukey", + "quartile_first": "primer cuartil", + "quartile_third": "tercer cuartil", + "median": "mediana" + }, + "message": { + "data": "analizando los datos", + "draw": "visualizando", + "initializing": "inicializando {0}", + "loading": "cargando datos", + "tooltipReset": "restableciendo las descripciones emergentes", + "ui": "actualizando la interfaz de usuario" + }, + "uppercase": [ + "CEO", + "CEOs", + "CFO", + "CFOs", + "CNC", + "COO", + "COOs", + "CPU", + "CPUs", + "PIB", + "HVAC", + "ID", + "TI", + "I&D", + "TV", + "UI" + ] +} + +},{}],74:[function(require,module,exports){ +module.exports = { + "format": { + "decimal": ",", + "thousands": ".", + "grouping": [3], + "currency": ["", " €"], + "dateTime": "%A, le %e %B %Y, %X", + "date": "%d/%m/%Y", + "time": "%H:%M:%S", + "periods": ["AM", "PM"], // unused + "days": ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"], + "shortDays": ["dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam."], + "months": ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"], + "shortMonths": ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."] + }, + "dev": { + "accepted": "{0} n'est pas une option valide pour {1}, les valeurs possibles sont: {2}.", + "deprecated": "{0} a été éliminé de la version courante, mettez à jour votre code source avec {1}.", + "noChange": "{0} n'a pas été mis à jour car inchangé.", + "noContainer": "impossible de trouver un contenant correspondant à {0}.", + "of": "de", + "oldStyle": "les propriétés de {0} ont été imbriquées dans .{1}().", + "sameEdge": "un arc ne peut pas boucler sur lui même. L'auto-référence est automatiquement éliminée {0}.", + "set": "{0} a été mis à jour.", + "setLong": "{0} a été mis à jour à {1}.", + "setContainer": "merci de choisir un div qui utilise .container()" + }, + "error": { + "accepted": "{0} n'est pas correct {1} pour {2} visualisations, merci d'utilisez une des options suivantes: {3}.", + "connections": "Pas de connections disponibles pour {0}.", + "data": "Pas de données disponibles", + "dataYear": "Pas de données disponibles pour {0}.", + "lib": "La visualisation de {0} nécessite le chargement de la librairie {1}.", + "libs": "La visualisation de {0} nécessite le chargement des librairies {1}.", + "method": "La visualisation du {0} exige la définition de {1}.", + "methods": "La visualisation du {0} exige les définitions de {1}." + }, + "lowercase": [ + "un", + "une", + "de", + "des", + "et", + "mais", + "les", + "ou", + "pour", + "avec", + "comme", + "par", + "vers", + "si", + "dans", + "près", + "ni", + "dessus", + "que", + "le", + "la", + "via", + "sinon", + "alors" + ], + "method": { + "active": "segments actifs", + "color": "couleur", + "depth": "profondeur", + "dev": "verbeux", + "focus": "focus", + "icon": "ícone", + "id": "id", + "height": "hauteur", + "labels": "labels", + "legend": "légende", + "margin": "marge", + "messages": "messages", + "order": "ordre", + "search": "recherche", + "shape": "format", + "size": "taille", + "style": "style", + "temp": "segments temporaires", + "text": "texte", + "time": "temps", + "timeline": "ligne temporelle", + "total": "segments totaux", + "type": "type", + "width": "largeur", + "x": "axe x", + "y": "axe y", + "zoom": "zoom", + "mode": "mode", + "mute": "cacher", + "solo": "isoler" + }, + "time": [ + "année", + "date", + "jour", + "heure", + "mois" + ], + "visualization": { + "bubbles": "Bulles", + "chart": "Graphique", + "geo_map": "Carte", + "line": "Courbes", + "network": "Réseau", + "rings": "Anneaux", + "scatter": "Nuage de points", + "stacked": "Aires empilées", + "tree_map": "Arbre", + "bar": "Diagramme en barres", + "box": "Boîtes à Moustaches", + "paths": "Chemins", + "pie": "Camembert", + "table": "Table" + }, + "ui": { + "and": "et", + "back": "retour", + "collapse": "clic pour réduire", + "error": "erreur", + "expand": "clic pour agrandir", + "loading": "chargement ...", + "more": "plus {0}", + "moreInfo": "clic pour plus d'information", + "noResults": "pas de résultat correspondant à {0}.", + "primary": "connections primaires", + "share": "part", + "total": "total", + "values": "valeurs", + "including": "incluant", + "or": "ou", + "iqr": "gamme interquartile pour {0}", + "max": "maximum", + "min": "le minimum", + "percentile": "{0} percentile", + "tukey_bottom": "tukey bas", + "tukey_top": "top tukey", + "quartile_first": "premier quartile", + "quartile_third": "le troisième quartile", + "median": "médian" + }, + "message": { + "data": "analyse des données", + "draw": "tracé en cours", + "initializing": "Initialisation {0}", + "loading": "chargement", + "tooltipReset": "réinitialisation des bulles", + "ui": "rafraichissement de l'interface" + }, + "uppercase": [ + "CEO", + "CEOs", + "CFO", + "CFOs", + "CNC", + "COO", + "COOs", + "CPU", + "CPUs", + "PIB", + "HVAC", + "ID", + "IT", + "TV", + "UI" + ] +} + +},{}],75:[function(require,module,exports){ +module.exports = { + "format": { + "decimal": ".", + "thousands": ",", + "grouping": [3], + "currency": ["₩", ""], + "dateTime": "%Y/%m/%d %a %X", + "date": "%Y/%m/%d", + "time": "%H:%M:%S", + "periods": ["오전", "오후"], + "days": ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"], + "shortDays": ["일", "월", "화", "수", "목", "금", "토"], + "months": ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"], + "shortMonths": ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"] + }, + "error": { + "accepted": "{0}하지 허용 {1} {2} 시각화는 다음 중 하나를 사용하십시오에 대해 : {3}.", + "connections": "{0}에 대한 연결이 없음.", + "data": "자료 없음", + "dataYear": "{0}에 대한 자료가 없음.", + "lib": "{0} 시각화는 {1} 라이브러리를로드 할 필요합니다.", + "libs": "{0} 시각화는 다음과 같은 라이브러리를로드 할 필요 : {1}.", + "method": "{0} 시각화를 위해 {1} 메서드를 설정해야 한다.", + "methods": "{0} 시각화를 위해 다음과 같은 메서드를 설정해야한다: {1}." + }, + "lowercase": [ + "" + ], + "method": { + "active": "활성 세그먼트", + "color": "색", + "depth": "깊이", + "dev": "풀어서", + "focus": "집중하다", + "icon": "상", + "id": "신분증", + "height": "높이", + "labels": "라벨", + "legend": "범례", + "margin": "여유", + "messages": "상태 메시지", + "order": "주문", + "search": "수색", + "shape": "모양", + "size": "크기", + "style": "스타일", + "temp": "임시 세그먼트", + "text": "본문", + "time": "시각", + "timeline": "타임 라인", + "total": "총 세그먼트", + "type": "유형", + "width": "폭", + "x": "X 축", + "y": "Y 축", + "zoom": "줌", + "mode": "모드", + "mute": "숨김", + "solo": "독주" + }, + "time": [ + "날짜", + "요일", + "월", + "시간", + "년" + ], + "visualization": { + "bubbles": "버블 차트", + "chart": "차트", + "geo_map": "지도형", + "line": "선형 그래프", + "network": "네트워크 그래프", + "rings": "반지", + "scatter": "산포도", + "stacked": "누적 된 지역", + "tree_map": "트리 맵", + "bar": "막대 차트", + "box": "박스 플롯", + "paths": "경로", + "pie": "파이 차트", + "table": "탁자" + }, + "ui": { + "and": "과", + "back": "뒤로", + "collapse": "축소하려면 클릭", + "error": "오류", + "expand": "확장하려면 클릭", + "loading": "로드 중 ...", + "more": "{0} 이상", + "moreInfo": "추가 정보를 위해 클릭하십시오", + "noResults": "일치하는 결과값이 없음 {0}.", + "primary": "기본 연결", + "share": "비중", + "total": "합계", + "values": "값", + "including": "...을 포함하여", + "or": "또는", + "iqr": "대한 사 분위 범위 {0}", + "max": "최고", + "min": "최저한의", + "percentile": "{0} 백분위 수", + "tukey_bottom": "바닥 Tukey에", + "tukey_top": "상단 Tukey에", + "quartile_first": "1 분위", + "quartile_third": "3 분위", + "median": "중앙값" + }, + "message": { + "data": "데이터 분석 중", + "draw": "데이터 시각화 중", + "initializing": "초기화 {0}", + "loading": "데이터 로딩 중", + "tooltipReset": "툴팁을 재설정", + "ui": "UI 업데이트 중" + }, + "uppercase": [ + "CEO", + "최고 경영자", + "최고 재무 책임자 (CFO)", + "CFO는", + "CNC", + "COO", + "구구", + "CPU", + "CPU에", + "GDP", + "HVAC", + "ID", + "IT", + "R & D", + "TV", + "UI" + ] +} + +},{}],76:[function(require,module,exports){ +module.exports = { + "format": { + "decimal": ",", + "thousands": ".", + "grouping": [3], + "currency": ["", " ден."], + "dateTime": "%A, %e %B %Y г. %X", + "date": "%d.%m.%Y", + "time": "%H:%M:%S", + "periods": ["AM", "PM"], + "days": ["недела", "понеделник", "вторник", "среда", "четврток", "петок", "сабота"], + "shortDays": ["нед", "пон", "вто", "сре", "чет", "пет", "саб"], + "months": ["јануари", "февруари", "март", "април", "мај", "јуни", "јули", "август", "септември", "октомври", "ноември", "декември"], + "shortMonths": ["јан", "фев", "мар", "апр", "мај", "јун", "јул", "авг", "сеп", "окт", "ное", "дек"] + }, + "error": { + "accepted": "{0} не е прифатлива за {1} {2} визуелизација, ве молиме користете една од следниве: {3}.", + "connections": "не е достапна за врски {0}.", + "data": "нема податоци", + "dataYear": "Не е достапен за податоци {0}.", + "lib": "{0} визуализации бараат вчитување на библиотеката {1} .", + "libs": "{0} визуализации бараат вчитување на следниве библиотеки: {1}.", + "method": "{0} визуализации бара поставување на {1} методот.", + "methods": "{0} визуализации бараат поставување на следниве методи: {1}." + }, + "lowercase": [ + "a", + "и", + "во", + "но", + "на", + "или", + "да", + "се", + "со" + ], + "method": { + "active": "активни сегменти", + "color": "боја", + "depth": "длабочина", + "dev": "опширно", + "focus": "фокус", + "icon": "икона", + "id": "проект", + "height": "височина", + "labels": "етикети", + "legend": "легенда", + "margin": "маргина", + "messages": "пораки за статусот", + "order": "со цел", + "search": "барај", + "shape": "форма", + "size": "големина", + "style": "стил", + "temp": "привремени сегменти", + "text": "текст", + "time": "време", + "timeline": "времеплов", + "total": "Вкупно сегменти", + "type": "тип", + "width": "ширина", + "x": "x оската", + "y": "Y оската", + "zoom": "зум", + "mode": "режим", + "mute": "се скрие", + "solo": "изолирање" + }, + "time": [ + "датум", + "ден", + "месец", + "време", + "година" + ], + "visualization": { + "bubbles": "меурчиња", + "chart": "Графикон", + "geo_map": "Гео мапа", + "line": "Линиски график", + "network": "мрежа", + "rings": "прстени", + "scatter": "Распрскан график", + "stacked": "Наредена површина", + "tree_map": "Мапа во вид на дрво", + "bar": "бар шема", + "box": "правоаголен дијаграм", + "paths": "патеки", + "pie": "пита графикон", + "table": "Табела" + }, + "ui": { + "and": "и", + "back": "назад", + "collapse": "кликни за да се собере", + "error": "грешка", + "expand": "Кликни за проширување", + "loading": "Се вчитува ...", + "more": "{0} повеќе", + "moreInfo": "кликнете за повеќе информации", + "noResults": "Не се пронајдени резултати за појавување на {0}.", + "primary": "основните врски", + "share": "удел", + "total": "Вкупниот", + "values": "вредности", + "including": "Вклучувајќи", + "or": "или", + "iqr": "interquartile опсег за {0}", + "max": "максималната", + "min": "минимум", + "percentile": "{0} перцентил", + "tukey_bottom": "дното Tukey", + "tukey_top": "Топ Tukey", + "quartile_first": "првиот квартал", + "quartile_third": "третиот квартал", + "median": "средната" + }, + "message": { + "data": "анализа на податоци", + "draw": "цртање на визуелизација", + "initializing": "иницијализација {0}", + "loading": "податоци за товарење", + "tooltipReset": "ресетирање на објаснувањата", + "ui": "ажурирање на кориничкиот интерфејс" + }, + "uppercase": [ + "CEO", + "CEOs", + "CFO", + "CFOs", + "CNC", + "COO", + "COOs", + "CPU", + "CPUs", + "GDP", + "HVAC", + "ID", + "IT", + "R&D", + "TV", + "UI" + ] +} + +},{}],77:[function(require,module,exports){ +module.exports = { + "format": { + "decimal": ",", + "thousands": ".", + "grouping": [3], + "currency": ["R$", ""], + "dateTime": "%A, %e de %B de %Y. %X", + "date": "%d/%m/%Y", + "time": "%H:%M:%S", + "periods": ["AM", "PM"], + "days": ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"], + "shortDays": ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"], + "months": ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"], + "shortMonths": ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"] + }, + "dev": { + "accepted": "{0} não é um valor válido para {1}, por favor use um dos seguintes procedimentos: {2}.", + "deprecated": "{0} método foi removido, por favor atualize seu código para utilizar {1}.", + "noChange": "{0} não foi atualizado porque ele não mudou.", + "noContainer": "Não foi possível encontrar um local na página correspondente a {0}.", + "of": "do", + "oldStyle": "propriedades de estilo para {0} já foram incorporados diretamente no. {1} ().", + "sameEdge": "bordas não podem vincular a si mesmos. removendo automaticamente borda de auto-referência {0}.", + "set": "{0} foi definido.", + "setLong": "{0} foi definido para {1}.", + "setContainer": "por favor, defina um div utilizando .container()" + }, + "error": { + "accepted": "{0} não é um {1} reconhecido para visualizações {2}, favor usar um dos seguintes procedimentos: {3}.", + "connections": "Não há conexões disponíveis para {0}.", + "data": "Não há dados disponíveis", + "dataYear": "Não há dados disponíveis para {0}.", + "lib": "A visualização {0} necessita que seja carregado a biblioteca {1}.", + "libs": "A visualização {0} necessita que seja carregado as bibliotecas {1}.", + "method": "A visualização {0} exige a definição do método {1}.", + "methods": "A visualização {0} exige a definição dos métodos {1}." + }, + "lowercase": [ + "um", + "uma", + "e", + "como", + "em", + "no", + "na", + "mas", + "por", + "para", + "pelo", + "pela", + "de", + "do", + "da", + "se", + "perto", + "nem", + "ou", + "que", + "o", + "a", + "com", + "v" + ], + "method": { + "active": "segmentos activos", + "color": "cor", + "depth": "profundidade", + "dev": "verboso", + "focus": "foco", + "icon": "ícone", + "id": "identificador", + "height": "altura", + "labels": "etiquetas", + "legend": "legenda", + "margin": "margem", + "messages": "mensagens de status", + "order": "ordenar", + "search": "pesquisar", + "shape": "forma", + "size": "tamanho", + "style": "estilo", + "temp": "segmentos temporários", + "text": "texto", + "time": "Tempo", + "timeline": "cronograma", + "total": "segmentos totais", + "type": "digitar", + "width": "largura", + "x": "eixo x", + "y": "eixo y", + "zoom": "zoom", + "mode": "modo", + "mute": "ocultar", + "solo": "isolar" + }, + "time": [ + "data", + "dia", + "mês", + "hora", + "ano" + ], + "visualization": { + "bubbles": "Bolhas", + "chart": "Gráfico", + "geo_map": "Mapa", + "line": "Gráfico de Linha", + "network": "Rede", + "rings": "Anéis", + "scatter": "dispersão", + "stacked": "Evolução", + "tree_map": "Tree Map", + "bar": "Gráfico de Barras", + "box": "box Plot", + "paths": "caminhos", + "pie": "Carta de torta", + "table": "Mesa" + }, + "ui": { + "and": "e", + "back": "voltar", + "collapse": "clique para entrar em colapso", + "error": "erro", + "expand": "clique para expandir", + "loading": "carregando ...", + "more": "mais {0}", + "moreInfo": "Clique para mais informações", + "noResults": "nenhum resultado para {0}.", + "primary": "conexões primárias", + "share": "participação", + "total": "total", + "values": "valores", + "including": "Incluindo", + "or": "ou", + "iqr": "intervalo interquartil para {0}", + "max": "máximo", + "min": "mínimo", + "percentile": "{0} percentil", + "tukey_bottom": "tukey bottom", + "tukey_top": "tukey topo", + "quartile_first": "primeiro quartil", + "quartile_third": "terceiro quartil", + "median": "mediana" + }, + "message": { + "data": "analisando dados", + "draw": "desenhando visualização", + "initializing": "inicializando {0}", + "loading": "carregando dados", + "tooltipReset": "redefinindo as dicas", + "ui": "atualizando interface" + }, + "uppercase": [ + "CEO", + "CEOs", + "CFO", + "CFOs", + "CNC", + "COO", + "COOs", + "CPU", + "CPUs", + "PIB", + "HVAC", + "ID", + "TI", + "P&D", + "TV", + "IU" + ] +} + +},{}],78:[function(require,module,exports){ +module.exports = { + "format": { + "decimal": ",", + "thousands": ".", + "grouping": [3], + "currency": ["€", ""], + "dateTime": "%A, %e de %B de %Y. %X", + "date": "%d/%m/%Y", + "time": "%H:%M:%S", + "periods": ["AM", "PM"], + "days": ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"], + "shortDays": ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"], + "months": ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"], + "shortMonths": ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"] + }, + "error": { + "accepted": "{0} não é uma {1} válida para a visualização {2}, por favor escolha uma das seguintes: {3}.", + "connections": "não existem ligações disponíveis para {0}.", + "data": "não existem dados disponíveis", + "dataYear": "não existem dados disponíveis para {0}.", + "lib": "a visualização {0} necessita que a biblioteca {1} seja carregada.", + "libs": "a visualização {0} necessita que as seguintes bibliotecas sejam carregadas: {1}.", + "method": "A visualização {0} exige a definição do método {1}.", + "methods": "A visualização {0} exige a definição dos seguintes métodos {1}." + }, + "lowercase": [ + "um", + "uma", + "e", + "como", + "em", + "no", + "na", + "mas", + "por", + "para", + "pelo", + "pela", + "de", + "do", + "da", + "se", + "perto", + "nem", + "ou", + "que", + "o", + "a", + "com", + "v" + ], + "method": { + "active": "segmentos activos", + "color": "cor", + "depth": "profundidade", + "dev": "verboso", + "focus": "foco", + "icon": "ícone", + "id": "identificador", + "height": "altura", + "labels": "etiquetas", + "legend": "legenda", + "margin": "margem", + "messages": "estado", + "order": "ordenar", + "search": "pesquisar", + "shape": "forma", + "size": "tamanho", + "style": "estilo", + "temp": "segmentos temporários", + "text": "texto", + "time": "tempo", + "timeline": "linha temporal", + "total": "segmentos totais", + "type": "digitar", + "width": "largura", + "x": "eixo dos xx", + "y": "eixo dos yy", + "zoom": "zoom", + "mode": "modo", + "mute": "ocultar", + "solo": "isolar" + }, + "time": [ + "data", + "dia", + "mês", + "hora", + "ano" + ], + "visualization": { + "bubbles": "Bolhas", + "chart": "Diagrama", + "geo_map": "Mapa", + "line": "Gráfico de Linha", + "network": "Grafo", + "rings": "Anéis", + "scatter": "Gráfico de Dispersão", + "stacked": "Gráfico de Área", + "tree_map": "Tree Map", + "bar": "Gráfico de Barras", + "box": "Diagrama de Caixa e Bigodes", + "paths": "caminhos", + "pie": "Gráfico de Setores", + "table": "Mesa" + }, + "ui": { + "and": "e", + "back": "voltar", + "collapse": "Clique para colapsar", + "error": "erro", + "expand": "clique para expandir", + "loading": "a carregar ...", + "more": "mais {0}", + "moreInfo": "Clique para mais informações", + "noResults": "nenhum resultado para {0}.", + "primary": "ligações principais", + "share": "proporção", + "total": "total", + "values": "valores", + "including": "Incluindo", + "or": "ou", + "iqr": "intervalo interquartil para {0}", + "max": "máximo", + "min": "mínimo", + "percentile": "{0} percentil", + "tukey_bottom": "tukey bottom", + "tukey_top": "tukey topo", + "quartile_first": "primeiro quartil", + "quartile_third": "terceiro quartil", + "median": "mediana" + }, + "message": { + "data": "a analisar os dados", + "draw": "a desenhar a visualização", + "initializing": "a inicializar {0}", + "loading": "a carregar os dados", + "tooltipReset": "a actualizar as caixas de informação", + "ui": "a actualizar o interface" + }, + "uppercase": [ + "CEO", + "CEOs", + "CFO", + "CFOs", + "CNC", + "COO", + "COOs", + "CPU", + "CPUs", + "PIB", + "HVAC", + "ID", + "TI", + "I&D", + "TV", + "IU" + ] +} + +},{}],79:[function(require,module,exports){ +module.exports = { + "format": { + "decimal": ",", + "thousands": "\xa0", + "grouping": [3], + "currency": ["", " руб."], + "dateTime": "%A, %e %B %Y г. %X", + "date": "%d.%m.%Y", + "time": "%H:%M:%S", + "periods": ["AM", "PM"], + "days": ["воскресенье", "понедельник", "вторник", "среда", "четверг", "пятница", "суббота"], + "shortDays": ["вс", "пн", "вт", "ср", "чт", "пт", "сб"], + "months": ["января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"], + "shortMonths": ["янв", "фев", "мар", "апр", "май", "июн", "июл", "авг", "сен", "окт", "ноя", "дек"] + }, + "error": { + "accepted": "{0} не является обслуживаемым {1} для {2} визуализаций, пожалуйста, используйте одно из следующих действий: {3}.", + "connections": "нет соединений, доступных для {0}.", + "data": "данные недоступны", + "dataYear": "нет данных для {0}.", + "lib": "{0} визуализаций требуют загрузки {1} библиотеки.", + "libs": "{0} визуализаций требует загрузки следующие библиотеки: {1}.", + "method": "{0} визуализаций требуют установки {1} метод.", + "methods": "{0} визуализаций требуют установки следующих методов: {1}." + }, + "lowercase": [ + "и", + "как", + "в", + "но", + "для", + "из", + "если в", + "в", + "недалеко", + "ни", + "на", + "на", + "или", + "в", + "что", + "к", + "с", + "с помощью", + "против", + "против" + ], + "method": { + "active": "активные сегменты", + "color": "цвет", + "depth": "глубина", + "dev": "подробный", + "focus": "фокус", + "icon": "значок", + "id": "Я бы", + "height": "высота", + "labels": "надписи", + "legend": "легенда", + "margin": "поле", + "messages": "сообщения о состоянии", + "order": "заказ", + "search": "поиск", + "shape": "форма", + "size": "размер", + "style": "стиль", + "temp": "временные сегменты", + "text": "текст", + "time": "время", + "timeline": "график", + "total": "всего сегментов", + "type": "тип", + "width": "ширина", + "x": "ось х", + "y": "ось Y", + "zoom": "масштаб", + "mode": "Режим", + "mute": "скрывать", + "solo": "изолировать" + }, + "time": [ + "дата", + "день недели", + "месяц", + "время", + "год" + ], + "visualization": { + "bubbles": "Пузыри", + "chart": "Диаграмма", + "geo_map": "Карта Geo", + "line": "линия Участок", + "network": "сеть", + "rings": "Кольца", + "scatter": "Scatter Plot", + "stacked": "Stacked Площадь", + "tree_map": "Дерево Карта", + "bar": "гистограмма", + "box": "Box Участок", + "paths": "пути", + "pie": "Круговая диаграмма", + "table": "Таблица" + }, + "ui": { + "and": "а также", + "back": "назад", + "collapse": "нажмите, чтобы свернуть", + "error": "ошибка", + "expand": "нажмите, чтобы развернуть", + "loading": "загрузка ...", + "more": "{0} более", + "moreInfo": "нажмите для получения дополнительной информации", + "noResults": "нет результатов, соответствующих {0}.", + "primary": "первичные соединения", + "share": "доля", + "total": "Всего", + "values": "значения", + "including": "в том числе", + "or": "или", + "iqr": "межквартильный диапазон для {0}", + "max": "максимальная", + "min": "минимальный", + "percentile": "{0} процентиль", + "tukey_bottom": "нижний Тьюки", + "tukey_top": "сверху Тьюки", + "quartile_first": "первый квартиль", + "quartile_third": "третий квартиль", + "median": "медиана" + }, + "message": { + "data": "данные анализа", + "draw": "рисование визуализация", + "initializing": "инициализацией {0}", + "loading": "Загрузка данных", + "tooltipReset": "сброс всплывающих подсказок", + "ui": "обновление пользовательского интерфейса" + }, + "uppercase": [ + "ID" + ] +} + +},{}],80:[function(require,module,exports){ +module.exports = { + "format": { + "decimal": ".", + "thousands": ",", + "grouping": [3], + "currency": ["¥", ""], + "dateTime": "%A %B %e %Y %X", + "date": "%Y/%-m/%-d", + "time": "%H:%M:%S", + "periods": ["上午", "下午"], + "days": ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"], + "shortDays": ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"], + "months": ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], + "shortMonths": ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"] + }, + "error": { + "accepted": "{0}对于{2}的可视化效果并不是一个可接受的{1}, 请使用如下的一个:{3}.", + "connections": "没有对{0}可用的连接。", + "data": "无可用数据", + "dataYear": "没有数据对{0}可用。", + "lib": "{0}的可视化要求装载{1}库。", + "libs": "{0}的可视化需要加载以下库:{1}。", + "method": "{0}的可视化要求设置{1}方法。", + "methods": "{0}的可视化要求设置以下方法:{1}。" + }, + "lowercase": [ + "一个", + "和", + "在", + "但是", + "在...里", + "的", + "或者", + "这", + "向", + "与...一起" + ], + "method": { + "active": "活跃段", + "color": "颜色", + "depth": "深度", + "dev": "详细", + "focus": "焦点", + "icon": "图标", + "id": "身份认证", + "height": "高度", + "labels": "标签", + "legend": "图例注释", + "margin": "外边距", + "messages": "状态消息", + "order": "规则", + "search": "搜索", + "shape": "形状", + "size": "大小", + "style": "样式", + "temp": "暂时性区段", + "text": "文本", + "time": "时间", + "timeline": "时间轴", + "total": "总段", + "type": "类型", + "width": "宽度", + "x": "X轴", + "y": "Y轴", + "zoom": "缩放", + "mode": "模式", + "mute": "隐藏", + "solo": "隔离" + }, + "time": [ + "日", + "星期", + "月", + "时间", + "年" + ], + "visualization": { + "bubbles": "气泡", + "chart": "图表", + "geo_map": "地理地图", + "line": "线图", + "network": "网络", + "rings": "特性", + "scatter": "散点图", + "stacked": "堆积面积图", + "tree_map": "树图", + "bar": "条图", + "box": "箱形图", + "paths": "路径", + "pie": "饼形图", + "table": "表" + }, + "ui": { + "and": "和", + "back": "后面", + "collapse": "点击合并", + "error": "错误", + "expand": "单击以展开", + "loading": "载入中...", + "more": "{0}更多", + "moreInfo": "点击了解更多信息", + "noResults": "没有结果匹配{0}。", + "primary": "主要连接", + "share": "共享", + "total": "总", + "values": "值", + "including": "包括", + "or": "要么", + "iqr": "间距范围为{0}", + "max": "最大值", + "min": "最低限度", + "percentile": "{0}百分", + "tukey_bottom": "底部杜克", + "tukey_top": "顶部杜克", + "quartile_first": "第一个四分位数", + "quartile_third": "第三个四分位数", + "median": "中位数" + }, + "message": { + "data": "分析数据", + "draw": "绘制可视化", + "initializing": "初始化{0}", + "loading": "加载数据", + "tooltipReset": "重置工具提示", + "ui": "更新UI" + }, + "uppercase": [ + "CEO", + "CEOs", + "CFO", + "CFOs", + "CNC", + "COO", + "COOs", + "CPU", + "CPUs", + "GDP", + "HVAC", + "ID", + "电视", + "用户界面", + "研发" + ] +} + +},{}],81:[function(require,module,exports){ +module.exports = { + de_DE: require("./languages/de_DE.js"), + en_US: require("./languages/en_US.coffee"), + es_ES: require("./languages/es_ES.js"), + fr_FR: require("./languages/fr_FR.js"), + ko_KR: require("./languages/ko_KR.js"), + mk_MK: require("./languages/mk_MK.js"), + pt_BR: require("./languages/pt_BR.js"), + pt_PT: require("./languages/pt_PT.js"), + ru_RU: require("./languages/ru_RU.js"), + zh_CN: require("./languages/zh_CN.js") +}; + + +},{"./languages/de_DE.js":71,"./languages/en_US.coffee":72,"./languages/es_ES.js":73,"./languages/fr_FR.js":74,"./languages/ko_KR.js":75,"./languages/mk_MK.js":76,"./languages/pt_BR.js":77,"./languages/pt_PT.js":78,"./languages/ru_RU.js":79,"./languages/zh_CN.js":80}],82:[function(require,module,exports){ +var checkObject, copy, createFunction, initialize, print, process, setMethod, stringFormat, validObject; + +copy = require("../../util/copy.coffee"); + +print = require("../console/print.coffee"); + +process = require("./process/detect.coffee"); + +setMethod = require("./set.coffee"); + +stringFormat = require("../../string/format.js"); + +validObject = require("../../object/validate.coffee"); + +module.exports = function(vars, methods) { + var method, obj, results; + results = []; + for (method in methods) { + obj = methods[method]; + vars[method] = copy(obj); + vars[method].initialized = initialize(vars, vars[method], method); + results.push(vars.self[method] = createFunction(vars, method)); + } + return results; +}; + +initialize = function(vars, obj, method, p) { + var d, deps, i, len, o; + obj.previous = false; + obj.changed = false; + obj.initialized = false; + obj.callback = false; + if ("init" in obj && (!("value" in obj))) { + obj.value = obj.init(vars); + delete obj.init; + } + if ("process" in obj) { + obj.value = process(vars, obj, obj.value); + } + for (o in obj) { + if (o === "deprecates") { + deps = obj[o] instanceof Array ? obj[o] : [obj[o]]; + for (i = 0, len = deps.length; i < len; i++) { + d = deps[i]; + vars.self[d] = (function(dep, n) { + return function(x) { + var doc, rec, str; + str = vars.format.locale.value.dev.deprecated; + dep = "." + dep + "()"; + rec = p ? "\"" + n + "\" in ." + p + "()" : "." + n + "()"; + doc = p || n; + print.error(stringFormat(str, dep, rec), doc); + return vars.self; + }; + })(d, method); + } + } else if (o === "global") { + if (!(method in vars)) { + vars[method] = []; + } + } else if (o !== "value") { + if (validObject(obj[o])) { + initialize(vars, obj[o], o, method); + } + } + } + return true; +}; + +createFunction = function(vars, key) { + return function(user, callback) { + var accepted, checkFont, checkValue, fontAttr, fontAttrValue, s, starting, str; + accepted = "accepted" in vars[key] ? vars[key].accepted : null; + if (typeof accepted === "function") { + accepted = accepted(vars); + } + if (!(accepted instanceof Array)) { + accepted = [accepted]; + } + if (user === Object) { + return vars[key]; + } else if (!arguments.length && accepted.indexOf(void 0) < 0) { + if ("value" in vars[key]) { + return vars[key].value; + } else { + return vars[key]; + } + } + if (key === "style" && typeof user === "object") { + str = vars.format.locale.value.dev.oldStyle; + for (s in user) { + print.warning(stringFormat(str, "\"" + s + "\"", s), s); + vars.self[s](user[s]); + } + } + if (key === "font") { + if (typeof user === "string") { + user = { + family: user + }; + } + starting = true; + checkValue = function(o, a, m, v) { + if (validObject(o[m]) && a in o[m]) { + if (validObject(o[m][a])) { + if (o[m][a].process) { + o[m][a].value = o[m][a].process(v); + } else { + o[m][a].value = v; + } + } else { + o[m][a] = v; + } + } + }; + checkFont = function(o, a, v) { + var m; + if (validObject(o)) { + if (starting) { + for (m in o) { + checkValue(o, a, m, v); + } + } else if ("font" in o) { + checkValue(o, a, "font", v); + } + starting = false; + for (m in o) { + checkFont(o[m], a, v); + } + } + }; + for (fontAttr in user) { + fontAttrValue = user[fontAttr]; + if (fontAttr !== "secondary") { + if (validObject(fontAttrValue)) { + fontAttrValue = fontAttrValue.value; + } + if (fontAttrValue) { + checkFont(vars, fontAttr, fontAttrValue); + } + } + } + } + checkObject(vars, key, vars, key, user); + if (typeof callback === "function") { + vars[key].callback = callback; + } + if (vars[key].chainable === false) { + return vars[key].value; + } else { + return vars.self; + } + }; +}; + +checkObject = function(vars, method, object, key, value) { + var approvedObject, d, objectOnly, passingObject; + if (["accepted", "changed", "initialized", "previous", "process"].indexOf(key) < 0) { + passingObject = validObject(value); + objectOnly = validObject(object[key]) && "objectAccess" in object[key] && object[key]["objectAccess"] === false; + approvedObject = passingObject && (objectOnly || ((!("value" in value)) && ((!validObject(object[key])) || (!(d3.keys(value)[0] in object[key]))))); + if (value === null || !passingObject || approvedObject) { + setMethod(vars, method, object, key, value); + } else if (passingObject) { + for (d in value) { + checkObject(vars, method, object[key], d, value[d]); + } + } + } +}; + + +},{"../../object/validate.coffee":175,"../../string/format.js":176,"../../util/copy.coffee":210,"../console/print.coffee":54,"./process/detect.coffee":90,"./set.coffee":96}],83:[function(require,module,exports){ +module.exports = function(g) { + if (!g) { + g = false; + } + return { + accepted: [false, Array, Function, Number, Object, String], + callback: { + accepted: [false, Function], + value: false + }, + global: g, + process: Array, + value: [] + }; +}; + + +},{}],84:[function(require,module,exports){ +var rtl; + +rtl = require("../../../client/rtl.coffee"); + +module.exports = function(align) { + var accepted; + accepted = ["left", "center", "right"]; + if (align === false) { + accepted.unshift(false); + } + if (accepted.indexOf(align) < 0) { + align = "left"; + } + return { + accepted: accepted, + process: function(value) { + if (rtl) { + if (value === "left") { + return "right"; + } else { + if (value === "right") { + return "left"; + } else { + return value; + } + } + } else { + return value; + } + }, + value: align + }; +}; + + +},{"../../../client/rtl.coffee":42}],85:[function(require,module,exports){ +module.exports = function(decoration) { + var accepted; + accepted = ["line-through", "none", "overline", "underline"]; + if (decoration === false) { + accepted.unshift(false); + } + if (accepted.indexOf(decoration) < 0) { + decoration = "none"; + } + return { + accepted: accepted, + value: decoration + }; +}; + + +},{}],86:[function(require,module,exports){ +var helvetica, validate; + +validate = require("../../../font/validate.coffee"); + +helvetica = ["Helvetica Neue", "HelveticaNeue", "Helvetica", "Arial", "sans-serif"]; + +module.exports = function(family) { + if (family === void 0) { + family = helvetica; + } + return { + process: validate, + value: family + }; +}; + + +},{"../../../font/validate.coffee":105}],87:[function(require,module,exports){ +module.exports = function(position) { + var accepted; + accepted = ["top", "middle", "bottom"]; + if (position === false) { + accepted.unshift(false); + } + if (accepted.indexOf(position) < 0) { + position = "bottom"; + } + return { + accepted: accepted, + mapping: { + top: "0ex", + middle: "0.5ex", + bottom: "1ex" + }, + process: function(value) { + this.text = value; + return this.mapping[value]; + }, + value: position + }; +}; + + +},{}],88:[function(require,module,exports){ +module.exports = function(transform) { + var accepted; + accepted = ["capitalize", "lowercase", "none", "uppercase"]; + if (transform === false) { + accepted.unshift(false); + } + if (accepted.indexOf(transform) < 0) { + transform = "none"; + } + return { + accepted: accepted, + value: transform + }; +}; + + +},{}],89:[function(require,module,exports){ +module.exports = function(value, vars, method) { + var elem; + if (vars.history) { + vars.history.reset(); + } + if (value.constructor === String) { + if (value.indexOf("/") >= 0) { + method.url = value; + return []; + } + elem = d3.selectAll(value); + if (elem.size()) { + return elem; + } + if (value.indexOf(".") >= 0) { + method.url = value; + } + return []; + } else { + return value; + } +}; + + +},{}],90:[function(require,module,exports){ +var copy, update; + +copy = require("../../../util/copy.coffee"); + +update = require("../../../array/update.coffee"); + +module.exports = function(vars, object, value) { + if (object.process === Array) { + return update(copy(object.value), value); + } else if (typeof object.process === "object" && typeof value === "string") { + return object.process[value]; + } else if (typeof object.process === "function") { + return object.process(value, vars, object); + } else { + return value; + } +}; + + +},{"../../../array/update.coffee":37,"../../../util/copy.coffee":210}],91:[function(require,module,exports){ +var stylesheet; + +stylesheet = require("../../../client/css.coffee"); + +module.exports = function(value, vars, method) { + if (value === false || value.indexOf("fa-") < 0 || (value.indexOf("fa-") === 0 && stylesheet("font-awesome"))) { + return value; + } else { + return method.fallback; + } +}; + + +},{"../../../client/css.coffee":38}],92:[function(require,module,exports){ +module.exports = function(value, self) { + var i, j, k, l, len, len1, len2, len3, m, results, side, sides, v; + if (typeof value === "string") { + value = value.split(" "); + for (i = j = 0, len = value.length; j < len; i = ++j) { + v = value[i]; + value[i] = parseFloat(v, 10); + } + if (value.length === 1) { + value = value[0]; + } else if (value.length === 2) { + value = { + top: value[0], + right: value[1], + bottom: value[0], + left: value[1] + }; + } else if (value.length === 3) { + value = { + top: value[0], + right: value[1], + bottom: value[2], + left: value[1] + }; + } else if (value.length === 4) { + value = { + top: value[0], + right: value[1], + bottom: value[2], + left: value[3] + }; + } else { + value = 0; + } + } + sides = ["top", "right", "bottom", "left"]; + if (typeof value === "number") { + for (k = 0, len1 = sides.length; k < len1; k++) { + side = sides[k]; + self[side] = value; + } + } else { + for (l = 0, len2 = sides.length; l < len2; l++) { + side = sides[l]; + self[side] = value[side]; + } + } + self.css = ""; + results = []; + for (i = m = 0, len3 = sides.length; m < len3; i = ++m) { + side = sides[i]; + if (i) { + self.css += " "; + } + results.push(self.css += self[side] + "px"); + } + return results; +}; + + +},{}],93:[function(require,module,exports){ +var contains, format, list, print; + +contains = require("../../array/contains.coffee"); + +format = require("../../string/format.js"); + +list = require("../../string/list.coffee"); + +print = require("../console/print.coffee"); + +module.exports = function(vars, accepted, value, method, text) { + var a, allowed, app, i, len, recs, str, val; + if (typeof accepted === "function") { + accepted = accepted(vars); + } + if (!(accepted instanceof Array)) { + accepted = [accepted]; + } + allowed = contains(accepted, value); + if (allowed === false && value !== void 0) { + recs = []; + val = JSON.stringify(value); + if (typeof value !== "string") { + val = "\"" + val + "\""; + } + for (i = 0, len = accepted.length; i < len; i++) { + a = accepted[i]; + if (typeof a === "string") { + recs.push("\"" + a + "\""); + } else if (typeof a === "function") { + recs.push(a.toString().split("()")[0].substring(9)); + } else if (a === void 0) { + recs.push("undefined"); + } else { + recs.push(JSON.stringify(a)); + } + } + recs = list(recs, vars.format.locale.value.ui.or); + if (vars.type && ["mode", "shape"].indexOf(method) >= 0) { + str = vars.format.locale.value.error.accepted; + app = vars.format.locale.value.visualization[vars.type.value] || vars.type.value; + print.warning(format(str, val, method, app, recs), method); + } else { + str = vars.format.locale.value.dev.accepted; + print.warning(format(str, val, text, recs), method); + } + } + return !allowed; +}; + + +},{"../../array/contains.coffee":35,"../../string/format.js":176,"../../string/list.coffee":177,"../console/print.coffee":54}],94:[function(require,module,exports){ +module.exports = function(rendering) { + var accepted; + accepted = ["auto", "optimizeSpeed", "crispEdges", "geometricPrecision"]; + if (!(accepted.indexOf(rendering) >= 0)) { + rendering = "crispEdges"; + } + return { + accepted: accepted, + value: rendering + }; +}; + + +},{}],95:[function(require,module,exports){ +var reset, validObject; + +validObject = require("../../object/validate.coffee"); + +reset = function(obj, method) { + var o; + if (obj.changed) { + obj.changed = false; + } + if (method === "draw") { + obj.frozen = false; + obj.update = true; + obj.first = false; + } + for (o in obj) { + if (o.indexOf("d3plus") < 0 && validObject(obj[o])) { + reset(obj[o], o); + } + } +}; + +module.exports = reset; + + +},{"../../object/validate.coffee":175}],96:[function(require,module,exports){ +var copy, d3selection, mergeObject, print, process, rejected, stringFormat, updateArray, validObject; + +copy = require("../../util/copy.coffee"); + +d3selection = require("../../util/d3selection.coffee"); + +validObject = require("../../object/validate.coffee"); + +mergeObject = require("../../object/merge.coffee"); + +print = require("../console/print.coffee"); + +process = require("./process/detect.coffee"); + +rejected = require("./rejected.coffee"); + +stringFormat = require("../../string/format.js"); + +updateArray = require("../../array/update.coffee"); + +module.exports = function(vars, method, object, key, value) { + var accepted, c, callback, d3object, hasValue, id, k, longArray, n, parentKey, str, text, typeFunction, valString; + if (key === "value" || !key || key === method) { + text = "." + method + "()"; + } else { + text = "\"" + key + "\" " + vars.format.locale.value.dev.of + " ." + method + "()"; + } + if (key === "value" && "accepted" in object) { + accepted = object.accepted; + } else if (validObject(object[key]) && "accepted" in object[key]) { + accepted = object[key].accepted; + } else { + accepted = [value]; + } + if (!rejected(vars, accepted, value, method, text)) { + if (validObject(object[key]) && "value" in object[key]) { + parentKey = key; + object = object[key]; + key = "value"; + } + if (key === "value" && "process" in object) { + value = process(vars, object, value); + } + if ((!(object[key] instanceof Array)) && object[key] === value && value !== void 0) { + str = vars.format.locale.value.dev.noChange; + if (vars.dev.value) { + print.comment(stringFormat(str, text)); + } + } else { + object.changed = true; + if (object.loaded) { + object.loaded = false; + } + if ("history" in vars && method !== "draw") { + c = copy(object); + c.method = method; + vars.history.chain.push(c); + } + object.previous = object[key]; + if ("id" in vars && key === "value" && "nesting" in object) { + if (method !== "id") { + if (typeof object.nesting !== "object") { + object.nesting = {}; + } + if (validObject(value)) { + for (id in value) { + if (typeof value[id] === "string") { + value[id] = [value[id]]; + } + } + object.nesting = mergeObject(object.nesting, value); + if (!(vars.id.value in object.nesting)) { + object.nesting[vars.id.value] = value[d3.keys(value)[0]]; + } + } else if (value instanceof Array) { + object.nesting[vars.id.value] = value; + } else { + object.nesting[vars.id.value] = [value]; + } + object[key] = object.nesting[vars.id.value][0]; + } else { + if (value instanceof Array) { + object.nesting = value; + if ("depth" in vars && vars.depth.value < value.length) { + object[key] = value[vars.depth.value]; + } else { + object[key] = value[0]; + if ("depth" in vars) { + vars.depth.value = 0; + } + } + } else { + object[key] = value; + object.nesting = [value]; + if ("depth" in vars) { + vars.depth.value = 0; + } + } + } + } else if (method === "depth") { + if (value >= vars.id.nesting.length) { + vars.depth.value = vars.id.nesting.length - 1; + } else if (value < 0) { + vars.depth.value = 0; + } else { + vars.depth.value = value; + } + vars.id.value = vars.id.nesting[vars.depth.value]; + if (typeof vars.text.nesting === "object") { + n = vars.text.nesting[vars.id.value]; + if (n) { + vars.text.nesting[vars.id.value] = typeof n === "string" ? [n] : n; + vars.text.value = (n instanceof Array ? n[0] : n); + } + } + } else if (validObject(object[key]) && validObject(value)) { + object[key] = mergeObject(object[key], value); + } else { + object[key] = value; + } + if (key === "value" && object.global) { + hasValue = object[key].length > 0; + k = parentKey || key; + if (k in vars && ((hasValue && vars.data[k].indexOf(method) < 0) || (!hasValue && vars.data[k].indexOf(method) >= 0))) { + vars.data[k] = updateArray(vars.data[k], method); + } + } + if (key === "value" && object.dataFilter && vars.data && vars.data.filters.indexOf(method) < 0) { + vars.data.filters.push(method); + } + if (vars.dev.value && object.changed && object[key] !== void 0) { + longArray = object[key] instanceof Array && object[key].length > 10; + d3object = d3selection(object[key]); + typeFunction = typeof object[key] === "function"; + valString = (!longArray && !d3object && !typeFunction ? (typeof object[key] === "string" ? object[key] : JSON.stringify(object[key])) : null); + if (valString !== null && valString.length < 260) { + str = vars.format.locale.value.dev.setLong; + print.log(stringFormat(str, text, "\"" + valString + "\"")); + } else { + str = vars.format.locale.value.dev.set; + print.log(stringFormat(str, text)); + } + } + } + if (key === "value" && object.callback && !object.url) { + callback = typeof object.callback === "function" ? object.callback : object.callback.value; + if (callback) { + callback(value, vars.self); + } + } + } +}; + + +},{"../../array/update.coffee":37,"../../object/merge.coffee":174,"../../object/validate.coffee":175,"../../string/format.js":176,"../../util/copy.coffee":210,"../../util/d3selection.coffee":211,"../console/print.coffee":54,"./process/detect.coffee":90,"./rejected.coffee":93}],97:[function(require,module,exports){ +var print = require("../console/print.coffee"), + stringFormat = require("../../string/format.js") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Cleans edges list and populates nodes list if needed +//------------------------------------------------------------------- +module.exports = function( vars ) { + + if ( vars.dev.value ) { + var timerString = "analyzing edges list" + print.time( timerString ) + } + + var appReqs = vars.types[vars.type.value].requirements + if (!(appReqs instanceof Array)) appReqs = [appReqs] + var createNodes = appReqs.indexOf("nodes") >= 0 && !vars.nodes.value + + if ( createNodes ) { + vars.nodes.value = [] + var placed = [] + vars.nodes.changed = true + } + + vars.edges.value.forEach(function(e){ + + ["source", "target"].forEach(function(dir){ + + var dirType = typeof e[vars.edges[dir]]; + + if (dirType !== "object") { + if (dirType === "number" && !createNodes && vars.data.keys[vars.id.value] !== "number") { + e[vars.edges[dir]] = vars.nodes.value[e[vars.edges[dir]]]; + } + else { + if (createNodes && placed.indexOf(e[vars.edges[dir]]) >= 0) { + e[vars.edges[dir]] = vars.nodes.value.filter(function(n){ + return n[vars.id.value] === e[vars.edges[dir]]; + })[0]; + } + else { + var obj = {}; + obj[vars.id.value] = e[vars.edges[dir]]; + e[vars.edges[dir]] = obj; + } + } + } + + var newNode = e[vars.edges[dir]]; + if (createNodes) { + if (placed.indexOf(newNode[vars.id.value]) < 0) { + placed.push(newNode[vars.id.value]); + vars.nodes.value.push(newNode); + } + } + }); + + if (!("keys" in vars.data)) { + vars.data.keys = {}; + } + + if (!(vars.id.value in vars.data.keys)) { + vars.data.keys[vars.id.value] = typeof e[vars.edges.source][vars.id.value]; + } + + }); + + vars.edges.value = vars.edges.value.filter(function(e){ + + var source = e[vars.edges.source][vars.id.value] + , target = e[vars.edges.target][vars.id.value] + + if ( source === target ) { + var str = vars.format.locale.value.dev.sameEdge + print.warning(stringFormat(str,"\""+source+"\"") , "edges" ) + return false + } + else { + return true + } + + }) + + vars.edges.linked = true + + if ( vars.dev.value ) print.timeEnd( timerString ) + +} + +},{"../../string/format.js":176,"../console/print.coffee":54}],98:[function(require,module,exports){ +var hideElement = require("./hideElement.js"); + +// Parses an HTML element for data +module.exports = function( vars ) { + + var attributes = [ vars.color.value + , vars.icon.value + , vars.keywords.value + , vars.alt.value + , "style" ] + + if (!vars.text.value) { + vars.self.text("text") + } + + attributes = attributes.concat(vars.id.nesting) + + function get_attributes( obj , elem ) { + [].forEach.call(elem.attributes, function(attr) { + if (/^data-/.test(attr.name)) { + var camelCaseName = attr.name.substr(5).replace(/-(.)/g, function ($0, $1) { + return $1.toUpperCase(); + }); + obj[camelCaseName] = attr.value; + } + }) + + attributes.forEach(function(a){ + + if ( elem.getAttribute(a) !== null ) { + obj[a] = elem.getAttribute(a) + } + + }) + + } + + vars.self.data({"element": vars.data.value}) + + var elementTag = vars.data.element.value.node().tagName.toLowerCase() + , elementType = vars.data.element.value.attr("type") + , elementData = [] + + if ( elementTag === "select" ) { + + var elementID = vars.data.element.value.node().id + if ( elementID ) { + vars.self.container({"id": elementID}) + } + + vars.data.element.value.selectAll("option") + .each(function( o , i ){ + + var data_obj = {} + + data_obj.text = d3.select(this).text(); + + get_attributes(data_obj,this) + + elementData.push(data_obj) + + if (this.selected) { + for (var i = vars.id.nesting.length-1; i >= 0; i--) { + var level = vars.id.nesting[i] + if (level in data_obj) { + vars.self.focus(data_obj[level]) + break + } + } + } + + }) + + } + else if ( elementTag === "input" && elementType === "radio" ) { + + var elementName = vars.data.element.value.node().getAttribute("name") + if ( elementName ) { + vars.self.container({"id": elementName}) + } + + vars.data.element.value + .each(function( o , i ){ + + var data_obj = {} + + get_attributes(data_obj,this) + + var id = data_obj[vars.id.value] || this.id || false + + if ( id && isNaN(parseFloat(id)) ) { + + var label = d3.select("label[for="+id+"]") + + if ( !label.empty() ) { + data_obj.text = label.html() + label.call(hideElement) + } + + } + + elementData.push(data_obj) + + if (this.checked) { + vars.self.focus(data_obj[vars.id.value]) + } + + }) + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Get focus from data, if it hasn't been found or set. + //---------------------------------------------------------------------------- + if ( !vars.focus.value.length && elementData.length ) { + + vars.data.element.value.node().selectedIndex = 0 + vars.self.focus(elementData[0][vars.id.value]) + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If a element exists, use it as the title. + //---------------------------------------------------------------------------- + var elementLegend = d3.select("legend[for="+vars.container.id+"]") + if ( !elementLegend.empty() ) { + + vars.self.title(elementLegend.html()) + elementLegend.call(hideElement) + + } + + var containerTag = vars.container.value + ? vars.container.value.node().tagName.toLowerCase() : false + + if ( vars.container.value === false || containerTag === "body" ) { + vars.container.value = d3.select(vars.data.element.value.node().parentNode) + } + + vars.data.element.value.call(hideElement) + + return elementData + +}; + +},{"./hideElement.js":99}],99:[function(require,module,exports){ +module.exports = function(elem) { + + elem + .style("position","absolute","important") + .style("clip","rect(1px 1px 1px 1px)","important") + .style("clip","rect(1px, 1px, 1px, 1px)","important") + .style("width","1px","important") + .style("height","1px","important") + .style("margin","-1px","important") + .style("padding","0","important") + .style("border","0","important") + .style("overflow","hidden","important"); + +} + +},{}],100:[function(require,module,exports){ +var print = require("../console/print.coffee"); + +// Calculates node positions, if needed for network. +module.exports = function(vars) { + + if (vars.type.value === "network") { + + if (vars.dev.value) { + var timerString = "analyzing node positions"; + print.time(timerString); + } + + var set = vars.nodes.value.filter(function(n){ + return typeof n.x === "number" && typeof n.y === "number"; + }).length; + + if (set === vars.nodes.value.length) { + vars.nodes.positions = true; + } + else { + + var force = d3.layout.force() + .size([vars.width.viz, vars.height.viz]) + .nodes(vars.nodes.value) + .links(vars.edges.value); + + var strength = vars.edges.strength.value; + if (strength) { + if (typeof strength === "string") { + force.linkStrength(function(e){ + return e[strength]; + }); + } + else { + force.linkStrength(strength); + } + } + + var iterations = 50, + threshold = 0.01; + + force.start(); // Defaults to alpha = 0.1 + for (var i = iterations; i > 0; --i) { + force.tick(); + if(force.alpha() < threshold) { + break; + } + } + force.stop(); + + vars.nodes.positions = true; + + } + + if (vars.dev.value) print.timeEnd(timerString); + + } + +} + +},{"../console/print.coffee":54}],101:[function(require,module,exports){ +var numeric; + +numeric = require('numeric'); + +module.exports = function(data, options) { + var N, X, Xfulltr, Xtr, bestResult, beta_hat, bic, degree, degrees, i, j, k, l, loglike, m, point, prevBIC, q, ref, ref1, residual, sigma2, sse, y, y_hat; + if (options == null) { + options = {}; + } + if (options.maxDegree == null) { + options.maxDegree = 5; + } + N = data.length; + prevBIC = Number.MAX_VALUE; + bestResult = null; + Xfulltr = (function() { + var l, ref, results; + results = []; + for (degree = l = 1, ref = options.maxDegree + 1; 1 <= ref ? l < ref : l > ref; degree = 1 <= ref ? ++l : --l) { + results.push((function() { + var len, m, results1; + results1 = []; + for (m = 0, len = data.length; m < len; m++) { + point = data[m]; + results1.push(Math.pow(point[0], degree)); + } + return results1; + })()); + } + return results; + })(); + y = (function() { + var l, len, results; + results = []; + for (l = 0, len = data.length; l < len; l++) { + point = data[l]; + results.push(point[1]); + } + return results; + })(); + for (i = l = 0, ref = 1 << options.maxDegree; 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) { + Xtr = [ + (function() { + var m, ref1, results; + results = []; + for (q = m = 0, ref1 = N; 0 <= ref1 ? m < ref1 : m > ref1; q = 0 <= ref1 ? ++m : --m) { + results.push(1); + } + return results; + })() + ]; + degrees = [0]; + for (j = m = 0, ref1 = options.maxDegree; 0 <= ref1 ? m < ref1 : m > ref1; j = 0 <= ref1 ? ++m : --m) { + if ((i & 1 << j) > 0) { + Xtr.push(Xfulltr[j]); + degrees.push(j + 1); + } + } + X = numeric.transpose(Xtr); + k = degrees.length; + beta_hat = numeric.dot(numeric.dot(numeric.inv(numeric.dot(Xtr, X)), Xtr), y); + y_hat = numeric.dot(X, beta_hat); + residual = numeric.sub(y, y_hat); + sse = numeric.dot(residual, residual); + sigma2 = sse / (N - k); + loglike = -0.5 * N * Math.log(2 * Math.PI) - 0.5 * N * Math.log(sigma2) - sse / (2 * sigma2); + bic = -2 * loglike + k * (Math.log(N) - Math.log(2 * Math.PI)); + if (bic < prevBIC) { + prevBIC = bic; + bestResult = [degrees, beta_hat, y_hat]; + } + } + return bestResult; +}; + + +},{"numeric":8}],102:[function(require,module,exports){ +var kdtree; + +kdtree = require('static-kdtree'); + +module.exports = function(points, K) { + var avg_lrd, i, j, kdists, ldr, ldrs, neighbors, p, reachDist, result, sqDist, tree; + if (K == null) { + K = 10; + } + tree = kdtree(points); + neighbors = (function() { + var k, len, results; + results = []; + for (k = 0, len = points.length; k < len; k++) { + p = points[k]; + results.push(tree.knn(p, K + 1).slice(1)); + } + return results; + })(); + sqDist = function(i, j) { + var A, B, delta, dist, k, ref; + A = points[i]; + B = points[j]; + dist = 0; + for (i = k = 0, ref = A.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) { + delta = A[i] - B[i]; + dist += delta * delta; + } + return dist; + }; + kdists = (function() { + var k, ref, results; + results = []; + for (i = k = 0, ref = points.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) { + results.push(sqDist(i, neighbors[i][K - 1])); + } + return results; + })(); + reachDist = function(i, j) { + return Math.max(sqDist(i, j), kdists[j]); + }; + ldr = function(i) { + var j, k, len, rDist, ref; + rDist = 0; + ref = neighbors[i]; + for (k = 0, len = ref.length; k < len; k++) { + j = ref[k]; + rDist += reachDist(i, j); + } + return K / rDist; + }; + ldrs = (function() { + var k, ref, results; + results = []; + for (i = k = 0, ref = points.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) { + results.push(ldr(i)); + } + return results; + })(); + result = (function() { + var k, l, len, ref, ref1, results; + results = []; + for (i = k = 0, ref = points.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) { + avg_lrd = 0; + ref1 = neighbors[i]; + for (l = 0, len = ref1.length; l < len; l++) { + j = ref1[l]; + avg_lrd += ldrs[j]; + } + avg_lrd /= K; + results.push([i, avg_lrd / ldrs[i]]); + } + return results; + })(); + return result.sort(function(a, b) { + return b[1] - a[1]; + }); +}; + + +},{"static-kdtree":10}],103:[function(require,module,exports){ +module.exports = function(points) { + var mad, median, result; + median = d3.median(points); + mad = d3.median(points.map(function(p) { + return Math.abs(p - median); + })); + result = points.map(function(p, i) { + return [i, Math.abs(p - median) / mad]; + }); + return result.sort(function(a, b) { + return b[1] - a[1]; + }); +}; + + +},{}],104:[function(require,module,exports){ +var fontTester; + +fontTester = require("../core/font/tester.coffee"); + +module.exports = function(words, style, opts) { + var attr, getHeight, getWidth, sizes, spacing, tester, tspans; + if (!opts) { + opts = {}; + } + style = style || {}; + tester = opts.parent || fontTester("svg").append("text"); + sizes = []; + if (!(words instanceof Array)) { + words = [words]; + } + tspans = tester.selectAll("tspan").data(words); + attr = { + left: "0px", + position: "absolute", + top: "0px", + x: 0, + y: 0 + }; + spacing = 0; + if ("letter-spacing" in style) { + spacing = parseFloat(style["letter-spacing"]); + delete style["letter-spacing"]; + } + getWidth = function(elem) { + var add; + add = 0; + if (spacing) { + add = (d3.select(elem).text().length - 1) * spacing; + } + return elem.getComputedTextLength() + add; + }; + getHeight = function(elem) { + return elem.parentNode.getBBox().height || elem.getBoundingClientRect().height; + }; + tspans.enter().append("tspan").text(String).style(style).attr(attr).each(function(d) { + if (typeof opts.mod === "function") { + return opts.mod(this); + } + }).each(function(d) { + var children, height, width; + children = d3.select(this).selectAll("tspan"); + if (children.size()) { + width = []; + children.each(function() { + return width.push(getWidth(this)); + }); + width = d3.max(width); + } else { + width = getWidth(this); + } + height = getHeight(this); + return sizes.push({ + height: height, + text: d, + width: width + }); + }); + tspans.remove(); + if (!opts.parent) { + tester.remove(); + } + return sizes; +}; + + +},{"../core/font/tester.coffee":70}],105:[function(require,module,exports){ +var fontTester, validate; + +fontTester = require("../core/font/tester.coffee"); + +validate = function(fontList) { + var completed, family, font, fontString, i, j, len, len1, monospace, proportional, testElement, testWidth, tester, valid; + if (!(fontList instanceof Array)) { + fontList = fontList.split(","); + } + for (i = 0, len = fontList.length; i < len; i++) { + font = fontList[i]; + font.trim(); + } + fontString = fontList.join(", "); + completed = validate.complete; + if (fontString in completed) { + return completed[fontString]; + } + testElement = function(font) { + return tester.append("span").style("font-family", font).style("font-size", "32px").style("padding", "0px").style("margin", "0px").text("abcdefghiABCDEFGHI_!@#$%^&*()_+1234567890"); + }; + testWidth = function(font, control) { + var elem, width1, width2; + elem = testElement(font); + width1 = elem.node().offsetWidth; + width2 = control.node().offsetWidth; + elem.remove(); + return width1 !== width2; + }; + tester = fontTester("div"); + monospace = testElement("monospace"); + proportional = testElement("sans-serif"); + for (j = 0, len1 = fontList.length; j < len1; j++) { + family = fontList[j]; + valid = testWidth(family + ",monospace", monospace); + if (!valid) { + valid = testWidth(family + ",sans-serif", proportional); + } + if (valid) { + valid = family; + break; + } + } + if (!valid) { + valid = "sans-serif"; + } + monospace.remove(); + proportional.remove(); + completed[fontString] = valid; + return valid; +}; + +validate.complete = {}; + +module.exports = validate; + + +},{"../core/font/tester.coffee":70}],106:[function(require,module,exports){ +var arraySort = require("../array/sort.coffee"), + attach = require("../core/methods/attach.coffee"), + dataFormat = require("../core/data/format.js"), + dataKeys = require("../core/data/keys.coffee"), + dataLoad = require("../core/data/load.coffee"), + fetchData = require("../core/fetch/data.js"), + ie = require("../client/ie.js"), + methodReset = require("../core/methods/reset.coffee"), + print = require("../core/console/print.coffee"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Form Element shell +//------------------------------------------------------------------------------ +module.exports = function() { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialize the global variable object. + //---------------------------------------------------------------------------- + var vars = { + "types": { + "auto": require("./types/auto.js"), + "button": require("./types/button/button.coffee"), + "drop": require("./types/drop/drop.coffee"), + "toggle": require("./types/toggle.js") + } + }; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create the main drawing function. + //---------------------------------------------------------------------------- + vars.self = function( selection ) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Set timing to 0 if it's the first time running this function or if the + // data length is longer than the "large" limit + //-------------------------------------------------------------------------- + var large = vars.data.value instanceof Array && vars.data.value.length > vars.data.large; + + vars.draw.timing = vars.draw.first || large || ie ? 0 : vars.timing.ui; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create/update the UI element + //-------------------------------------------------------------------------- + if ( vars.data.value instanceof Array ) { + + if ( vars.dev.value ) print.group("drawing \""+vars.type.value+"\""); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Analyze new data, if changed. + //------------------------------------------------------------------------ + if ( vars.data.changed ) { + vars.data.cache = {}; + dataKeys( vars , "data" ); + dataFormat( vars ); + } + + vars.data.viz = fetchData( vars ); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Sort the data, if needed. + //------------------------------------------------------------------------ + if (vars.data.sort.value && (vars.data.changed || vars.order.changed || vars.order.sort.changed) ) { + arraySort( vars.data.viz , vars.order.value || vars.text.value, + vars.order.sort.value , vars.color.value , vars ); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Set first element in data as focus if there is no focus set. + //------------------------------------------------------------------------ + if (vars.focus.value === false && ["auto", "button"].indexOf(vars.type.value) < 0) { + + var element = vars.data.element.value; + + if ( element && element.node().tagName.toLowerCase() === "select" ) { + var i = element.property("selectedIndex"); + i = i < 0 ? 0 : i; + var option = element.selectAll("option")[0][i], + val = option.getAttribute("data-"+vars.id.value) || option.getAttribute(vars.id.value); + if (val) vars.focus.value = val; + } + + if ( vars.focus.value === false && vars.data.viz.length ) { + vars.focus.value = vars.data.viz[0][vars.id.value]; + } + + if (vars.dev.value && vars.focus.value !== false) print.log("\"value\" set to \""+vars.focus.value+"\""); + + } + + var getLevel = function(d,depth) { + + depth = typeof depth !== "number" ? vars.id.nesting.length === 1 ? 0 : vars.id.nesting.length-1 : depth; + var level = vars.id.nesting[depth]; + + if ( depth > 0 && (!(level in d) || d[level] instanceof Array) ) { + return getLevel(d,depth-1); + } + else { + return level; + } + + }; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Run these things if the data has changed. + //------------------------------------------------------------------------ + if ( vars.data.changed ) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Determine if search box is needed. + //---------------------------------------------------------------------- + if ( vars.search.value === "auto" ) { + + if (vars.data.viz.length > 10) { + vars.search.enabled = true; + if ( vars.dev.value ) print.log("Search enabled."); + } + else { + vars.search.enabled = false; + if ( vars.dev.value ) print.log("Search disabled."); + } + + } + else { + + vars.search.enabled = vars.search.value; + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Update OPTION elements with the new data. + //---------------------------------------------------------------------- + var elementTag = vars.data.element.value ? vars.data.element.value.node().tagName.toLowerCase() : ""; + if ( vars.data.element.value && elementTag === "select" ) { + + var optionData = []; + for (var level in vars.data.nested.all) { + optionData = optionData.concat(vars.data.nested.all[level]); + } + + options = vars.data.element.value.selectAll("option") + .data(optionData,function(d){ + var level = d ? getLevel(d) : false; + return d && level in d ? d[level] : false; + }); + + options.exit().remove(); + + options.enter().append("option"); + + options + .each(function(d){ + + var level = getLevel(d), + textKey = level === vars.id.value ? vars.text.value || vars.id.value + : vars.text.nesting !== true && level in vars.text.nesting ? vars.text.nesting[level] : level; + + for ( var k in d ) { + + if ( typeof d[k] !== "object" ) { + + if ( k === textKey ) { + d3.select(this).html(d[k]); + } + + if ( ["alt","value"].indexOf(k) >= 0 ) { + d3.select(this).attr(k,d[k]); + } + else { + d3.select(this).attr("data-"+k,d[k]); + } + + } + + } + + if (d[level] === vars.focus.value) { + this.selected = true; + } + else { + this.selected = false; + } + + }); + + } + + } + else if (vars.focus.changed && vars.data.element.value) { + var tag = vars.data.element.value.node().tagName.toLowerCase(); + if (tag === "select") { + vars.data.element.value.selectAll("option") + .each(function(d){ + if (d[getLevel(d)] === vars.focus.value) { + this.selected = true; + } + else { + this.selected = false; + } + }); + } + else { + var tag = vars.data.element.value.attr("type").toLowerCase(); + if (tag === "radio") { + vars.data.element.value + .each(function(d){ + if (this.value === vars.focus.value) { + this.checked = true; + } + else { + this.checked = false; + } + }) + } + } + } + + if ( vars.type.value !== "auto" ) { + + if ( !vars.container.ui ) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Select container DIV for UI element + //---------------------------------------------------------------------- + vars.container.ui = vars.container.value + .selectAll("div#d3plus_"+vars.type.value+"_"+vars.container.id) + .data(["container"]); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create container DIV for UI element + //---------------------------------------------------------------------- + var before = vars.data.element.value ? vars.data.element.value[0][0] : null; + + if ( before ) { + + if ( before.id ) { + before = "#"+before.id; + } + else { + + var id = before.getAttribute(vars.id.value) ? vars.id.value : "data-"+vars.id.value; + + if ( before.getAttribute(id) ) { + before = "["+id+"="+before.getAttribute(id)+"]"; + } + else { + before = null; + } + + } + + } + + vars.container.ui.enter() + .insert("div",before) + .attr("id","d3plus_"+vars.type.value+"_"+vars.container.id) + .style("position","relative") + .style("overflow","visible") + .style("vertical-align","top"); + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Update Container + //------------------------------------------------------------------------ + vars.container.ui + .style("display", vars.ui.display.value); + + vars.container.ui.transition().duration(vars.draw.timing) + .style("margin", vars.ui.margin.css); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create title, if available. + //------------------------------------------------------------------------ + var title = vars.container.ui.selectAll("div.d3plus_title") + .data(vars.title.value ? [vars.title.value] : []); + + title.enter().insert("div","#d3plus_"+vars.type.value+"_"+vars.container.id) + .attr("class","d3plus_title") + .style("display","inline-block"); + + title + .style("color",vars.font.color) + .style("font-family",vars.font.family.value) + .style("font-size",vars.font.size+"px") + .style("font-weight",vars.font.weight) + .style("padding",vars.ui.padding.css) + .style("border-color","transparent") + .style("border-style","solid") + .style("border-width",vars.ui.border+"px") + .text(String) + .each(function(d){ + vars.margin.left = this.offsetWidth; + }); + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Call specific UI element type, if there is data. + //------------------------------------------------------------------------ + if ( vars.data.value.length ) { + + var app = vars.format.locale.value.visualization[vars.type.value]; + if ( vars.dev.value ) print.time("drawing "+ app); + vars.types[vars.type.value]( vars ); + if ( vars.dev.value ) print.timeEnd("drawing "+ app); + + } + else if ( vars.data.url && (!vars.data.loaded || vars.data.stream) ) { + + dataLoad( vars , "data" , vars.self.draw ); + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialization complete + //------------------------------------------------------------------------ + if (vars.dev.value) print.timeEnd("total draw time"); + methodReset( vars ); + + } + + }; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Define methods and expose public variables. + //---------------------------------------------------------------------------- + attach(vars, { + "active": require("./methods/active.coffee"), + "alt": require("./methods/alt.coffee"), + "color": require("./methods/color.coffee"), + "config": require("./methods/config.coffee"), + "container": require("./methods/container.coffee"), + "data": require("./methods/data.js"), + "depth": require("./methods/depth.coffee"), + "dev": require("./methods/dev.coffee"), + "draw": require("./methods/draw.js"), + "focus": require("./methods/focus.coffee"), + "font": require("./methods/font.coffee"), + "format": require("./methods/format.coffee"), + "height": require("./methods/height.coffee"), + "history": require("./methods/history.coffee"), + "hover": require("./methods/hover.coffee"), + "icon": require("./methods/icon.coffee"), + "id": require("./methods/id.coffee"), + "keywords": require("./methods/keywords.coffee"), + "margin": require("./methods/margin.coffee"), + "open": require("./methods/open.coffee"), + "order": require("./methods/order.coffee"), + "remove": require("./methods/remove.coffee"), + "search": require("./methods/search.coffee"), + "select": require("./methods/select.coffee"), + "selectAll": require("./methods/selectAll.coffee"), + "text": require("./methods/text.coffee"), + "timing": require("./methods/timing.coffee"), + "title": require("./methods/title.coffee"), + "type": require("./methods/type.coffee"), + "ui": require("./methods/ui.coffee"), + "width": require("./methods/width.coffee") + }); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Finally, return the main UI function to the user + //---------------------------------------------------------------------------- + return vars.self; + +}; + +},{"../array/sort.coffee":36,"../client/ie.js":39,"../core/console/print.coffee":54,"../core/data/format.js":58,"../core/data/keys.coffee":60,"../core/data/load.coffee":61,"../core/fetch/data.js":66,"../core/methods/attach.coffee":82,"../core/methods/reset.coffee":95,"./methods/active.coffee":107,"./methods/alt.coffee":108,"./methods/color.coffee":109,"./methods/config.coffee":110,"./methods/container.coffee":111,"./methods/data.js":112,"./methods/depth.coffee":113,"./methods/dev.coffee":114,"./methods/draw.js":115,"./methods/focus.coffee":116,"./methods/font.coffee":117,"./methods/format.coffee":118,"./methods/height.coffee":119,"./methods/history.coffee":120,"./methods/hover.coffee":121,"./methods/icon.coffee":122,"./methods/id.coffee":123,"./methods/keywords.coffee":124,"./methods/margin.coffee":125,"./methods/open.coffee":126,"./methods/order.coffee":127,"./methods/remove.coffee":128,"./methods/search.coffee":129,"./methods/select.coffee":130,"./methods/selectAll.coffee":131,"./methods/text.coffee":132,"./methods/timing.coffee":133,"./methods/title.coffee":134,"./methods/type.coffee":135,"./methods/ui.coffee":136,"./methods/width.coffee":137,"./types/auto.js":138,"./types/button/button.coffee":139,"./types/drop/drop.coffee":144,"./types/toggle.js":161}],107:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [false, Array, Function, Number, String], + value: false +}; + + +},{"../../core/methods/filter.coffee":83}],108:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [false, Array, Function, Object, String], + mute: filter(true), + solo: filter(true), + value: "alt" +}; + + +},{"../../core/methods/filter.coffee":83}],109:[function(require,module,exports){ +module.exports = { + accepted: [String], + value: "color" +}; + + +},{}],110:[function(require,module,exports){ +module.exports = { + accepted: [Object], + objectAccess: false, + process: function(value, vars) { + var method, setting; + for (method in value) { + setting = value[method]; + if (method in vars.self) { + vars.self[method](setting); + } + } + return value; + }, + value: {} +}; + + +},{}],111:[function(require,module,exports){ +var d3selection; + +d3selection = require("../../util/d3selection.coffee"); + +module.exports = { + accepted: [false, Array, Object, String], + element: false, + id: "default", + process: function(value) { + if (value === false) { + return d3.select("body"); + } else if (d3selection(value)) { + return value; + } else if (value instanceof Array) { + return d3.select(value[0][0]); + } else { + this.selector = value; + return d3.select(value); + } + }, + value: d3.select("body") +}; + + +},{"../../util/d3selection.coffee":211}],112:[function(require,module,exports){ +var d3selection = require("../../util/d3selection.coffee"), + process = require("../../core/methods/process/data.coffee"); + +module.exports = { + "accepted" : [ false , Array , Function , String ], + "delimiter" : { + "accepted" : [ String ], + "value" : "|" + }, + "element": { + "process": function(value, vars) { + + var element = false; + + if ( d3selection(value) ) { + element = value; + } + else if (typeof value === "string" && !d3.select(value).empty()) { + element = d3.select(value); + } + + if (element) { + vars.self.container(d3.select(element.node().parentNode)); + } + + return element; + + }, + "value": false + }, + "filetype" : { + "accepted" : [false, "json", "xml", "html", "csv", "dsv", "tsv", "txt"], + "value" : false + }, + "filters" : [], + "large": 400, + "mute" : [], + "process" : function(value, vars) { + + if ( vars.container.id === "default" && value.length ) { + vars.self.container({"id": "default"+value.length}); + } + + return process(value, vars, this); + }, + "solo" : [], + "sort": { + "accepted": [Boolean], + "value": false + }, + "value" : false +}; + +},{"../../core/methods/process/data.coffee":89,"../../util/d3selection.coffee":211}],113:[function(require,module,exports){ +module.exports = { + accepted: [Number], + value: 0 +}; + + +},{}],114:[function(require,module,exports){ +module.exports = { + accepted: [Boolean], + value: false +}; + + +},{}],115:[function(require,module,exports){ +var d3selection = require("../../util/d3selection.coffee"), + hideElement = require("../../core/parse/hideElement.js"), + parseElement = require("../../core/parse/element.js"), + print = require("../../core/console/print.coffee"), + stringFormat = require("../../string/format.js") + +module.exports = { + "accepted" : [ undefined , Function ], + "first" : true, + "frozen" : false, + "process" : function (value, vars) { + + if ( this.initialized === false ) { + this.initialized = true + return value + } + + if (vars.data.value && (!(vars.data.value instanceof Array) || d3selection(vars.data.value))) { + vars.data.value = parseElement( vars ) + } + else if (vars.data.element.value) { + vars.data.element.value.call(hideElement); + } + + if ( value === undefined && typeof this.value === "function" ) { + value = this.value + } + + if ( vars.container.value === false ) { + + var str = vars.format.locale.value.dev.setContainer + print.warning( str , "container" ) + + } + else if ( vars.container.value.empty() ) { + + var str = vars.format.locale.value.dev.noContainer + var selector = vars.container.selector || ""; + print.warning( stringFormat(str, "\"" + selector + "\"") , "container" ) + + } + else { + + if (vars.dev.value) print.time("total draw time"); + + vars.container.value.call(vars.self); + + } + + if ( typeof value === "function" && vars.history.chain.length ) { + + var changesObject = {} + vars.history.chain.forEach(function(c){ + var method = c.method + delete c.method + changesObject[method] = c + }) + + value(changesObject) + + vars.history.chain = [] + + } + + return value + + }, + "update" : true, + "value" : undefined +} + +},{"../../core/console/print.coffee":54,"../../core/parse/element.js":98,"../../core/parse/hideElement.js":99,"../../string/format.js":176,"../../util/d3selection.coffee":211}],116:[function(require,module,exports){ +module.exports = { + accepted: [false, Number, String], + deprecates: "highlight", + process: function(value, vars) { + var d, element, elementTag, elementType, i, j, k, len, len1, ref; + element = vars.data.element.value; + if (element && ["string", "number"].indexOf(typeof value) >= 0) { + elementTag = element.node().tagName.toLowerCase(); + elementType = element.attr("type"); + if (elementTag === "select") { + ref = element.selectAll("option"); + for (i = j = 0, len = ref.length; j < len; i = ++j) { + d = ref[i]; + if (d && d[vars.id.value] === value) { + element.node().selectedIndex = i; + } + } + } else if (elementTag === "input" && elementType === "radio") { + for (k = 0, len1 = element.length; k < len1; k++) { + d = element[k]; + this.checked = d && d[vars.id.value] === value; + } + } + } + return value; + }, + value: false +}; + + +},{}],117:[function(require,module,exports){ +var align, decoration, family, transform; + +family = require("../../core/methods/font/family.coffee"); + +align = require("../../core/methods/font/align.coffee"); + +decoration = require("../../core/methods/font/decoration.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +module.exports = { + align: align(), + color: "#444444", + decoration: decoration(), + family: family(), + secondary: { + align: align(), + color: "#444444", + decoration: decoration(), + family: family(), + size: 12, + spacing: 0, + transform: transform(), + weight: 200 + }, + size: 12, + spacing: 0, + transform: transform(), + weight: 200 +}; + + +},{"../../core/methods/font/align.coffee":84,"../../core/methods/font/decoration.coffee":85,"../../core/methods/font/family.coffee":86,"../../core/methods/font/transform.coffee":88}],118:[function(require,module,exports){ +var formatNumber, locale, mergeObject, titleCase; + +formatNumber = require("../../number/format.coffee"); + +locale = require("../../core/locale/locale.coffee"); + +mergeObject = require("../../object/merge.coffee"); + +titleCase = require("../../string/title.coffee"); + +module.exports = { + accepted: [Function, String], + affixes: { + accepted: [Object], + objectAccess: false, + value: {} + }, + deprecates: ["number_format", "text_format"], + locale: { + accepted: function() { + return d3.keys(locale); + }, + process: function(value) { + var defaultLocale, returnObject; + defaultLocale = "en_US"; + returnObject = locale[defaultLocale]; + if (value !== defaultLocale) { + returnObject = mergeObject(returnObject, locale[value]); + } + this.language = value; + return returnObject; + }, + value: "en_US" + }, + number: { + accepted: [false, Function], + value: false + }, + process: function(value, vars) { + if (typeof value === "string") { + vars.self.format({ + locale: value + }); + } else { + if (typeof value === "function") { + return value; + } + } + return this.value; + }, + text: { + accepted: [false, Function], + value: false + }, + value: function(value, opts) { + var f, v, vars; + if (!opts) { + opts = {}; + } + vars = opts.vars || {}; + if (vars.time && vars.time.value && opts.key === vars.time.value) { + v = value.constructor === Date ? value : new Date(value); + return vars.data.time.format(v); + } else if (typeof value === "number") { + f = this.number.value || formatNumber; + return f(value, opts); + } else if (typeof value === "string") { + f = this.text.value || titleCase; + return f(value, opts); + } else { + return JSON.stringify(value); + } + } +}; + + +},{"../../core/locale/locale.coffee":81,"../../number/format.coffee":173,"../../object/merge.coffee":174,"../../string/title.coffee":179}],119:[function(require,module,exports){ +module.exports = { + accepted: [false, Number], + max: 600, + secondary: false, + value: false +}; + + +},{}],120:[function(require,module,exports){ +module.exports = { + back: function() { + if (this.states.length) { + return this.states.pop()(); + } + }, + chain: [], + reset: function() { + var results; + results = []; + while (this.states.length) { + results.push(this.states.pop()()); + } + return results; + }, + states: [] +}; + + +},{}],121:[function(require,module,exports){ +module.exports = { + accepted: [Boolean, Number, String], + value: false +}; + + +},{}],122:[function(require,module,exports){ +var process; + +process = require("../../core/methods/process/icon.coffee"); + +module.exports = { + accepted: [false, Array, Function, Object, String], + back: { + accepted: [false, String], + fallback: "❮", + opacity: 1, + process: process, + rotate: 0, + value: "fa-angle-left" + }, + button: { + accepted: [false, String], + fallback: false, + opacity: 1, + process: process, + rotate: 0, + value: false + }, + drop: { + accepted: [false, String], + fallback: "❯", + opacity: 1, + process: process, + rotate: 0, + value: "fa-angle-down" + }, + next: { + accepted: [false, String], + fallback: "❯", + opacity: 1, + process: process, + rotate: 0, + value: "fa-angle-right" + }, + select: { + accepted: [false, String], + fallback: "✓", + opacity: 1, + process: process, + rotate: 0, + value: "fa-check" + }, + style: { + accepted: [Object, String], + value: "default" + }, + value: "icon" +}; + + +},{"../../core/methods/process/icon.coffee":91}],123:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [Array, String], + dataFilter: true, + mute: filter(true), + nesting: ["value"], + solo: filter(true), + value: "value" +}; + + +},{"../../core/methods/filter.coffee":83}],124:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [false, Array, Function, Object, String], + mute: filter(true), + solo: filter(true), + value: "keywords" +}; + + +},{"../../core/methods/filter.coffee":83}],125:[function(require,module,exports){ +var process; + +process = require("../../core/methods/process/margin.coffee"); + +module.exports = { + accepted: [Number, Object, String], + process: function(value) { + var userValue; + if (value === void 0) { + value = this.value; + } + userValue = value; + process(value, this); + return userValue; + }, + value: 0 +}; + + +},{"../../core/methods/process/margin.coffee":92}],126:[function(require,module,exports){ +module.exports = { + accepted: [Boolean], + flipped: { + accepted: [Boolean], + value: false + }, + value: false +}; + + +},{}],127:[function(require,module,exports){ +module.exports = { + accepted: [false, Function, String], + sort: { + accepted: ["asc", "desc"], + deprecates: ["sort"], + value: "asc" + }, + value: false +}; + + +},{}],128:[function(require,module,exports){ +module.exports = { + accepted: [void 0, Function], + process: function(value, vars) { + if (this.initialized) { + vars.container.ui.remove(); + } + delete vars.container.ui; + }, + value: void 0 +}; + + +},{}],129:[function(require,module,exports){ +module.exports = { + accepted: ["auto", Boolean], + process: function(value) { + if (typeof value === "Boolean") { + this.enabled = value; + } + return value; + }, + term: "", + value: "auto" +}; + + +},{}],130:[function(require,module,exports){ +module.exports = { + accepted: [String], + chainable: false, + process: function(value, vars) { + var container; + container = vars.container.value; + if (container && value) { + return container.select(value); + } else { + return value; + } + }, + value: void 0 +}; + + +},{}],131:[function(require,module,exports){ +module.exports = { + accepted: [String], + chainable: false, + process: function(value, vars) { + var container; + container = vars.container.value; + if (container && value) { + return container.selectAll(value); + } else { + return value; + } + }, + value: void 0 +}; + + +},{}],132:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [false, String], + nesting: true, + mute: filter(true), + solo: filter(true), + secondary: { + accepted: [false, String], + nesting: true, + value: false + }, + value: false +}; + + +},{"../../core/methods/filter.coffee":83}],133:[function(require,module,exports){ +module.exports = { + mouseevents: 60, + ui: 200 +}; + + +},{}],134:[function(require,module,exports){ +var decoration, family, stringStrip, transform; + +decoration = require("../../core/methods/font/decoration.coffee"); + +family = require("../../core/methods/font/family.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +stringStrip = require("../../string/strip.js"); + +module.exports = { + accepted: [false, Function, String], + font: { + align: "center", + color: "#444444", + decoration: decoration(), + family: family(), + size: 16, + transform: transform(), + weight: 400 + }, + link: false, + process: function(value, vars) { + var id; + if (vars.container.id.indexOf("default") === 0 && value) { + id = stringStrip(value).toLowerCase(); + vars.self.container({ + id: id + }); + } + return value; + }, + value: false +}; + + +},{"../../core/methods/font/decoration.coffee":85,"../../core/methods/font/family.coffee":86,"../../core/methods/font/transform.coffee":88,"../../string/strip.js":178}],135:[function(require,module,exports){ +module.exports = { + accepted: function(vars) { + return d3.keys(vars.types); + }, + value: "auto" +}; + + +},{}],136:[function(require,module,exports){ +var align, decoration, family, margin, transform; + +family = require("../../core/methods/font/family.coffee"); + +align = require("../../core/methods/font/align.coffee"); + +decoration = require("../../core/methods/font/decoration.coffee"); + +margin = require("../../core/methods/process/margin.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +module.exports = { + align: align("center"), + border: 1, + color: { + primary: { + process: function(value, vars) { + var primary; + primary = this.value; + if (!vars.ui.color.secondary.value) { + vars.ui.color.secondary.value = d3.rgb(primary).darker(0.75).toString(); + } + return value; + }, + value: "#ffffff" + }, + secondary: { + value: false + } + }, + display: { + acceped: ["block", "inline-block"], + value: "inline-block" + }, + font: { + align: align("center"), + color: "#444", + decoration: decoration(), + family: family(), + size: 11, + transform: transform(), + weight: 200 + }, + margin: { + process: function(value) { + var userValue; + if (value === void 0) { + value = this.value; + } + userValue = value; + margin(value, this); + return userValue; + }, + value: 5 + }, + padding: { + process: function(value) { + var userValue; + if (value === void 0) { + value = this.value; + } + userValue = value; + margin(value, this); + return userValue; + }, + value: 5 + } +}; + + +},{"../../core/methods/font/align.coffee":84,"../../core/methods/font/decoration.coffee":85,"../../core/methods/font/family.coffee":86,"../../core/methods/font/transform.coffee":88,"../../core/methods/process/margin.coffee":92}],137:[function(require,module,exports){ +module.exports = { + accepted: [false, Number], + secondary: false, + value: false +}; + + +},{}],138:[function(require,module,exports){ +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Determines form type based on data length. +//------------------------------------------------------------------------------ +module.exports = function( vars ) { + + var dataLength = vars.data.value.length + + if ( dataLength === 1 ) { + vars.self.type("button").draw() + } + else if ( dataLength < 5 ) { + vars.self.type("toggle").draw() + } + else { + vars.self.type("drop").draw() + } + +} + +},{}],139:[function(require,module,exports){ +module.exports = function(vars) { + var button, checks, color, icons, mouseevents, print, style, updatedButtons; + print = require("../../../core/console/print.coffee"); + color = require("./functions/color.coffee"); + icons = require("./functions/icons.js"); + mouseevents = require("./functions/mouseevents.coffee"); + style = require("./functions/style.js"); + button = vars.container.ui.selectAll('div.d3plus_node').data(vars.data.viz, function(d) { + return d[vars.id.value]; + }); + if (vars.dev.value) { + print.time("enter"); + } + button.enter().append("div").attr("class", "d3plus_node").call(color, vars).call(style, vars).call(icons, vars).call(mouseevents, vars); + if (vars.dev.value) { + print.timeEnd("enter"); + } + if (vars.draw.update || vars.draw.timing) { + if (vars.dev.value) { + print.time("ordering"); + } + button.order(); + if (vars.dev.value) { + print.timeEnd("ordering"); + } + updatedButtons = button; + } else { + checks = [vars.focus.previous, vars.focus.value, vars.hover.previous, vars.hover.value].filter(function(c) { + return c; + }); + updatedButtons = button.filter(function(b) { + return checks.indexOf(b[vars.id.value]) >= 0; + }); + } + if (vars.dev.value) { + print.time("update"); + } + updatedButtons.classed("d3plus_button_active", function(d) { + return vars.focus.value === d[vars.id.value]; + }); + if (vars.draw.timing) { + updatedButtons.transition().duration(vars.draw.timing).call(color, vars).call(style, vars); + } else { + updatedButtons.call(color, vars).call(style, vars); + } + updatedButtons.call(icons, vars).call(mouseevents, vars); + if (vars.dev.value) { + print.timeEnd("update"); + } + return button.exit().remove(); +}; + + +},{"../../../core/console/print.coffee":54,"./functions/color.coffee":140,"./functions/icons.js":141,"./functions/mouseevents.coffee":142,"./functions/style.js":143}],140:[function(require,module,exports){ +module.exports = function(elem, vars) { + var legible, lighter, textColor; + legible = require("../../../../color/legible.coffee"); + lighter = require("../../../../color/lighter.coffee"); + textColor = require("../../../../color/text.coffee"); + return elem.style("background-color", function(d) { + var color; + if (vars.focus.value === d[vars.id.value]) { + color = vars.ui.color.secondary.value; + } else { + color = vars.ui.color.primary.value; + } + if (vars.hover.value === d[vars.id.value]) { + color = d3.rgb(color).darker(0.15).toString(); + } + return color; + }).style("color", function(d) { + var bg, color, image, opacity; + if (vars.focus.value === d[vars.id.value]) { + opacity = 0.75; + } else { + opacity = 1; + } + image = d[vars.icon.value] && vars.data.viz.length < vars.data.large; + if (!image && d[vars.color.value]) { + color = legible(d[vars.color.value]); + } else { + if (vars.focus.value === d[vars.id.value]) { + bg = vars.ui.color.secondary.value; + } else { + bg = vars.ui.color.primary.value; + } + if (vars.hover.value === d[vars.id.value]) { + bg = d3.rgb(bg).darker(0.15).toString(); + } + color = textColor(bg); + } + color = d3.rgb(color); + return "rgba(" + color.r + "," + color.g + "," + color.b + "," + opacity + ")"; + }).style('border-color', vars.ui.color.secondary.value); +}; + + +},{"../../../../color/legible.coffee":46,"../../../../color/lighter.coffee":47,"../../../../color/text.coffee":52}],141:[function(require,module,exports){ +var prefix = require("../../../../client/prefix.coffee"), + rtl = require("../../../../client/rtl.coffee") + +module.exports = function ( elem , vars ) { + + var reversed = (vars.font.align.value === "right" && !rtl) + || (rtl && vars.font.align.value === "right") + + elem + .each(function(d,i){ + + var children = ["label"] + + if ( d[vars.icon.value] && vars.data.viz.length <= vars.data.large ) { + children.push("icon") + } + + var iconGraphic = vars.icon.button.value + if ( d[vars.id.value] === vars.focus.value && vars.icon.select.value ) { + iconGraphic = vars.icon.select.value + children.push("selected") + } + else if ( iconGraphic && d.d3plus.icon !== false ) { + children.push("selected") + } + + var buffer = 0 + + var items = d3.select(this).selectAll("div.d3plus_button_element") + .data(children,function(c){ + return c + }) + + items.enter().append("div") + .style("display",function(c){ + return c === "label" ? "block" : "absolute" + }) + + items.order() + .attr("class",function(c){ + var extra = "" + if ( c === "selected" && iconGraphic.indexOf("fa-") === 0 ) { + extra = " fa "+iconGraphic + } + return "d3plus_button_element d3plus_button_" + c + extra + }) + .html(function(c){ + if ( c === "label" ) { + var k = vars.text.value && vars.text.value in d && !(d[vars.text.value] instanceof Array) + ? vars.text.value : vars.id.value + return vars.format.value(d[k]) + } + return c === "selected" && iconGraphic.indexOf("fa-") < 0 + ? iconGraphic : "" + }) + .style("background-image",function(c){ + if (c === "icon") { + return "url('"+d[vars.icon.value]+"')" + } + return "none" + }) + .style("background-color",function(c){ + if (c === "icon" && d.style === "knockout") { + return d[vars.color.value] || vars.ui.color.primary.value + } + return "transparent" + }) + .style("background-size","100%") + .style("text-align",function(c){ + return c === "label" ? vars.font.align.value : "center" + }) + .style("position",function(c){ + return c == "label" ? "static" : "absolute" + }) + .style("width",function(c){ + + if ( c === "label" ) { + return "auto" + } + + if (vars.height.value) { + buffer = (vars.height.value-(vars.ui.padding.top + vars.ui.padding.bottom)-(vars.ui.border*2)); + } + else { + buffer = vars.font.size+vars.ui.border; + } + return buffer+"px" + }) + .style("height",function(c){ + if ( c === "icon" ) { + return buffer+"px" + } + return "auto" + }) + .style("margin-top",function(c){ + if ( c === "label" ) { + return "0px" + } + if (this.offsetHeight || this.getBoundingClientRect().height) { + var h = this.offsetHeight || this.getBoundingClientRect().height + } + else if ( c === "selected" ) { + var h = vars.font.size + } + else { + var h = buffer + } + return -h/2+"px" + }) + .style("top",function(c){ + return c === "label" ? "auto" : "50%" + }) + .style("left",function(c){ + if ((c === "icon" && !reversed) || (c === "selected" && reversed)) { + return vars.ui.padding.left+"px" + } + return "auto" + }) + .style("right",function(c){ + if ((c === "icon" && reversed) || (c === "selected" && !reversed)) { + return vars.ui.padding.right+"px" + } + return "auto" + }) + .style(prefix()+"transition",function(c){ + return c === "selected" ? (vars.draw.timing/1000)+"s" : "none" + }) + .style(prefix()+"transform",function(c){ + var degree = c === "selected" ? vars.icon.select.rotate : "none" + return typeof degree === "string" ? degree : "rotate("+degree+"deg)" + }) + .style("opacity",function(c){ + return c === "selected" ? vars.icon.select.opacity : 1 + }) + + items.exit().remove() + + var text = d3.select(this).selectAll(".d3plus_button_label") + + if (buffer > 0) { + + var p = vars.ui.padding; + + if (children.length === 3) { + p = p.top+"px "+(p.right*2+buffer)+"px "+p.bottom+"px "+(p.left*2+buffer)+"px"; + } + else if ((children.indexOf("icon") >= 0 && !rtl) || (children.indexOf("selected") >= 0 && rtl)) { + p = p.top+"px "+p.right+"px "+p.bottom+"px "+(p.left*2+buffer)+"px"; + } + else { + p = p.top+"px "+(p.right*2+buffer)+"px "+p.bottom+"px "+p.left+"px"; + } + + text.style("padding", p) + + } + else { + text.style("padding",vars.ui.padding.css) + } + + if (typeof vars.width.value === "number") { + var width = vars.width.value + width -= parseFloat(text.style("padding-left"),10) + width -= parseFloat(text.style("padding-right"),10) + width -= vars.ui.border*2 + width += "px" + } + else { + var width = "auto" + } + + text.style("width",width) + + }) + +} + +},{"../../../../client/prefix.coffee":41,"../../../../client/rtl.coffee":42}],142:[function(require,module,exports){ +module.exports = function(elem, vars, color) { + var events, ie; + color = require("./color.coffee"); + events = require("../../../../client/pointer.coffee"); + ie = require("../../../../client/ie.js"); + return elem.on(events.over, function(d, i) { + vars.self.hover(d[vars.id.value]); + if (ie || !vars.draw.timing) { + return d3.select(this).style("cursor", "pointer").call(color, vars); + } else { + return d3.select(this).style("cursor", "pointer").transition().duration(vars.timing.mouseevents).call(color, vars); + } + }).on(events.out, function(d) { + vars.self.hover(false); + if (ie || !vars.draw.timing) { + return d3.select(this).style("cursor", "auto").call(color, vars); + } else { + return d3.select(this).style("cursor", "auto").transition().duration(vars.timing.mouseevents).call(color, vars); + } + }).on(events.click, function(d) { + if (vars.focus.value !== false) { + return vars.self.focus(d[vars.id.value]).draw(); + } else if (vars.focus.callback) { + return vars.focus.callback(d, vars.self); + } + }); +}; + + +},{"../../../../client/ie.js":39,"../../../../client/pointer.coffee":40,"./color.coffee":140}],143:[function(require,module,exports){ +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// +//------------------------------------------------------------------------------ +module.exports = function ( elem , vars ) { + + elem + .style("position","relative") + .style("margin",vars.ui.margin.css) + .style("display",vars.ui.display.value) + .style("border-style","solid") + .style("border-width",vars.ui.border+"px") + .style("font-family",vars.font.family.value) + .style("font-size",vars.font.size+"px") + .style("font-weight",vars.font.weight) + .style("letter-spacing",vars.font.spacing+"px") + +} + +},{}],144:[function(require,module,exports){ +module.exports = function(vars) { + var button, data, element, keyboard, list, search, selector, title, update, width, windowevent; + element = require("./functions/element.coffee"); + keyboard = require("./functions/keyboard.coffee"); + windowevent = require("./functions/window.js"); + width = require("./functions/width.js"); + button = require("./functions/button.js"); + selector = require("./functions/selector.js"); + title = require("./functions/title.js"); + search = require("./functions/search.js"); + list = require("./functions/list.js"); + data = require("./functions/data.js"); + update = require("./functions/update.js"); + vars.margin.top = 0; + vars.margin.title = 0; + element(vars); + keyboard(vars); + windowevent(vars); + width(vars); + button(vars); + selector(vars); + title(vars); + search(vars); + list(vars); + data(vars); + return update(vars); +}; + + +},{"./functions/button.js":147,"./functions/data.js":148,"./functions/element.coffee":149,"./functions/keyboard.coffee":152,"./functions/list.js":153,"./functions/search.js":155,"./functions/selector.js":156,"./functions/title.js":157,"./functions/update.js":158,"./functions/width.js":159,"./functions/window.js":160}],145:[function(require,module,exports){ +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Checks to see if a given variable is allowed to be selected. +//------------------------------------------------------------------------------ +module.exports = function ( vars , value , active ) { + + var ret = [] + , active = active || vars.active.value + + if ( active instanceof Array ) { + + for (var i = 0; i < active.length; i++) { + ret.push(this(vars,value,active[i])) + } + + } + else { + + var t = typeof active + + if (t === "number") { + ret.push(vars.depth.value === active) + } + else if (t === "function") { + ret.push(active(value)) + } + else { + ret.push(value === active) + } + + } + + return ret.indexOf(true) >= 0 + +} + +},{}],146:[function(require,module,exports){ +var print = require("../../../../core/console/print.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Toggles the state of the dropdown menu. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + if ( vars.dev.value ) print.time("rotating arrow") + + var offset = vars.icon.drop.value === "❯" ? 90 : 0 + + if (vars.open.value != vars.open.flipped.value) { + var rotate = 180 + offset + } + else { + var rotate = offset + } + + vars.container.button + .icon({ + "select": { + "opacity": vars.open.value ? 0.5 : 1, + "rotate": rotate + } + }) + .draw() + + if ( vars.dev.value ) print.timeEnd("rotating arrow") + +} + +},{"../../../../core/console/print.coffee":54}],147:[function(require,module,exports){ +var copy = require("../../../../util/copy.coffee"), + events = require("../../../../client/pointer.coffee"), + form = require("../../../form.js"), + print = require("../../../../core/console/print.coffee") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates and styles the main drop button. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + if ( !("button" in vars.container) ) { + + if ( vars.dev.value ) print.time("creating main button") + + vars.container.button = form() + .container(vars.container.ui) + .type("button") + .ui({ + "margin": 0 + }) + + if ( vars.dev.value ) print.timeEnd("creating main button") + + } + + if ( vars.focus.changed || vars.data.changed || vars.depth.changed ) { + + var depth = vars.depth.value + + var buttonData = copy(vars.data.value.filter(function(d){ + var match = false + for ( var i = 0 ; i < vars.id.nesting.length ; i++ ) { + var level = vars.id.nesting[i] + match = level in d && d[level] === vars.focus.value + if (match) { + depth = i + break + } + } + return match + })[0]) + + if ( !buttonData ) { + buttonData = vars.container.button.data()[0] || vars.data.viz[0] + } + + vars.container.button + .data([buttonData]) + .id( vars.id.nesting ) + .depth(depth) + + } + + var hover = vars.hover.value === true ? vars.focus.value : false; + + vars.container.button + .draw({ + "update": vars.draw.update + }) + .focus("") + .font( vars.font ) + .format(vars.format) + .hover(hover) + .icon({ + "button": vars.icon.drop.value, + "select": vars.icon.drop.value, + "value": vars.icon.value + }) + .text( vars.text.value ) + .timing({ + "ui": vars.draw.timing + }) + .ui({ + "border": vars.ui.border, + "color": vars.ui.color, + "padding": vars.ui.padding.css + }) + .width(vars.width.value) + .draw() + + var button = vars.container.button.container(Object).ui + + vars.margin.top += button.node().offsetHeight || button.node().getBoundingClientRect().height + + button.on(events.click,function(){ + vars.self.open(!vars.open.value).draw() + }) + +} + +},{"../../../../client/pointer.coffee":40,"../../../../core/console/print.coffee":54,"../../../../util/copy.coffee":210,"../../../form.js":106}],148:[function(require,module,exports){ +var stringFormat = require("../../../../string/format.js"), + stringStrip = require("../../../../string/strip.js"); + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates and populates the dropdown list of items. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + if ( vars.data.url && !vars.data.loaded ) { + var loadingObject = {}; + loadingObject[vars.text.value || vars.id.value] = vars.format.value(vars.format.locale.value.ui.loading); + vars.data.filtered = [loadingObject]; + vars.data.changed = vars.data.lastFilter !== "loading"; + vars.data.lastFilter = "loading"; + } + else if (vars.open.value) { + + if (!vars.search.term) { + vars.data.filtered = vars.data.viz; + vars.data.changed = vars.data.lastFilter !== "viz"; + vars.data.lastFilter = "viz"; + if (vars.id.nesting.length > 1 && vars.depth.value < vars.id.nesting.length-1) { + vars.data.filtered = vars.data.filtered.filter(function(d){ + if ("endPoint" in d.d3plus && d.d3plus.endPoint === vars.depth.value) { + d.d3plus.icon = false; + } + return true; + }); + vars.data.changed = vars.data.lastFilter !== "depth"; + vars.data.lastFilter = "depth"; + } + } + else { + + var searchWords = stringStrip(vars.search.term).split("_"), + searchKeys = [vars.id.value, vars.text.value, vars.alt.value, vars.keywords.value ]; + + searchKeys = searchKeys.filter(function(t){ return t; }); + searchWords = searchWords.filter(function(t){ return t !== ""; }); + + var startMatches = [], + exactMatches = [], + softMatches = [], + searchData = []; + + vars.id.nesting.forEach(function(n){ + searchData = searchData.concat(vars.data.nested.all[n]); + }); + + searchData.forEach(function(d){ + + var match = false; + + searchKeys.forEach(function(key){ + + if ( !match && key in d && typeof d[key] === "string" ) { + + var text = d[key].toLowerCase(); + + if ( [vars.text.value,vars.id.value].indexOf(key) >= 0 && text.indexOf(vars.search.term) === 0 ) { + startMatches.push(d); + match = true; + } + else if ( text.indexOf(vars.search.term) >= 0 ) { + exactMatches.push(d); + match = true; + } + else { + + var texts = stringStrip(text).split("_"); + + for (var t in texts) { + + if ( !match ) { + + for (var s in searchWords) { + if (texts[t].indexOf(searchWords[s]) === 0) { + softMatches.push(d); + match = true; + break; + } + } + + } + else { + break; + } + + } + + } + } + + }); + + }); + + vars.data.filtered = d3.merge([ startMatches , exactMatches , softMatches ]); + + vars.data.filtered.forEach(function(d,i){ + d.d3plus_order = i; + }); + + vars.data.changed = true; + vars.data.lastFilter = "search"; + + if ( vars.data.filtered.length === 0 ) { + + var noData = {}, str = vars.format.value(vars.format.locale.value.ui.noResults); + noData[vars.text.value || vars.id.value] = stringFormat(str,"\""+vars.search.term+"\""); + vars.data.filtered = [ noData ]; + + } + + } + + } + else { + vars.data.filtered = []; + } + +}; + +},{"../../../../string/format.js":176,"../../../../string/strip.js":178}],149:[function(require,module,exports){ +module.exports = function(vars) { + if (vars.data.element.value) { + vars.data.element.value.on("focus." + vars.container.id, function() { + return vars.self.hover(true).draw(); + }); + vars.data.element.value.on("blur." + vars.container.id, function() { + var search; + if (vars.search.enabled) { + search = d3.event.relatedTarget !== vars.container.value.select('input').node(); + } else { + search = true; + } + if (search) { + return vars.self.open(false).hover(false).draw(); + } + }); + vars.data.element.value.on("change." + vars.container.id, function() { + return vars.self.focus(this.value).draw(); + }); + return vars.data.element.value.on("keydown.cancel_" + vars.container.id, function() { + if (d3.event.keyCode !== 9) { + return d3.event.preventDefault(); + } + }); + } +}; + + +},{}],150:[function(require,module,exports){ +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Calculates the height and orientation of the dropdown list, based on +// available screen space. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + var height = vars.height.secondary, + button = vars.container.button.container().node().getBoundingClientRect(), + available = window.innerHeight - button.bottom - vars.ui.border * 2 - + vars.ui.margin.top - vars.ui.margin.bottom - + vars.ui.padding.top - vars.ui.padding.bottom; + + if (available < button.height * 3) { + available = button.top-10; + vars.self.open({"flipped": true}); + } + // else { + // vars.self.open({"flipped": false}); + // } + + if (typeof height !== "number") { + height = available; + } + + if (height > vars.height.max) { + height = vars.height.max; + } + + vars.self.height({"secondary": height}); + +}; + +},{}],151:[function(require,module,exports){ +var active, copy, form, print; + +active = require("./active.js"); + +copy = require("../../../../util/copy.coffee"); + +form = require("../../../form.js"); + +print = require("../../../../core/console/print.coffee"); + +module.exports = function(vars) { + var deepest, large, order; + if (vars.open.value) { + if (vars.dev.value) { + print.time("updating list items"); + } + if (!("items" in vars.container)) { + vars.container.items = form().container(vars.container.list).type("button").ui({ + border: 0, + display: "block", + margin: 0 + }).width(false); + } + large = vars.draw.timing ? vars.data.large : 1; + order = copy(vars.order); + order.value = vars.search.term.length ? "d3plus_order" : vars.order.value; + deepest = vars.depth.value === vars.id.nesting.length - 1; + if (vars.focus.changed || vars.container.items.focus() === false) { + vars.container.items.focus(vars.focus.value, function(value) { + var change, data, depth, solo; + data = vars.data.filtered.filter(function(f) { + return f[vars.id.value] === value; + })[0]; + if (vars.depth.value < vars.id.nesting.length - 1 && vars.id.nesting[vars.depth.value + 1] in data) { + depth = vars.depth.value; + solo = vars.id.solo.value; + vars.history.states.push(function() { + return vars.self.depth(depth).id({ + solo: solo + }).draw(); + }); + vars.self.depth(vars.depth.value + 1).id({ + solo: [value] + }).draw(); + } else { + if (!vars.depth.changed) { + vars.self.open(false); + } + change = value !== vars.focus.value; + if (change && vars.active.value) { + change = active(vars, value); + } + if (change) { + vars.self.focus(value).draw(); + } + } + }); + } + vars.container.items.active(vars.active.value).data({ + large: large, + sort: vars.data.sort.value, + value: vars.data.filtered + }).draw({ + update: vars.draw.update + }).font(vars.font.secondary).format(vars.format).hover(vars.hover.value).id(vars.id.value).icon({ + button: (deepest ? false : vars.icon.next), + select: (deepest ? vars.icon.select : false), + value: vars.icon.value + }).order(order).text(vars.text.secondary.value || vars.text.value).timing({ + ui: vars.draw.timing + }).ui({ + color: { + primary: (vars.id.nesting.length === 1 ? vars.ui.color.primary.value : vars.ui.color.secondary.value), + secondary: vars.ui.color.secondary.value + }, + padding: vars.ui.padding.css + }).draw(); + if (vars.dev.value) { + print.timeEnd("updating list items"); + } + } +}; + + +},{"../../../../core/console/print.coffee":54,"../../../../util/copy.coffee":210,"../../../form.js":106,"./active.js":145}],152:[function(require,module,exports){ +module.exports = function(vars) { + return d3.select(window).on("keydown." + vars.container.id, function() { + var d, data, depth, hist, hover, i, index, j, key, len, matchKey, ref, solo; + key = d3.event.keyCode; + if (vars.open.value || vars.hover.value === true) { + matchKey = vars.hover.value === true ? "focus" : "hover"; + index = false; + ref = vars.data.filtered; + for (i = j = 0, len = ref.length; j < len; i = ++j) { + d = ref[i]; + if (d[vars.id.value] === vars[matchKey].value) { + index = i; + break; + } + } + if (key === 9 && vars.open.value && (!vars.search.enabled || (vars.search.enabled && !d3.event.shiftKey))) { + return vars.self.open(false).hover(false).draw(); + } else if ([38, 40].indexOf(key) >= 0) { + if (index === false) { + index = 0; + } else if (key === 38) { + if (vars.open.value) { + if (index <= 0) { + index = vars.data.filtered.length - 1; + } else { + index -= 1; + } + } + } else if (key === 40) { + if (vars.open.value) { + if (index >= vars.data.filtered.length - 1) { + index = 0; + } else { + index += 1; + } + } + } + if (typeof vars.hover.value !== "boolean") { + hover = vars.data.filtered[index][vars.id.value]; + } else { + hover = vars.focus.value; + } + return vars.self.hover(hover).open(true).draw(); + } else if (key === 13) { + if (typeof vars.hover.value !== "boolean") { + data = vars.data.filtered.filter(function(f) { + return f[vars.id.value] === vars.hover.value; + })[0]; + depth = vars.depth.value; + if (depth < vars.id.nesting.length - 1 && vars.id.nesting[depth + 1] in data) { + solo = vars.id.solo.value; + hist = function() { + return vars.self.depth(depth).id({ + solo: solo + }).draw(); + }; + vars.history.states.push(hist); + return vars.self.depth(vars.depth.value + 1).id({ + solo: [vars.hover.value] + }).draw(); + } else { + return vars.self.focus(vars.hover.value).hover(true).draw(); + } + } else { + return vars.self.hover(vars.focus.value).open(true).draw(); + } + } else if (key === 27) { + if (vars.open.value) { + return vars.self.open(false).hover(true).draw(); + } else if (vars.hover.value === true) { + return vars.self.hover(false).draw(); + } + } + } + }); +}; + + +},{}],153:[function(require,module,exports){ +var print = require("../../../../core/console/print.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates and populates the dropdown list of items. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + if ( vars.dev.value ) print.time("populating list") + + vars.container.list = vars.container.selector.selectAll("div.d3plus_drop_list") + .data(["list"]) + + vars.container.list.enter().append("div") + .attr("class","d3plus_drop_list") + .attr("id","d3plus_drop_list_"+vars.container.id) + .style("overflow-y","auto") + .style("overflow-x","hidden") + + if ( vars.dev.value ) print.timeEnd("populating list") + +} + +},{"../../../../core/console/print.coffee":54}],154:[function(require,module,exports){ +var print = require("../../../../core/console/print.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Calculates scroll position of list. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + if (vars.open.value) { + + if ( vars.dev.value ) print.time("calculating height") + + var hidden = false + if (vars.container.selector.style("display") == "none") { + var hidden = true + } + + if (hidden) vars.container.selector.style("display","block") + + var old_height = vars.container.selector.style("height"), + old_scroll = vars.container.selector.property("scrollTop"), + list_height = vars.container.list.style("max-height"), + list_scroll = vars.container.list.property("scrollTop") + + vars.container.selector.style("height","auto") + vars.container.list.style("max-height","200000px") + + vars.container.listHeight = parseFloat(vars.container.selector.style("height"),10) + + vars.container.list + .style("max-height",list_height) + .property("scrollTop",list_scroll) + + vars.container.selector + .style("height",old_height) + .property("scrollTop",old_scroll) + + var scrolling = false + if (vars.container.listHeight > vars.height.secondary) { + vars.container.listHeight = vars.height.secondary + scrolling = true + } + + if (hidden) vars.container.selector.style("display","none") + + if ( vars.dev.value ) print.timeEnd("calculating height") + + if (scrolling) { + + if ( vars.dev.value ) print.time("calculating scroll position") + + var options = vars.container.list.select("div").selectAll("div.d3plus_node") + var option = options[0][0] + var matchID = typeof vars.hover.value !== "boolean" ? vars.hover.value : vars.focus.value; + options.each(function(d,i){ + if (d[vars.id.value] === matchID) { + option = this + } + }) + + var hidden = false + if (vars.container.selector.style("display") === "none") { + hidden = true + vars.container.selector.style("display","block") + } + + var button_top = option.offsetTop, + button_height = option.offsetHeight || option.getBoundingClientRect().height, + list_top = vars.container.list.property("scrollTop") + + if (hidden) vars.container.selector.style("display","none") + + if ( hidden || vars.data.changed || vars.depth.changed ) { + + vars.container.listScroll = button_top + + } + else { + + vars.container.listScroll = list_top; + + if (button_top < list_top) { + vars.container.listScroll = button_top + } + else if (button_top+button_height > list_top+vars.height.secondary-vars.search.height) { + vars.container.listScroll = button_top - (vars.height.secondary-button_height-vars.search.height) + } + + } + + if ( vars.dev.value ) print.timeEnd("calculating scroll position") + + } + else { + vars.container.listScroll = 0 + } + + } + else { + vars.container.listScroll = vars.container.list.property("scrollTop") + vars.container.listHeight = 0 + } + +} + +},{"../../../../core/console/print.coffee":54}],155:[function(require,module,exports){ +var prefix = require("../../../../client/prefix.coffee"), + print = require("../../../../core/console/print.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates and styles the search box, if enabled. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + if ( vars.dev.value ) print.time("creating search") + + var data = require("./data.js") + , items = require("./items.coffee") + , update = require("./update.js") + + vars.container.search = vars.container.selector.selectAll("div.d3plus_drop_search") + .data(vars.search.enabled ? ["search"] : []) + + function searchStyle(elem) { + + elem + .style("padding",vars.ui.padding.css) + .style("display","block") + .style("background-color",d3.rgb(vars.ui.color.primary.value).darker(0.15).toString()) + + } + + function inputStyle(elem) { + + var width = vars.width.secondary - vars.ui.padding.left*2 - vars.ui.padding.right*2 + vars.ui.border*2 + + elem + .style("padding",vars.ui.padding.left/2+vars.ui.padding.right/2+"px") + .style("width",width+"px") + .style("border-width","0px") + .style("font-family",vars.font.secondary.family.value) + .style("font-size",vars.font.secondary.size+"px") + .style("font-weight",vars.font.secondary.weight) + .style("text-align",vars.font.secondary.align) + .style("outline","none") + .style(prefix()+"border-radius","0") + .attr("placeholder",vars.format.value(vars.format.locale.value.method.search)) + + } + + if (vars.draw.timing) { + + vars.container.search.transition().duration(vars.draw.timing) + .call(searchStyle) + + vars.container.search.select("input").transition().duration(vars.draw.timing) + .call(inputStyle) + + } + else { + + vars.container.search + .call(searchStyle) + + vars.container.search.select("input") + .call(inputStyle) + + } + + vars.container.search.enter() + .insert("div","#d3plus_drop_list_"+vars.container.id) + .attr("class","d3plus_drop_search") + .attr("id","d3plus_drop_search_"+vars.container.id) + .call(searchStyle) + .append("input") + .attr("id","d3plus_drop_input_"+vars.container.id) + .style("-webkit-appearance","none") + .call(inputStyle) + + vars.container.search.select("input").on("keyup."+vars.container.id,function(d){ + var term = this.value; + if (vars.search.term !== term) { + vars.search.term = term; + data(vars); + items(vars); + update(vars); + } + }); + + vars.container.search.exit().remove() + + var oldDisplay = vars.container.selector.style("display") + vars.container.selector.style("display", "block") + vars.search.height = vars.search.enabled ? vars.container.search.node().offsetHeight || + vars.container.search.node().getBoundingClientRect().height : 0; + vars.container.selector.style("display", oldDisplay) + + if ( vars.search.enabled ) { + vars.margin.title += vars.search.height + } + + if ( vars.dev.value ) print.timeEnd("creating search") + +} + +},{"../../../../client/prefix.coffee":41,"../../../../core/console/print.coffee":54,"./data.js":148,"./items.coffee":151,"./update.js":158}],156:[function(require,module,exports){ +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates and styles the div that holds the search box and item list. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + vars.container.selector = vars.container.ui + .selectAll("div.d3plus_drop_selector") + .data(["selector"]) + + vars.container.selector.enter().append("div") + .attr("class","d3plus_drop_selector") + .style("position","absolute") + .style("top","0px") + .style("z-index","-1") + .style("overflow","hidden") + + vars.container.selector + .style("padding",vars.ui.border+"px") + +} + +},{}],157:[function(require,module,exports){ +var events = require("../../../../client/pointer.coffee"), + lighter = require("../../../../color/lighter.coffee"), + print = require("../../../../core/console/print.coffee"), + textColor = require("../../../../color/text.coffee") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates and styles the title and back button. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + if ( vars.open.value ) { + + if ( vars.dev.value ) print.time("creating title and back button") + + var self = this + , enabled = vars.id.solo.value.length === 1 && vars.depth.value > 0 + , title = enabled + , focus = vars.container.button.data(Object).viz[0] + + title = true + for (var i = 0; i < vars.id.nesting.length; i++) { + var level = vars.id.nesting[i] + if ( level in focus && focus[level] === vars.focus.value ) { + title = false + break; + } + } + + vars.container.title = vars.container.selector.selectAll("div.d3plus_drop_title") + .data(enabled ? ["title"] : []) + + function boxStyle(elem) { + + elem + .style("padding",vars.ui.padding.css) + .style("display","block") + .style("background-color",vars.ui.color.secondary.value) + .style("font-family",vars.font.secondary.family.value) + .style("font-size",vars.font.secondary.size+"px") + .style("font-weight",vars.font.secondary.weight) + .style("text-align",vars.font.secondary.align) + .style("color",textColor(vars.ui.color.secondary.value)) + + } + + function backStyle(elem) { + + if ( !elem.empty() ) { + + var className = vars.icon.back.value.indexOf("fa-") === 0 ? " fa "+vars.icon.back.value : "" + className = "d3plus_drop_back" + className + + var text = vars.icon.back.value.indexOf("fa-") === 0 ? "" : vars.icon.back.value + + elem + .style("position","absolute") + .attr("class",className) + .style("top",vars.ui.padding.top+(vars.font.secondary.size/2)/2.5+"px") + .html(text) + + } + + } + + function titleStyle(elem) { + + var text = title ? vars.focus.value : vars.format.locale.value.ui.back + + elem + .text(vars.format.value(text)) + .style("padding","0px "+(vars.ui.padding.left+vars.ui.padding.right)+"px") + + } + + if (vars.draw.timing) { + + vars.container.title.transition().duration(vars.draw.timing) + .call(boxStyle) + + vars.container.title.select("div.d3plus_drop_title_text") + .transition().duration(vars.draw.timing) + .call(titleStyle) + + } + else { + + vars.container.title + .call(boxStyle) + + vars.container.title.select("div.d3plus_drop_title_text") + .call(titleStyle) + + } + + vars.container.title.select("span.d3plus_drop_back") + .call(backStyle) + + var enter = vars.container.title.enter() + .insert("div","#d3plus_drop_list_"+vars.container.id) + .attr("class","d3plus_drop_title") + .attr("id","d3plus_drop_title_"+vars.container.id) + .call(boxStyle) + + enter.append("span") + .attr("id","d3plus_drop_back_"+vars.container.id) + .attr("class","d3plus_drop_back") + .call(backStyle) + + enter.append("div") + .attr("id","d3plus_drop_title_text_"+vars.container.id) + .attr("class","d3plus_drop_title_text") + .call(titleStyle) + + vars.container.title + .on(events.over,function(d,i){ + + var color = lighter(vars.ui.color.secondary.value) + + d3.select(this).style("cursor","pointer") + .transition().duration(vars.timing.mouseevents) + .style("background-color",color) + .style("color",textColor(color)) + + }) + .on(events.out,function(d){ + + var color = vars.ui.color.secondary.value + + d3.select(this).style("cursor","auto") + .transition().duration(vars.timing.mouseevents) + .style("background-color",color) + .style("color",textColor(color)) + + }) + .on(events.click,function(d){ + vars.history.back() + }) + + vars.container.title.exit().remove() + + if ( enabled ) { + vars.margin.title += vars.container.title.node().offsetHeight || vars.container.title.node().getBoundingClientRect().height + } + + if ( vars.dev.value ) print.timeEnd("creating title and back button") + + } + +} + +},{"../../../../client/pointer.coffee":40,"../../../../color/lighter.coffee":47,"../../../../color/text.coffee":52,"../../../../core/console/print.coffee":54}],158:[function(require,module,exports){ +var items = require("./items.coffee"), + height = require("./height.js"), + print = require("../../../../core/console/print.coffee"), + scrolllist = require("./scroll.js"), + arrow = require("./arrow.js") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Redraws only the drop down list. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If the menu is open, set the container element's z-index to '9999'. + //---------------------------------------------------------------------------- + if ( vars.draw.timing ) { + + vars.container.ui.transition().duration(vars.draw.timing) + .each("start",function(){ + if (vars.open.value) { + d3.select(this).style("z-index",9999) + } + }) + .style("margin",vars.ui.margin.css) + .each("end",function(){ + if (!vars.open.value) { + d3.select(this).style("z-index","auto") + } + }) + + } + else { + + vars.container.ui + .style("margin",vars.ui.margin.css) + .style("z-index",function(){ + if (vars.open.value) { + return 9999 + } + else { + return "auto" + } + }) + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Update list items based on filtered data. + //---------------------------------------------------------------------------- + items( vars ) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Calculate the height and orientation of the dropdown list. + //---------------------------------------------------------------------------- + height( vars ) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Calculate scroll position of dropdown menu. + //---------------------------------------------------------------------------- + scrolllist( vars ) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Rotate the dropdown button arrow appropriately. + //---------------------------------------------------------------------------- + arrow( vars ) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Update List + //---------------------------------------------------------------------------- + if ( vars.dev.value ) print.time("drawing list") + + function position(elem) { + var flipped = vars.open.flipped.value + elem + .style("top",function(){ + return flipped ? "auto" : vars.margin.top-vars.ui.border+"px"; + }) + .style("bottom",function(){ + return flipped ? vars.margin.top+vars.ui.border+"px" : "auto"; + }); + } + + function update(elem) { + + elem + .style("left",function(){ + if (vars.font.align.value === "left") { + return vars.margin.left+"px"; + } + else if (vars.font.align.value === "center") { + return vars.margin.left-((vars.width.secondary-vars.width.value)/2)+"px"; + } + else { + return "auto"; + } + }) + .style("right",function(){ + return vars.font.align.value === "right" ? "0px" : "auto"; + }) + .style("height",vars.container.listHeight+"px") + .style("padding",vars.ui.border+"px") + .style("background-color",vars.ui.color.secondary.value) + .style("z-index",function(){ + return vars.open.value ? "9999" : "-1"; + }) + .style("width",(vars.width.secondary-(vars.ui.border*2))+"px") + .style("opacity",vars.open.value ? 1 : 0) + .call(position); + + } + + function finish(elem) { + + elem.style("display", vars.open.value ? null : "none") + .call(position); + + + if (vars.search.enabled && vars.open.value) { + vars.container.selector.select("div.d3plus_drop_search input").node().focus() + } + + } + + var max_height = vars.open.value ? vars.height.secondary - vars.margin.title: 0; + + if (!vars.draw.timing) { + + vars.container.selector.call(update).call(finish) + + vars.container.list + .style("width",vars.width.secondary-vars.ui.border*2+"px") + .style("max-height", max_height + "px") + .property("scrollTop",vars.container.listScroll); + + } + else { + vars.container.selector.transition().duration(vars.draw.timing) + .each("start",function(){ + d3.select(this) + .style("display",vars.open.value ? "block" : null) + }) + .call(update) + .each("end",function(){ + + d3.select(this).transition().duration(vars.draw.timing) + .call(finish) + + }) + + function scrollTopTween(scrollTop) { + return function() { + var i = d3.interpolateNumber(this.scrollTop, scrollTop); + return function(t) { this.scrollTop = i(t); }; + }; + } + + vars.container.list.transition().duration(vars.draw.timing) + .style("width",vars.width.secondary-vars.ui.border*2+"px") + .style("max-height",max_height+"px") + .tween("scroll",scrollTopTween(vars.container.listScroll)) + } + + if ( vars.dev.value ) print.timeEnd("drawing list") + +} + +},{"../../../../core/console/print.coffee":54,"./arrow.js":146,"./height.js":150,"./items.coffee":151,"./scroll.js":154}],159:[function(require,module,exports){ +var copy = require("../../../../util/copy.coffee"), + fontTester = require("../../../../core/font/tester.coffee"), + form = require("../../../form.js"), + print = require("../../../../core/console/print.coffee"), + validObject = require("../../../../object/validate.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// If no widths are defined, then this calculates the width needed to fit the +// longest entry in the list. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + var data = [], buffer = 0 + for ( var level in vars.data.nested.all ) { + var newData = vars.data.nested.all[level] + , key = validObject(vars.text.nesting) && level in vars.text.nesting + ? vars.text.nesting[level][0] : level + + if ( [vars.id.value,vars.text.value].indexOf(key) < 0 ) { + newData = copy(newData) + newData.forEach(function(d){ + d[vars.text.value || vars.id.value] = d[key] + }) + } + data = data.concat( newData ) + } + + function getWidth( type ) { + + var key = type === "primary" ? "value" : type + , icon = key === "value" ? vars.icon.drop.value + : vars.icon.select.value || vars.icon.drop.value + , text = key === "value" ? vars.text.value + : vars.text.secondary.value || vars.text.value + , font = key === "value" ? vars.font : vars.font.secondary + + if ( vars.dev.value ) print.time("calculating "+type+" width") + + var button = form() + .container( fontTester() ) + .data({ + "large": 9999, + "value": data + }) + .draw({ "update": false }) + .font( font ) + .format(vars.format) + .icon({ "button": icon, "value": vars.icon.value }) + .id(vars.id.value) + .timing({ + "ui": 0 + }) + .text( text || vars.id.value ) + .type( "button" ) + .ui({ + "border": type === "primary" ? vars.ui.border : 0, + "display": "inline-block", + "margin": 0, + "padding": vars.ui.padding.css + }) + .width(false) + .draw() + + var w = [] + button.selectAll("div.d3plus_node").each(function(o){ + w.push(this.offsetWidth + 1) + }).remove() + + var dropWidth = {} + dropWidth[key] = d3.max(w) + + vars.self.width( dropWidth ) + + if ( vars.dev.value ) print.timeEnd("calculating "+type+" width") + + } + + if ( typeof vars.width.value !== "number" ) { + + getWidth( "primary" ) + + } + + if ( typeof vars.width.secondary !== "number" ) { + + if ( !vars.text.secondary.value || vars.text.value === vars.text.secondary.value ) { + vars.self.width({"secondary": vars.width.value}) + } + else { + getWidth( "secondary" ) + } + + } + +} + +},{"../../../../core/console/print.coffee":54,"../../../../core/font/tester.coffee":70,"../../../../object/validate.coffee":175,"../../../../util/copy.coffee":210,"../../../form.js":106}],160:[function(require,module,exports){ +var child = require("../../../../util/child.coffee") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Recursive function that applies a click event to all parent windows that +// will close the dropdown if it is open. +//------------------------------------------------------------------------------ +var windowEvents = function ( vars , elem ) { + + if ( elem === undefined ) { + var elem = window + } + + d3.select(elem).on("click."+vars.container.id,function(){ + + var element = d3.event.target || d3.event.toElement + , parent = element.parentNode + + if ( parent && ["d3plus_node","d3plus_drop_title"].indexOf(parent.className) >= 0 ) { + element = parent.parentNode + } + + if (element && parent && !child(vars.container.ui, element) && (vars.open.value || vars.hover.value)) { + vars.self.open(false).hover(false).draw() + } + + }) + + try { + var same_origin = window.parent.location.host === window.location.host; + } + catch (e) { + var same_origin = false + } + + if (same_origin) { + if (elem.self !== window.top) { + windowEvents( vars , elem.parent ) + } + } + +} + +module.exports = windowEvents + +},{"../../../../util/child.coffee":208}],161:[function(require,module,exports){ +var form = require("../form.js") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates a set of Toggle Buttons +//------------------------------------------------------------------------------ +module.exports = function( vars ) { + + if ( !("buttons" in vars.container) ) { + + vars.container.buttons = form() + .container(vars.container.ui) + .type("button") + + } + + var dataLength = vars.data.viz.length + , buttonWidth = vars.width.value + ? vars.width.value/dataLength + : false + + var toggles = vars.container.ui.selectAll("div.d3plus_toggle") + .data(vars.data.viz,function(d){ + return d[vars.id.value]; + }) + + toggles.exit().remove(); + + toggles.enter().append("div") + .attr("class","d3plus_toggle") + .style("display","inline-block") + .style("vertical-align","top") + + toggles.order() + .each(function(d){ + + if (!("form" in d.d3plus)) { + d.d3plus.form = form().container(d3.select(this)) + } + + var id = vars.id.nesting.length > vars.depth.value ? vars.id.nesting[vars.depth.value+1] : vars.id.value + + if (d[id] instanceof Array) { + d.d3plus.form + .container({"id": vars.container.id+"_"+d[vars.id.value]}) + .data(d[id]) + .id(vars.id.nesting.slice(1)) + .type("drop") + } + else { + d.d3plus.form + .data([d]) + .id(vars.id.value) + .type("button") + } + + d.d3plus.form + .color(vars.color) + .focus(vars.focus.value,function(value){ + + if (value !== vars.focus.value) { + vars.self.focus(value).draw() + } + + }) + .hover(vars.hover.value) + .icon({ + "select": false, + "value": vars.icon.value + }) + .font(vars.font) + .format(vars.format) + .order(vars.order) + .text(vars.text.value) + .ui({ + "border": vars.ui.border, + "color": vars.ui.color, + "display": "inline-block", + "margin": 0, + "padding": vars.ui.padding.css + }) + .width(buttonWidth) + .draw() + + }) + + if (vars.data.element.value) { + vars.data.element.value + .on("focus."+vars.container.id, function(){ + vars.self.focus(this.value).hover(this.value).draw(); + }) + .on("blur."+vars.container.id, function(){ + vars.self.hover(false).draw(); + }) + } + +} + +},{"../form.js":106}],162:[function(require,module,exports){ +var intersectPoints, lineIntersection, pointInPoly, pointInSegmentBox, polyInsidePoly, rayIntersectsSegment, rotatePoint, rotatePoly, segmentsIntersect, simplify, squaredDist; + +simplify = require("simplify-js"); + +module.exports = function(poly, options) { + var aRatio, aRatios, angle, angleRad, angleStep, angles, area, aspectRatioStep, aspectRatios, bBox, boxHeight, boxWidth, centroid, events, height, i, insidePoly, j, k, l, left, len, len1, len2, len3, m, maxArea, maxAspectRatio, maxHeight, maxRect, maxWidth, maxx, maxy, minAspectRatio, minSqDistH, minSqDistW, minx, miny, modifOrigins, origOrigin, origin, origins, p, p1H, p1W, p2H, p2W, rectPoly, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, right, rndPoint, rndX, rndY, tempPoly, tolerance, width, widthStep, x0, y0; + if (poly.length < 3) { + return null; + } + events = []; + aspectRatioStep = 0.5; + angleStep = 5; + if (options == null) { + options = {}; + } + if (options.maxAspectRatio == null) { + options.maxAspectRatio = 15; + } + if (options.minWidth == null) { + options.minWidth = 0; + } + if (options.minHeight == null) { + options.minHeight = 0; + } + if (options.tolerance == null) { + options.tolerance = 0.02; + } + if (options.nTries == null) { + options.nTries = 20; + } + if (options.angle != null) { + if (options.angle instanceof Array) { + angles = options.angle; + } else if (typeof options.angle === 'number') { + angles = [options.angle]; + } else if (typeof options.angle === 'string' && !isNaN(options.angle)) { + angles = [Number(options.angle)]; + } + } + if (angles == null) { + angles = d3.range(-90, 90 + angleStep, angleStep); + } + if (options.aspectRatio != null) { + if (options.aspectRatio instanceof Array) { + aspectRatios = options.aspectRatio; + } else if (typeof options.aspectRatio === 'number') { + aspectRatios = [options.aspectRatio]; + } else if (typeof options.aspectRatio === 'string' && !isNaN(options.aspectRatio)) { + aspectRatios = [Number(options.aspectRatio)]; + } + } + if (options.origin != null) { + if (options.origin instanceof Array) { + if (options.origin[0] instanceof Array) { + origins = options.origin; + } else { + origins = [options.origin]; + } + } + } + area = Math.abs(d3.geom.polygon(poly).area()); + if (area === 0) { + return null; + } + ref = d3.extent(poly, function(d) { + return d[0]; + }), minx = ref[0], maxx = ref[1]; + ref1 = d3.extent(poly, function(d) { + return d[1]; + }), miny = ref1[0], maxy = ref1[1]; + tolerance = Math.min(maxx - minx, maxy - miny) * options.tolerance; + tempPoly = (function() { + var j, len, results; + results = []; + for (j = 0, len = poly.length; j < len; j++) { + p = poly[j]; + results.push({ + x: p[0], + y: p[1] + }); + } + return results; + })(); + if (tolerance > 0) { + tempPoly = simplify(tempPoly, tolerance); + poly = (function() { + var j, len, results; + results = []; + for (j = 0, len = tempPoly.length; j < len; j++) { + p = tempPoly[j]; + results.push([p.x, p.y]); + } + return results; + })(); + } + if (options.vdebug) { + events.push({ + type: 'simplify', + poly: poly + }); + } + ref2 = d3.extent(poly, function(d) { + return d[0]; + }), minx = ref2[0], maxx = ref2[1]; + ref3 = d3.extent(poly, function(d) { + return d[1]; + }), miny = ref3[0], maxy = ref3[1]; + bBox = [[minx, miny], [maxx, miny], [maxx, maxy], [minx, maxy]]; + ref4 = [maxx - minx, maxy - miny], boxWidth = ref4[0], boxHeight = ref4[1]; + widthStep = Math.min(boxWidth, boxHeight) / 50; + if (origins == null) { + origins = []; + centroid = d3.geom.polygon(poly).centroid(); + if (pointInPoly(centroid, poly)) { + origins.push(centroid); + } + while (origins.length < options.nTries) { + rndX = Math.random() * boxWidth + minx; + rndY = Math.random() * boxHeight + miny; + rndPoint = [rndX, rndY]; + if (pointInPoly(rndPoint, poly)) { + origins.push(rndPoint); + } + } + } + if (options.vdebug) { + events.push({ + type: 'origins', + points: origins + }); + } + maxArea = 0; + maxRect = null; + for (j = 0, len = angles.length; j < len; j++) { + angle = angles[j]; + angleRad = -angle * Math.PI / 180; + if (options.vdebug) { + events.push({ + type: 'angle', + angle: angle + }); + } + for (i = k = 0, len1 = origins.length; k < len1; i = ++k) { + origOrigin = origins[i]; + ref5 = intersectPoints(poly, origOrigin, angleRad), p1W = ref5[0], p2W = ref5[1]; + ref6 = intersectPoints(poly, origOrigin, angleRad + Math.PI / 2), p1H = ref6[0], p2H = ref6[1]; + modifOrigins = []; + if ((p1W != null) && (p2W != null)) { + modifOrigins.push([(p1W[0] + p2W[0]) / 2, (p1W[1] + p2W[1]) / 2]); + } + if ((p1H != null) && (p2H != null)) { + modifOrigins.push([(p1H[0] + p2H[0]) / 2, (p1H[1] + p2H[1]) / 2]); + } + if (options.vdebug) { + events.push({ + type: 'modifOrigin', + idx: i, + p1W: p1W, + p2W: p2W, + p1H: p1H, + p2H: p2H, + modifOrigins: modifOrigins + }); + } + for (l = 0, len2 = modifOrigins.length; l < len2; l++) { + origin = modifOrigins[l]; + if (options.vdebug) { + events.push({ + type: 'origin', + cx: origin[0], + cy: origin[1] + }); + } + ref7 = intersectPoints(poly, origin, angleRad), p1W = ref7[0], p2W = ref7[1]; + if (p1W === null || p2W === null) { + continue; + } + minSqDistW = Math.min(squaredDist(origin, p1W), squaredDist(origin, p2W)); + maxWidth = 2 * Math.sqrt(minSqDistW); + ref8 = intersectPoints(poly, origin, angleRad + Math.PI / 2), p1H = ref8[0], p2H = ref8[1]; + if (p1H === null || p2H === null) { + continue; + } + minSqDistH = Math.min(squaredDist(origin, p1H), squaredDist(origin, p2H)); + maxHeight = 2 * Math.sqrt(minSqDistH); + if (maxWidth * maxHeight < maxArea) { + continue; + } + if (aspectRatios != null) { + aRatios = aspectRatios; + } else { + minAspectRatio = Math.max(1, options.minWidth / maxHeight, maxArea / (maxHeight * maxHeight)); + maxAspectRatio = Math.min(options.maxAspectRatio, maxWidth / options.minHeight, (maxWidth * maxWidth) / maxArea); + aRatios = d3.range(minAspectRatio, maxAspectRatio + aspectRatioStep, aspectRatioStep); + } + for (m = 0, len3 = aRatios.length; m < len3; m++) { + aRatio = aRatios[m]; + left = Math.max(options.minWidth, Math.sqrt(maxArea * aRatio)); + right = Math.min(maxWidth, maxHeight * aRatio); + if (right * maxHeight < maxArea) { + continue; + } + if ((right - left) >= widthStep) { + if (options.vdebug) { + events.push({ + type: 'aRatio', + aRatio: aRatio + }); + } + } + while ((right - left) >= widthStep) { + width = (left + right) / 2; + height = width / aRatio; + x0 = origin[0], y0 = origin[1]; + rectPoly = [[x0 - width / 2, y0 - height / 2], [x0 + width / 2, y0 - height / 2], [x0 + width / 2, y0 + height / 2], [x0 - width / 2, y0 + height / 2]]; + rectPoly = rotatePoly(rectPoly, angleRad, origin); + if (polyInsidePoly(rectPoly, poly)) { + insidePoly = true; + maxArea = width * height; + maxRect = { + cx: x0, + cy: y0, + width: width, + height: height, + angle: angle + }; + left = width; + } else { + insidePoly = false; + right = width; + } + if (options.vdebug) { + events.push({ + type: 'rectangle', + cx: x0, + cy: y0, + width: width, + height: height, + areaFraction: (width * height) / area, + angle: angle, + insidePoly: insidePoly + }); + } + } + } + } + } + } + return [maxRect, maxArea, events]; +}; + +squaredDist = function(a, b) { + var deltax, deltay; + deltax = b[0] - a[0]; + deltay = b[1] - a[1]; + return deltax * deltax + deltay * deltay; +}; + +rayIntersectsSegment = function(p, p1, p2) { + var a, b, mAB, mAP, ref; + ref = p1[1] < p2[1] ? [p1, p2] : [p2, p1], a = ref[0], b = ref[1]; + if (p[1] === b[1] || p[1] === a[1]) { + p[1] += Number.MIN_VALUE; + } + if (p[1] > b[1] || p[1] < a[1]) { + return false; + } else if (p[0] > a[0] && p[0] > b[0]) { + return false; + } else if (p[0] < a[0] && p[0] < b[0]) { + return true; + } else { + mAB = (b[1] - a[1]) / (b[0] - a[0]); + mAP = (p[1] - a[1]) / (p[0] - a[0]); + return mAP > mAB; + } +}; + +pointInPoly = function(p, poly) { + var a, b, c, i, n; + i = -1; + n = poly.length; + b = poly[n - 1]; + c = 0; + while (++i < n) { + a = b; + b = poly[i]; + if (rayIntersectsSegment(p, a, b)) { + c++; + } + } + return c % 2 !== 0; +}; + +pointInSegmentBox = function(p, p1, q1) { + var eps, px, py; + eps = 1e-9; + px = p[0], py = p[1]; + if (px < Math.min(p1[0], q1[0]) - eps || px > Math.max(p1[0], q1[0]) + eps || py < Math.min(p1[1], q1[1]) - eps || py > Math.max(p1[1], q1[1]) + eps) { + return false; + } + return true; +}; + +lineIntersection = function(p1, q1, p2, q2) { + var cross1, cross2, denom, dx1, dx2, dy1, dy2, eps, px, py; + eps = 1e-9; + dx1 = p1[0] - q1[0]; + dy1 = p1[1] - q1[1]; + dx2 = p2[0] - q2[0]; + dy2 = p2[1] - q2[1]; + denom = dx1 * dy2 - dy1 * dx2; + if (Math.abs(denom) < eps) { + return null; + } + cross1 = p1[0] * q1[1] - p1[1] * q1[0]; + cross2 = p2[0] * q2[1] - p2[1] * q2[0]; + px = (cross1 * dx2 - cross2 * dx1) / denom; + py = (cross1 * dy2 - cross2 * dy1) / denom; + return [px, py]; +}; + +segmentsIntersect = function(p1, q1, p2, q2) { + var p; + p = lineIntersection(p1, q1, p2, q2); + if (p == null) { + return false; + } + return pointInSegmentBox(p, p1, q1) && pointInSegmentBox(p, p2, q2); +}; + +polyInsidePoly = function(polyA, polyB) { + var aA, aB, bA, bB, iA, iB, nA, nB; + iA = -1; + nA = polyA.length; + nB = polyB.length; + bA = polyA[nA - 1]; + while (++iA < nA) { + aA = bA; + bA = polyA[iA]; + iB = -1; + bB = polyB[nB - 1]; + while (++iB < nB) { + aB = bB; + bB = polyB[iB]; + if (segmentsIntersect(aA, bA, aB, bB)) { + return false; + } + } + } + return pointInPoly(polyA[0], polyB); +}; + +rotatePoint = function(p, alpha, origin) { + var cosAlpha, sinAlpha, xshifted, yshifted; + if (origin == null) { + origin = [0, 0]; + } + xshifted = p[0] - origin[0]; + yshifted = p[1] - origin[1]; + cosAlpha = Math.cos(alpha); + sinAlpha = Math.sin(alpha); + return [cosAlpha * xshifted - sinAlpha * yshifted + origin[0], sinAlpha * xshifted + cosAlpha * yshifted + origin[1]]; +}; + +rotatePoly = function(poly, alpha, origin) { + var j, len, point, results; + results = []; + for (j = 0, len = poly.length; j < len; j++) { + point = poly[j]; + results.push(rotatePoint(point, alpha, origin)); + } + return results; +}; + +intersectPoints = function(poly, origin, alpha) { + var a, b, closestPointLeft, closestPointRight, eps, i, idx, minSqDistLeft, minSqDistRight, n, p, shiftedOrigin, sqDist, x0, y0; + eps = 1e-9; + origin = [origin[0] + eps * Math.cos(alpha), origin[1] + eps * Math.sin(alpha)]; + x0 = origin[0], y0 = origin[1]; + shiftedOrigin = [x0 + Math.cos(alpha), y0 + Math.sin(alpha)]; + idx = 0; + if (Math.abs(shiftedOrigin[0] - x0) < eps) { + idx = 1; + } + i = -1; + n = poly.length; + b = poly[n - 1]; + minSqDistLeft = Number.MAX_VALUE; + minSqDistRight = Number.MAX_VALUE; + closestPointLeft = null; + closestPointRight = null; + while (++i < n) { + a = b; + b = poly[i]; + p = lineIntersection(origin, shiftedOrigin, a, b); + if ((p != null) && pointInSegmentBox(p, a, b)) { + sqDist = squaredDist(origin, p); + if (p[idx] < origin[idx]) { + if (sqDist < minSqDistLeft) { + minSqDistLeft = sqDist; + closestPointLeft = p; + } + } else if (p[idx] > origin[idx]) { + if (sqDist < minSqDistRight) { + minSqDistRight = sqDist; + closestPointRight = p; + } + } + } + } + return [closestPointLeft, closestPointRight]; +}; + + +},{"simplify-js":9}],163:[function(require,module,exports){ +module.exports = function(radians, distance, shape) { + var adjacentLegLength, coords, diagonal, oppositeLegLength; + coords = { + x: 0, + y: 0 + }; + if (radians < 0) { + radians = Math.PI * 2 + radians; + } + if (shape === "square") { + diagonal = 45 * (Math.PI / 180); + if (radians <= Math.PI) { + if (radians < (Math.PI / 2)) { + if (radians < diagonal) { + coords.x += distance; + oppositeLegLength = Math.tan(radians) * distance; + coords.y += oppositeLegLength; + } else { + coords.y += distance; + adjacentLegLength = distance / Math.tan(radians); + coords.x += adjacentLegLength; + } + } else { + if (radians < (Math.PI - diagonal)) { + coords.y += distance; + adjacentLegLength = distance / Math.tan(Math.PI - radians); + coords.x -= adjacentLegLength; + } else { + coords.x -= distance; + oppositeLegLength = Math.tan(Math.PI - radians) * distance; + coords.y += oppositeLegLength; + } + } + } else { + if (radians < (3 * Math.PI / 2)) { + if (radians < (diagonal + Math.PI)) { + coords.x -= distance; + oppositeLegLength = Math.tan(radians - Math.PI) * distance; + coords.y -= oppositeLegLength; + } else { + coords.y -= distance; + adjacentLegLength = distance / Math.tan(radians - Math.PI); + coords.x -= adjacentLegLength; + } + } else { + if (radians < (2 * Math.PI - diagonal)) { + coords.y -= distance; + adjacentLegLength = distance / Math.tan(2 * Math.PI - radians); + coords.x += adjacentLegLength; + } else { + coords.x += distance; + oppositeLegLength = Math.tan(2 * Math.PI - radians) * distance; + coords.y -= oppositeLegLength; + } + } + } + } else { + coords.x += distance * Math.cos(radians); + coords.y += distance * Math.sin(radians); + } + return coords; +}; + + +},{}],164:[function(require,module,exports){ +var offset; + +offset = require("../geom/offset.coffee"); + +module.exports = function(path) { + var angle, i, j, last, len, length, o, obtuse, p, poly, prev, radius, segments, start, step, width; + if (!path) { + return []; + } + path = path.slice(1).slice(0, -1).split(/L|A/); + poly = []; + for (j = 0, len = path.length; j < len; j++) { + p = path[j]; + p = p.split(" "); + if (p.length === 1) { + poly.push(p[0].split(",").map(function(d) { + return parseFloat(d); + })); + } else { + prev = poly[poly.length - 1]; + last = p.pop().split(",").map(function(d) { + return parseFloat(d); + }); + radius = parseFloat(p.shift().split(",")[0]); + width = Math.sqrt(Math.pow(last[0] - prev[0], 2) + Math.pow(last[1] - prev[1], 2)); + angle = Math.acos((radius * radius + radius * radius - width * width) / (2 * radius * radius)); + obtuse = p[1].split(",")[0] === "1"; + if (obtuse) { + angle = Math.PI * 2 - angle; + } + length = angle / (Math.PI * 2) * (radius * Math.PI * 2); + segments = length / 5; + start = Math.atan2(-prev[1], -prev[0]) - Math.PI; + step = angle / segments; + i = step; + while (i < angle) { + o = offset(start + i, radius); + poly.push([o.x, o.y]); + i += step; + } + poly.push(last); + } + } + return poly; +}; + + +},{"../geom/offset.coffee":163}],165:[function(require,module,exports){ + +/** + * @class d3plus + */ +var d3plus, message, stylesheet; + +d3plus = {}; + + +/** + * The current version of **D3plus** you are using. Returns a string in + * [semantic versioning](http://semver.org/) format. + * @property d3plus.version + * @for d3plus + * @type String + * @static + */ + +d3plus.version = "1.9.8 - Cornflower"; + + +/** + * The URL for the repo, used internally for certain error messages. + * @property d3plus.repo + * @for d3plus + * @type String + * @static + */ + +d3plus.repo = "https://github.com/alexandersimoes/d3plus/"; + + +/** + * Utilities related to modifying arrays. + * @class d3plus.array + * @for d3plus + * @static + */ + +d3plus.array = { + comparator: require("./array/comparator.coffee"), + contains: require("./array/contains.coffee"), + sort: require("./array/sort.coffee"), + update: require("./array/update.coffee") +}; + + +/** + * Utilities related to the client's browser. + * @class d3plus.client + * @for d3plus + * @static + */ + +d3plus.client = { + css: require("./client/css.coffee"), + ie: require("./client/ie.js"), + pointer: require("./client/pointer.coffee"), + prefix: require("./client/prefix.coffee"), + rtl: require("./client/rtl.coffee"), + scroll: require("./client/scroll.js"), + scrollbar: require("./client/scrollbar.coffee"), + touch: require("./client/touch.coffee") +}; + + +/** + * Utilities related to color manipulation. + * @class d3plus.color + * @for d3plus + * @static + */ + +d3plus.color = { + legible: require("./color/legible.coffee"), + lighter: require("./color/lighter.coffee"), + mix: require("./color/mix.coffee"), + random: require("./color/random.coffee"), + scale: require("./color/scale.coffee"), + sort: require("./color/sort.coffee"), + text: require("./color/text.coffee"), + validate: require("./color/validate.coffee") +}; + + +/** + * Utilities related to manipulating data. + * @class d3plus.data + * @for d3plus + * @static + */ + +d3plus.data = { + bestRegress: require("./data/bestRegress.coffee"), + lof: require("./data/lof.coffee"), + mad: require("./data/mad.coffee") +}; + + +/** + * Utilities related to fonts. + * @class d3plus.font + * @for d3plus + * @static + */ + +d3plus.font = { + sizes: require("./font/sizes.coffee"), + validate: require("./font/validate.coffee") +}; + + +/** + * D3plus Forms + * @class d3plus.form + * @for d3plus + */ + +d3plus.form = require("./form/form.js"); + + +/** + * Utilities related to geometric algorithms. + * @class d3plus.geom + * @for d3plus + * @static + */ + +d3plus.geom = { + largestRect: require("./geom/largestRect.coffee"), + offset: require("./geom/offset.coffee"), + path2poly: require("./geom/path2poly.coffee") +}; + + +/** + * Utilities related to network graphs. + * @class d3plus.network + * @for d3plus + * @static + */ + +d3plus.network = { + cluster: require("./network/cluster.coffee"), + distance: require("./network/distance.coffee"), + normalize: require("./network/normalize.coffee"), + shortestPath: require("./network/shortestPath.coffee"), + smallestGap: require("./network/smallestGap.coffee"), + subgraph: require("./network/subgraph.coffee") +}; + + +/** + * Utilities that process numbers. + * @class d3plus.number + * @for d3plus + * @static + */ + +d3plus.number = { + format: require("./number/format.coffee") +}; + + +/** + * D3plus features a set of methods that relate to various object properties. These methods may be used outside of the normal constraints of the visualizations. + * @class d3plus.object + * @for d3plus + * @static + */ + +d3plus.object = { + merge: require("./object/merge.coffee"), + validate: require("./object/validate.coffee") +}; + + +/** + * Utilities that process strings. + * @class d3plus.string + * @for d3plus + * @static + */ + +d3plus.string = { + format: require("./string/format.js"), + list: require("./string/list.coffee"), + strip: require("./string/strip.js"), + title: require("./string/title.coffee") +}; + + +/** + * D3plus SVG Textwrapping + * @class d3plus.textwrap + * @for d3plus + */ + +d3plus.textwrap = require("./textwrap/textwrap.coffee"); + + +/** + * D3plus Tooltips + * @class d3plus.tooltip + * @for d3plus + */ + +d3plus.tooltip = { + create: require("./tooltip/create.js"), + move: require("./tooltip/move.coffee"), + remove: require("./tooltip/remove.coffee") +}; + + +/** + * D3plus features Utilities that can be used to help with some common javascript processes. + * @class d3plus.util + * @for d3plus + * @static + */ + +d3plus.util = { + buckets: require("./util/buckets.coffee"), + child: require("./util/child.coffee"), + closest: require("./util/closest.coffee"), + copy: require("./util/copy.coffee"), + d3selection: require("./util/d3selection.coffee"), + dataurl: require("./util/dataURL.coffee"), + uniques: require("./util/uniques.coffee") +}; + + +/** + * D3plus Visualizations + * @class d3plus.viz + * @for d3plus + */ + +d3plus.viz = require("./viz/viz.coffee"); + +stylesheet = require("./client/css.coffee"); + +message = require("./core/console/print.coffee"); + +if (stylesheet("d3plus.css")) { + message.warning("d3plus.css has been deprecated, you do not need to load this file.", d3plus.repo + "releases/tag/v1.4.0"); +} + +if (typeof window !== "undefined") { + window.d3plus = d3plus; +} + +module.exports = d3plus; + + +},{"./array/comparator.coffee":34,"./array/contains.coffee":35,"./array/sort.coffee":36,"./array/update.coffee":37,"./client/css.coffee":38,"./client/ie.js":39,"./client/pointer.coffee":40,"./client/prefix.coffee":41,"./client/rtl.coffee":42,"./client/scroll.js":43,"./client/scrollbar.coffee":44,"./client/touch.coffee":45,"./color/legible.coffee":46,"./color/lighter.coffee":47,"./color/mix.coffee":48,"./color/random.coffee":49,"./color/scale.coffee":50,"./color/sort.coffee":51,"./color/text.coffee":52,"./color/validate.coffee":53,"./core/console/print.coffee":54,"./data/bestRegress.coffee":101,"./data/lof.coffee":102,"./data/mad.coffee":103,"./font/sizes.coffee":104,"./font/validate.coffee":105,"./form/form.js":106,"./geom/largestRect.coffee":162,"./geom/offset.coffee":163,"./geom/path2poly.coffee":164,"./network/cluster.coffee":167,"./network/distance.coffee":168,"./network/normalize.coffee":169,"./network/shortestPath.coffee":170,"./network/smallestGap.coffee":171,"./network/subgraph.coffee":172,"./number/format.coffee":173,"./object/merge.coffee":174,"./object/validate.coffee":175,"./string/format.js":176,"./string/list.coffee":177,"./string/strip.js":178,"./string/title.coffee":179,"./textwrap/textwrap.coffee":203,"./tooltip/create.js":204,"./tooltip/move.coffee":205,"./tooltip/remove.coffee":206,"./util/buckets.coffee":207,"./util/child.coffee":208,"./util/closest.coffee":209,"./util/copy.coffee":210,"./util/d3selection.coffee":211,"./util/dataURL.coffee":212,"./util/uniques.coffee":213,"./viz/viz.coffee":336}],166:[function(require,module,exports){ +window.d3 = require("d3"); + +window.topojson = require("topojson"); + + +},{"d3":3,"topojson":33}],167:[function(require,module,exports){ +var normalize; + +normalize = require("./normalize.coffee"); + +module.exports = function(edges, options) { + var Q, a, b, cid, commSize, commSizes, communities, community, deltaQ, distance, edge, endpoint, events, i, id, iter, j, k, len, len1, linksMap, m, maxa, maxb, node, nodeid, nodes, nodesMap, ref, ref1, result, startpoint; + events = []; + if (options == null) { + options = {}; + } + if ((options.nodes == null) || typeof options.nodes !== 'object') { + ref = normalize(edges, options), edges = ref[0], options = ref[1]; + if (options === null) { + return null; + } + } + distance = options.distance, nodeid = options.nodeid, startpoint = options.startpoint, endpoint = options.endpoint, nodes = options.nodes; + nodesMap = {}; + for (id in nodes) { + nodesMap[id] = { + node: nodes[id].node, + degree: 0 + }; + } + m = 0; + linksMap = {}; + for (i = 0, len = edges.length; i < len; i++) { + edge = edges[i]; + a = nodeid(startpoint(edge)); + b = nodeid(endpoint(edge)); + if (!(a in linksMap)) { + linksMap[a] = {}; + } + if (!(b in linksMap)) { + linksMap[b] = {}; + } + if (!(b in linksMap[a])) { + linksMap[a][b] = 0; + linksMap[b][a] = 0; + m++; + nodesMap[a].degree += 1; + nodesMap[b].degree += 1; + } + } + communities = {}; + Q = 0; + for (id in nodesMap) { + node = nodesMap[id]; + communities[id] = { + score: node.degree / (2.0 * m), + nodes: [id] + }; + } + for (a in linksMap) { + for (b in linksMap[a]) { + linksMap[a][b] = 1.0 / (2 * m) - (nodesMap[a].degree * nodesMap[b].degree) / (4.0 * m * m); + } + } + iter = 0; + while (iter < 1000) { + deltaQ = -1; + maxa = void 0; + maxb = void 0; + for (a in linksMap) { + for (b in linksMap[a]) { + if (linksMap[a][b] > deltaQ) { + deltaQ = linksMap[a][b]; + maxa = a; + maxb = b; + } + } + } + if (deltaQ < 0) { + break; + } + for (k in linksMap[maxa]) { + if (k !== maxb) { + if (k in linksMap[maxb]) { + linksMap[maxb][k] += linksMap[maxa][k]; + } else { + linksMap[maxb][k] = linksMap[maxa][k] - 2 * communities[maxb].score * communities[k].score; + } + linksMap[k][maxb] = linksMap[maxb][k]; + } + delete linksMap[k][maxa]; + } + for (k in linksMap[maxb]) { + if (!(k in linksMap[maxa]) && k !== maxb) { + linksMap[maxb][k] -= 2 * communities[maxa].score * communities[k].score; + linksMap[k][maxb] = linksMap[maxb][k]; + } + } + ref1 = communities[maxa].nodes; + for (j = 0, len1 = ref1.length; j < len1; j++) { + node = ref1[j]; + communities[maxb].nodes.push(node); + } + communities[maxb].score += communities[maxa].score; + if (options.vdebug) { + events.push({ + type: 'merge', + father: maxb, + child: maxa, + nodes: communities[maxb].nodes + }); + } + delete communities[maxa]; + delete linksMap[maxa]; + Q += deltaQ; + iter++; + } + commSizes = (function() { + var results; + results = []; + for (cid in communities) { + community = communities[cid]; + results.push([cid, community.nodes.length]); + } + return results; + })(); + commSizes.sort(function(a, b) { + return b[1] - a[1]; + }); + result = (function() { + var l, len2, results; + results = []; + for (l = 0, len2 = commSizes.length; l < len2; l++) { + commSize = commSizes[l]; + results.push(communities[commSize[0]].nodes); + } + return results; + })(); + return [result, events]; +}; + + +},{"./normalize.coffee":169}],168:[function(require,module,exports){ +module.exports = function(n1, n2) { + var xx, yy; + if (!(n1 instanceof Array)) { + n1 = [n1.x, n1.y]; + } + if (!(n2 instanceof Array)) { + n2 = [n2.x, n2.y]; + } + xx = Math.abs(n1[0] - n2[0]); + yy = Math.abs(n1[1] - n2[1]); + return Math.sqrt((xx * xx) + (yy * yy)); +}; + + +},{}],169:[function(require,module,exports){ +var print; + +print = require("../core/console/print.coffee"); + +module.exports = function(edges, options) { + var K, a, b, directed, distance, edge, edge2distance, endpoint, errormsg, i, id, id1, idA, idB, j, k, l, len, len1, len2, node, nodeA, nodeB, nodeid, nodes, ref, ref1, source, startpoint, target, vdebug; + source = options.source, target = options.target, directed = options.directed, distance = options.distance, nodeid = options.nodeid, startpoint = options.startpoint, endpoint = options.endpoint, K = options.K, vdebug = options.vdebug; + if (!directed) { + directed = false; + } + if (K == null) { + K = 1; + } + if (nodeid == null) { + nodeid = function(node) { + return node; + }; + } else if (typeof nodeid === 'string') { + nodeid = (function(nodeid) { + return function(node) { + return node[nodeid]; + }; + })(nodeid); + } + if ((source != null) && typeof source === 'object') { + source = nodeid(source); + } + if ((target != null) && typeof target === 'object') { + target = nodeid(target); + } + if (startpoint == null) { + startpoint = function(edge) { + return edge.source; + }; + } else if (typeof startpoint === 'string') { + startpoint = (function(startpoint) { + return function(edge) { + return edge[startpoint]; + }; + })(startpoint); + } + if (endpoint == null) { + endpoint = function(edge) { + return edge.target; + }; + } else if (typeof endpoint === 'string') { + endpoint = (function(endpoint) { + return function(edge) { + return edge[endpoint]; + }; + })(endpoint); + } + if (distance == null) { + distance = function(edge) { + return 1; + }; + } else if (typeof distance === 'number') { + distance = (function(distance) { + return function(edge) { + return distance; + }; + })(distance); + } else if (typeof distance === 'string') { + distance = (function(distance) { + return function(edge) { + return edge[distance]; + }; + })(distance); + } else if (distance instanceof Array) { + edge2distance = {}; + for (i = j = 0, len = edges.length; j < len; i = ++j) { + edge = edges[i]; + a = nodeid(startpoint(edge)); + b = nodeid(endpoint(edge)); + edge2distance[a + '_' + b] = distance[i]; + } + distance = function(edge) { + a = nodeid(startpoint(edge)); + b = nodeid(endpoint(edge)); + return edge2distance[a + '_' + b]; + }; + } + nodes = {}; + for (k = 0, len1 = edges.length; k < len1; k++) { + edge = edges[k]; + nodeA = startpoint(edge); + nodeB = endpoint(edge); + idA = nodeid(nodeA); + idB = nodeid(nodeB); + ref = [nodeA, nodeB]; + for (l = 0, len2 = ref.length; l < len2; l++) { + node = ref[l]; + id = nodeid(node); + if (!(id in nodes)) { + nodes[id] = { + node: node, + outedges: [] + }; + } + } + nodes[idA].outedges.push(edge); + if (!directed) { + nodes[idB].outedges.push(edge); + } + } + errormsg = null; + if (edges.length === 0) { + errormsg = 'The length of edges is 0'; + } else if (K < 0) { + errormsg = 'K can not have negative value'; + } else if (distance(edges[0]) == null) { + errormsg = 'Check the distance function/attribute'; + } else if (startpoint(edges[0]) == null) { + errormsg = 'Check the startpoint function/attribute'; + } else if (endpoint(edges[0]) == null) { + errormsg = 'Check the endpoint function/attribute'; + } else { + id1 = nodeid(startpoint(edges[0])); + if ((id1 == null) || ((ref1 = typeof id1) !== 'string' && ref1 !== 'number')) { + errormsg = 'Check the nodeid function/attribute'; + } else if ((source != null) && !(source in nodes)) { + errormsg = 'The source is not in the graph'; + } else if ((target != null) && !(target in nodes)) { + errormsg = 'The target is not in the graph'; + } + } + if (errormsg != null) { + print.error(errormsg); + return null; + } + return [ + edges, { + source: source, + target: target, + directed: directed, + distance: distance, + nodeid: nodeid, + startpoint: startpoint, + endpoint: endpoint, + K: K, + nodes: nodes, + vdebug: vdebug + } + ]; +}; + + +},{"../core/console/print.coffee":54}],170:[function(require,module,exports){ +var Heap, normalize; + +Heap = require('heap'); + +normalize = require("./normalize.coffee"); + +module.exports = function(edges, source, options) { + var K, a, alt, b, directed, distance, edge, endpoint, getPath, heap, i, id, j, len, len1, maxsize, node, nodeid, nodes, path, ref, ref1, ref2, res, result, startpoint, target, u, visited; + if (options == null) { + options = {}; + } + options.source = source; + if ((options.nodes == null) || typeof options.nodes !== 'object') { + ref = normalize(edges, options), edges = ref[0], options = ref[1]; + if (options === null) { + return null; + } + } + source = options.source, target = options.target, directed = options.directed, distance = options.distance, nodeid = options.nodeid, startpoint = options.startpoint, endpoint = options.endpoint, K = options.K, nodes = options.nodes; + for (id in nodes) { + node = nodes[id]; + node.count = 0; + } + heap = new Heap(function(a, b) { + return a.distance - b.distance; + }); + visited = {}; + if (target == null) { + visited[source] = true; + } + heap.push({ + edge: null, + target: source, + distance: 0 + }); + maxsize = 0; + result = []; + while (!heap.empty()) { + maxsize = Math.max(maxsize, heap.size()); + path = heap.pop(); + u = path.target; + nodes[u].count++; + if (target == null) { + result.push(path); + } else if (u === target) { + result.push(path); + } + if (result.length === K) { + break; + } + if (nodes[u].count <= K) { + ref1 = nodes[u].outedges; + for (i = 0, len = ref1.length; i < len; i++) { + edge = ref1[i]; + a = nodeid(startpoint(edge)); + b = nodeid(endpoint(edge)); + if (!directed && b === u) { + ref2 = [b, a], a = ref2[0], b = ref2[1]; + } + if (target == null) { + if (visited[b]) { + continue; + } + visited[b] = true; + } + alt = path.distance + distance(edge); + heap.push({ + edge: edge, + previous: path, + target: b, + distance: alt + }); + } + } + } + getPath = function(path) { + edges = []; + while (path.edge != null) { + edges.push(path.edge); + path = path.previous; + } + return edges.reverse(); + }; + for (j = 0, len1 = result.length; j < len1; j++) { + res = result[j]; + if (target != null) { + delete res.target; + res.edges = getPath(res); + } + delete res.edge; + delete res.previous; + } + return result; +}; + + +},{"./normalize.coffee":169,"heap":4}],171:[function(require,module,exports){ +var distance; + +distance = require("./distance.coffee"); + +module.exports = function(arr, opts) { + var distances, quad; + if (!opts) { + opts = {}; + } + distances = []; + quad = d3.geom.quadtree().x(function(d) { + if (opts.accessor) { + return opts.accessor(d)[0]; + } else { + return d[0]; + } + }).y(function(d) { + if (opts.accessor) { + return opts.accessor(d)[1]; + } else { + return d[1]; + } + }); + quad(arr).visit(function(node) { + var i, j, len, len1, n1, n2, ref, ref1; + if (!node.leaf) { + ref = node.nodes; + for (i = 0, len = ref.length; i < len; i++) { + n1 = ref[i]; + if (n1 && n1.point) { + if (opts.origin) { + distances.push(distance(n1, opts)); + } else { + ref1 = node.nodes; + for (j = 0, len1 = ref1.length; j < len1; j++) { + n2 = ref1[j]; + if (n2 && n2.point && n2.point !== n1.point) { + distances.push(distance(n1, n2)); + } + } + } + } + } + } + return false; + }); + if (opts.all) { + return distances.sort(function(aa, bb) { + return aa - bb; + }); + } else { + return d3.min(distances); + } +}; + + +},{"./distance.coffee":168}],172:[function(require,module,exports){ +var normalize; + +normalize = require("./normalize.coffee"); + +module.exports = function(edges, source, options) { + var K, dfs, directed, distance, edge, endpoint, id, nodeid, nodes, ref, startpoint, visited; + if (options == null) { + options = {}; + } + options.source = source; + if ((options.nodes == null) || typeof options.nodes !== 'object') { + ref = normalize(edges, options), edges = ref[0], options = ref[1]; + if (options === null) { + return null; + } + } + source = options.source, directed = options.directed, distance = options.distance, nodeid = options.nodeid, startpoint = options.startpoint, endpoint = options.endpoint, K = options.K, nodes = options.nodes; + visited = {}; + visited[source] = true; + dfs = function(origin, curr_distance) { + var a, b, edge, i, len, new_distance, ref1, ref2, results; + ref1 = nodes[origin].outedges; + results = []; + for (i = 0, len = ref1.length; i < len; i++) { + edge = ref1[i]; + a = nodeid(startpoint(edge)); + b = nodeid(endpoint(edge)); + if (!directed && b === origin) { + ref2 = [b, a], a = ref2[0], b = ref2[1]; + } + if (!(b in visited)) { + new_distance = curr_distance + distance(edge); + if (new_distance <= K) { + visited[b] = true; + results.push(dfs(b, new_distance)); + } else { + results.push(void 0); + } + } else { + results.push(void 0); + } + } + return results; + }; + dfs(source, 0); + return { + nodes: (function() { + var results; + results = []; + for (id in visited) { + results.push(nodes[id].node); + } + return results; + })(), + edges: (function() { + var i, len, results; + results = []; + for (i = 0, len = edges.length; i < len; i++) { + edge = edges[i]; + if (nodeid(startpoint(edge)) in visited && nodeid(endpoint(edge)) in visited) { + results.push(edge); + } + } + return results; + })() + }; +}; + + +},{"./normalize.coffee":169}],173:[function(require,module,exports){ +var defaultLocale; + +defaultLocale = require("../core/locale/languages/en_US.coffee"); + +module.exports = function(number, opts) { + var affixes, format, key, labels, length, locale, ret, sigs, symbol, time, vars, zeros; + if (number === void 0 || number === null || number === false) { + return ""; + } + if (!opts) { + opts = {}; + } + if ("locale" in opts) { + locale = opts.locale; + } else { + locale = defaultLocale; + } + time = locale.time.slice(); + format = d3.locale(locale.format); + if (!opts) { + opts = {}; + } + vars = opts.vars || {}; + key = opts.key; + labels = "labels" in opts ? opts.labels : true; + length = number.toString().split(".")[0].length; + if (vars.time && vars.time.value) { + time.push(vars.time.value); + } + if (typeof key === "string" && time.indexOf(key.toLowerCase()) >= 0) { + ret = number; + } else if (key === "share") { + if (number === 0) { + ret = 0; + } else if (number >= 100) { + ret = format.numberFormat(",f")(number); + } else if (number > 99) { + ret = format.numberFormat(".3g")(number); + } else { + ret = format.numberFormat(".2g")(number); + } + ret += "%"; + } else if (number < 10 && number > -10) { + length = number.toString().split("."); + sigs = 1; + if (length.length > 1) { + sigs = d3.min([parseFloat(length[1]).toString().length, 2]); + if (!((-1 < number && number < 1))) { + zeros = length[1].length - parseFloat(length[1]).toString().length; + sigs += 1 + zeros; + } + } + ret = format.numberFormat("." + sigs + "g")(number); + } else if (length > 3) { + symbol = d3.formatPrefix(number).symbol; + symbol = symbol.replace("G", "B"); + number = d3.formatPrefix(number).scale(number); + number = format.numberFormat(".3g")(number); + number = number.replace(locale.format.decimal, "."); + number = parseFloat(number) + ""; + number = number.replace(".", locale.format.decimal); + ret = number + symbol; + } else if (length === 3) { + ret = format.numberFormat(",f")(number); + } else if (number === 0) { + ret = 0; + } else { + if (number === parseInt(number, 10)) { + ret = format.numberFormat(".2")(number); + } else { + ret = format.numberFormat(".3g")(number); + } + } + if (ret.length > 2 && "" + ret.indexOf(".0") === ret.length - 2) { + ret = ret.slice(0, ret.length - 2); + } + if (labels && key && "format" in vars && key in vars.format.affixes.value) { + affixes = vars.format.affixes.value[key]; + return affixes[0] + ret + affixes[1]; + } else { + return ret; + } +}; + + +},{"../core/locale/languages/en_US.coffee":72}],174:[function(require,module,exports){ +var d3selection, validate; + +d3selection = require("../util/d3selection.coffee"); + +validate = require("./validate.coffee"); + + +/** + * Given any two objects, this method will merge the two objects together, returning a new third object. The values of the second object always overwrite the first. + * @method d3plus.object.merge + * @for d3plus.object + * @param obj1 {Object} The primary object. + * @param obj2 {Object} The secondary object to merge into the first. + * @return {Object} + */ + +module.exports = function(obj1, obj2) { + var copyObject, obj3; + copyObject = function(obj, ret, shallow) { + var k, results, v; + results = []; + for (k in obj) { + v = obj[k]; + if (typeof v !== "undefined") { + if (!shallow && validate(v)) { + if (typeof ret[k] !== "object") { + ret[k] = {}; + } + results.push(copyObject(v, ret[k], k.indexOf("d3plus") === 0)); + } else if (!d3selection(v) && v instanceof Array) { + results.push(ret[k] = v.slice(0)); + } else { + results.push(ret[k] = v); + } + } else { + results.push(void 0); + } + } + return results; + }; + obj3 = {}; + if (obj1) { + copyObject(obj1, obj3); + } + if (obj2) { + copyObject(obj2, obj3); + } + return obj3; +}; + + +},{"../util/d3selection.coffee":211,"./validate.coffee":175}],175:[function(require,module,exports){ + +/** + * This function returns true if the variable passed is a literal javascript keyed Object. It's a small, simple function, but it catches some edge-cases that can throw off your code (such as Arrays and `null`). + * @method d3plus.object.validate + * @for d3plus.object + * @param obj {Object} The object to validate. + * @return {Boolean} + */ +module.exports = function(obj) { + return obj && obj.constructor === Object; +}; + + +},{}],176:[function(require,module,exports){ +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Formats a string similar to Python's "format" +//------------------------------------------------------------------------------ +module.exports = function() { + + var args = Array.prototype.slice.call(arguments) + , str = args.shift() + + str.unkeyed_index = 0; + return str.replace(/\{(\w*)\}/g, function(match, key) { + if (key === '') { + key = str.unkeyed_index; + str.unkeyed_index++ + } + if (key == +key) { + return args[key] !== 'undefined' + ? args[key] + : match; + } else { + for (var i = 0; i < args.length; i++) { + if (typeof args[i] === 'object' && typeof args[i][key] !== 'undefined') { + return args[i][key]; + } + } + return match; + } + }.bind(str)); + +} + +},{}],177:[function(require,module,exports){ +var format, locale; + +format = require("./format.js"); + +locale = require("../core/locale/languages/en_US.coffee").ui; + +module.exports = function(list, andText, max, moreText) { + var amount; + if (!(list instanceof Array)) { + return list; + } else { + list = list.slice(0); + } + if (!andText) { + andText = locale.and; + } + if (!moreText) { + moreText = locale.moreText; + } + if (list.length === 2) { + return list.join(" " + andText + " "); + } else { + if (max && list.length > max) { + amount = list.length - max + 1; + list = list.slice(0, max - 1); + list[max - 1] = format(moreText, amount); + } + if (list.length > 1) { + list[list.length - 1] = andText + " " + list[list.length - 1]; + } + return list.join(", "); + } +}; + + +},{"../core/locale/languages/en_US.coffee":72,"./format.js":176}],178:[function(require,module,exports){ +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Removes all non ASCII characters +//------------------------------------------------------------------------------ +module.exports = function(str) { + + var removed = [ "!","@","#","$","%","^","&","*","(",")", + "[","]","{","}",".",",","/","\\","|", + "'","\"",";",":","<",">","?","=","+"]; + + var diacritics = [ + [/[\300-\306]/g, "A"], + [/[\340-\346]/g, "a"], + [/[\310-\313]/g, "E"], + [/[\350-\353]/g, "e"], + [/[\314-\317]/g, "I"], + [/[\354-\357]/g, "i"], + [/[\322-\330]/g, "O"], + [/[\362-\370]/g, "o"], + [/[\331-\334]/g, "U"], + [/[\371-\374]/g, "u"], + [/[\321]/g, "N"], + [/[\361]/g, "n"], + [/[\307]/g, "C"], + [/[\347]/g, "c"] + ]; + + str += ""; + + return ""+str.replace(/[^A-Za-z0-9\-_]/g, function(chr) { + + if (" " === chr) { + return "_"; + } + else if (removed.indexOf(chr) >= 0) { + return ""; + } + + var ret = chr; + for (var d = 0; d < diacritics.length; d++) { + if (new RegExp(diacritics[d][0]).test(chr)) { + ret = diacritics[d][1]; + break; + } + } + + return ret; + + }); + +}; + +},{}],179:[function(require,module,exports){ +var defaultLocale; + +defaultLocale = require("../core/locale/languages/en_US.coffee"); + +module.exports = function(text, opts) { + var biglow, bigs, key, locale, smalls; + if (!text) { + return ""; + } + if (!opts) { + opts = {}; + } + key = opts.key; + if (text.charAt(text.length - 1) === ".") { + return text.charAt(0).toUpperCase() + text.substr(1); + } + locale = "locale" in this ? this.locale.value : defaultLocale; + smalls = locale.lowercase.map(function(b) { + return b.toLowerCase(); + }); + bigs = locale.uppercase; + bigs = bigs.concat(bigs.map(function(b) { + return b + "s"; + })); + biglow = bigs.map(function(b) { + return b.toLowerCase(); + }); + return text.replace(/[^\s!-#%&(-\x2A,-:;\x3F@\x5B-\x5D_\x7B}\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E3B\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]*/g, function(txt, i) { + var bigindex, new_txt; + if (txt) { + bigindex = biglow.indexOf(txt.toLowerCase()); + if (bigindex >= 0) { + return new_txt = bigs[bigindex]; + } else if (smalls.indexOf(txt.toLowerCase()) >= 0 && i !== 0 && i !== text.length - 1) { + return new_txt = txt.toLowerCase(); + } else { + return new_txt = txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); + } + } else { + return ""; + } + }); +}; + + +},{"../core/locale/languages/en_US.coffee":72}],180:[function(require,module,exports){ +var foreign, tspan; + +foreign = require("./foreign.coffee"); + +tspan = require("./tspan.coffee"); + +module.exports = function(vars) { + if (vars.text.html.value) { + foreign(vars); + } else { + tspan(vars); + } +}; + + +},{"./foreign.coffee":181,"./tspan.coffee":184}],181:[function(require,module,exports){ +module.exports = function(vars) { + var anchor, color, family, opacity, text; + text = vars.container.value; + family = text.attr("font-family") || text.style("font-family"); + anchor = vars.align.value || text.attr("text-anchor") || text.style("text-anchor"); + color = text.attr("fill") || text.style("fill"); + opacity = text.attr("opacity") || text.style("opacity"); + anchor = anchor === "end" ? "right" : (anchor === "middle" ? "center" : "left"); + d3.select(text.node().parentNode).append("foreignObject").attr("width", vars.width.value + "px").attr("height", vars.height.value + "px").attr("x", "0px").attr("y", "0px").append("xhtml:div").style("font-family", family).style("font-size", vars.size.value[1] + "px").style("color", color).style("text-align", anchor).style("opacity", opacity).text(vars.text.current); +}; + + +},{}],182:[function(require,module,exports){ +module.exports = function(vars) { + var diff, elem, height, prev, radius, shape, size, width, x, y; + elem = vars.container.value; + prev = elem.node().previousElementSibling; + shape = prev ? prev.tagName.toLowerCase() : ""; + if (prev) { + prev = d3.select(prev); + } + vars.container.x = vars.x.value || parseFloat(elem.attr("x"), 10); + vars.container.y = vars.y.value || parseFloat(elem.attr("y"), 10); + if (prev) { + if (vars.shape.accepted.indexOf(shape) >= 0) { + vars.self.shape(shape); + } + if (shape === "rect") { + x = parseFloat(prev.attr("x"), 10) || 0; + y = parseFloat(prev.attr("y"), 10) || 0; + if (vars.padding.value === false) { + diff = Math.abs(x - vars.container.x); + if (diff) { + vars.self.padding(diff); + } + } + if (!vars.container.x) { + vars.container.x = x + vars.padding.value; + } + if (!vars.container.y) { + vars.container.y = y + vars.padding.value; + } + if (!vars.width.value) { + width = parseFloat(prev.attr("width" || prev.style("width", 10))); + vars.self.width(width); + } + if (!vars.height.value) { + height = parseFloat(prev.attr("height" || prev.style("height", 10))); + vars.self.height(height); + } + } else if (shape === "circle") { + radius = parseFloat(prev.attr("r"), 10); + x = parseFloat(prev.attr("cx"), 10) || 0; + x -= radius; + y = parseFloat(prev.attr("cy"), 10) || 0; + y -= radius; + if (vars.padding.value === false) { + diff = Math.abs(x - vars.container.x); + if (diff) { + vars.self.padding(diff); + } + } + if (!vars.container.x) { + vars.container.x = x + vars.padding.value; + } + if (!vars.container.y) { + vars.container.y = y + vars.padding.value; + } + if (!vars.width.value) { + vars.self.width(radius * 2, 10); + } + if (!vars.height.value) { + vars.self.height(radius * 2, 10); + } + } else { + if (!vars.width.value) { + vars.self.width(500); + } + if (!vars.height.value) { + vars.self.height(500); + } + } + } + if (!vars.container.x) { + vars.container.x = 0; + } + if (!vars.container.y) { + vars.container.y = 0; + } + vars.width.inner = vars.width.value - vars.padding.value * 2; + vars.height.inner = vars.height.value - vars.padding.value * 2; + size = elem.attr("font-size") || elem.style("font-size"); + size = parseFloat(size, 10); + vars.container.fontSize = size; + vars.container.dy = parseFloat(elem.attr("dy"), 10); + if (!vars.size.value) { + if (vars.resize.value) { + return vars.self.size([4, 80]); + } else { + return vars.self.size([size / 2, size]); + } + } +}; + + +},{}],183:[function(require,module,exports){ +module.exports = function(vars) { + var text; + if (!vars.text.value) { + text = vars.container.value.text(); + if (text) { + if (text.indexOf("tspan") >= 0) { + text.replace(/\<\/tspan\>\/g, " "); + text.replace(/\<\/tspan\>/g, ""); + text.replace(/\/g, ""); + } + text = text.replace(/(\r\n|\n|\r)/gm, ""); + text = text.replace(/^\s+|\s+$/g, ""); + vars.self.text(text); + } + } + if (vars.text.value instanceof Array) { + vars.text.phrases = vars.text.value.filter(function(t) { + return ["string", "number"].indexOf(typeof t) >= 0; + }); + } else { + vars.text.phrases = [vars.text.value + ""]; + } + if (!vars.align.value) { + return vars.container.align = vars.container.value.style("text-anchor") || vars.container.value.attr("text-anchor"); + } +}; + + +},{}],184:[function(require,module,exports){ +var rtl; + +rtl = require("../../client/rtl.coffee"); + +module.exports = function(vars) { + var anchor, dy, ellipsis, fontSize, h, height, line, lineWidth, lines, mirror, newLine, placeWord, progress, reverse, rmod, rotate, rx, ry, space, start, textBox, translate, truncate, valign, width, words, wrap, x, xOffset, y, yOffset; + newLine = function(first) { + var tspan; + if (!reverse || first) { + tspan = vars.container.value.append("tspan"); + } else { + tspan = vars.container.value.insert("tspan", "tspan"); + } + return tspan.attr("x", x + "px").attr("dy", dy + "px").style("baseline-shift", "0%").attr("dominant-baseline", "alphabetic"); + }; + mirror = vars.rotate.value === -90 || vars.rotate.value === 90; + width = mirror ? vars.height.inner : vars.width.inner; + height = mirror ? vars.width.inner : vars.height.inner; + if (vars.shape.value === "circle") { + anchor = "middle"; + } else { + anchor = vars.align.value || vars.container.align || "start"; + } + if (anchor === "end" || (anchor === "start" && rtl)) { + xOffset = width; + } else if (anchor === "middle") { + xOffset = width / 2; + } else { + xOffset = 0; + } + valign = vars.valign.value || "top"; + x = vars.container.x + xOffset; + fontSize = vars.resize.value ? vars.size.value[1] : vars.container.fontSize || vars.size.value[0]; + dy = vars.container.dy || fontSize * 1.1; + textBox = null; + progress = null; + words = null; + reverse = false; + yOffset = 0; + if (vars.shape.value === "circle") { + if (valign === "middle") { + yOffset = ((height / dy % 1) * dy) / 2; + } else if (valign === "end") { + yOffset = (height / dy % 1) * dy; + } + } + vars.container.value.attr("text-anchor", anchor).attr("font-size", fontSize + "px").style("font-size", fontSize + "px").attr("x", vars.container.x).attr("y", vars.container.y); + truncate = function() { + textBox.remove(); + if (reverse) { + line++; + textBox = vars.container.value.select("tspan"); + } else { + line--; + textBox = d3.select(vars.container.value.node().lastChild); + } + if (!textBox.empty()) { + words = textBox.text().match(/[^\s-]+-?/g); + return ellipsis(); + } + }; + lineWidth = function() { + var b; + if (vars.shape.value === "circle") { + b = ((line - 1) * dy) + yOffset; + if (b > height / 2) { + b += dy; + } + return 2 * Math.sqrt(b * ((2 * (width / 2)) - b)); + } else { + return width; + } + }; + ellipsis = function() { + var lastChar, lastWord; + if (words && words.length) { + lastWord = words.pop(); + lastChar = lastWord.charAt(lastWord.length - 1); + if (lastWord.length === 1 && vars.text.split.value.indexOf(lastWord) >= 0) { + return ellipsis(); + } else { + if (vars.text.split.value.indexOf(lastChar) >= 0) { + lastWord = lastWord.substr(0, lastWord.length - 1); + } + textBox.text(words.join(" ") + " " + lastWord + "..."); + if (textBox.node().getComputedTextLength() > lineWidth()) { + return ellipsis(); + } + } + } else { + return truncate(); + } + }; + placeWord = function(word) { + var current, i, joiner, next_char; + current = textBox.text(); + next_char = ""; + if (reverse) { + next_char = vars.text.current.charAt(vars.text.current.length - progress.length - 1); + if (next_char === " ") { + joiner = ""; + i = 2; + while (next_char === " ") { + joiner += " "; + next_char = vars.text.current.charAt(vars.text.current.length - progress.length - i); + i++; + } + } else { + joiner = ""; + } + progress = word + joiner + progress; + textBox.text(word + joiner + current); + } else { + next_char = vars.text.current.charAt(progress.length); + if (next_char === " ") { + joiner = ""; + i = 1; + while (next_char === " ") { + joiner += " "; + next_char = vars.text.current.charAt(progress.length + i); + i++; + } + } else { + joiner = ""; + } + progress += joiner + word; + textBox.text(current + joiner + word); + } + if (Math.floor(textBox.node().getComputedTextLength()) > lineWidth() || next_char === "\n") { + textBox.text(current); + if (current.length) { + textBox = newLine(); + } + textBox.text(word); + if (reverse) { + return line--; + } else { + return line++; + } + } + }; + start = 1; + line = null; + lines = null; + wrap = function() { + var i, j, len, next_char, unsafe, word; + vars.container.value.text("").html(""); + words = vars.text.words.slice(); + if (reverse) { + words.reverse(); + } + progress = ""; + textBox = newLine(true); + line = start; + for (j = 0, len = words.length; j < len; j++) { + word = words[j]; + if (line * dy > height) { + truncate(); + break; + } + placeWord(word); + unsafe = true; + while (unsafe) { + next_char = vars.text.current.charAt(progress.length); + i = 1; + while (next_char === " ") { + next_char = vars.text.current.charAt(progress.length + i); + i++; + } + unsafe = vars.text.split.value.indexOf(next_char) >= 0; + if (unsafe) { + placeWord(next_char); + } + } + } + if (line * dy > height) { + truncate(); + } + return lines = Math.abs(line - start) + 1; + }; + wrap(); + lines = 0; + vars.container.value.selectAll("tspan").each(function() { + if (d3.select(this).text().length) { + return lines++; + } + }); + if (vars.shape.value === "circle") { + space = height - lines * dy; + if (space > dy) { + if (valign === "middle") { + start = (space / dy / 2 >> 0) + 1; + wrap(); + } else if (valign === "bottom") { + reverse = true; + start = height / dy >> 0; + wrap(); + } + } + } + lines = 0; + vars.container.value.selectAll("tspan").each(function() { + if (d3.select(this).text().length) { + return lines++; + } + }); + if (valign === "top") { + y = 0; + } else { + h = lines * dy; + y = valign === "middle" ? height / 2 - h / 2 : height - h; + } + y -= dy * 0.2; + translate = "translate(0," + y + ")"; + if (vars.rotate.value === 180 || vars.rotate.value === -180) { + rx = vars.container.x + width / 2; + ry = vars.container.y + height / 2; + } else { + rmod = vars.rotate.value < 0 ? width : height; + rx = vars.container.x + rmod / 2; + ry = vars.container.y + rmod / 2; + } + rotate = "rotate(" + vars.rotate.value + ", " + rx + ", " + ry + ")"; + return vars.container.value.attr("transform", rotate + translate); +}; + + +},{"../../client/rtl.coffee":42}],185:[function(require,module,exports){ +var flow, fontSizes, resize, wrap; + +flow = require("./flow.coffee"); + +fontSizes = require("../../font/sizes.coffee"); + +wrap = function(vars) { + var firstChar; + if (vars.text.phrases.length) { + vars.text.current = vars.text.phrases.shift() + ""; + vars.text.words = vars.text.current.match(vars.text.split["break"]); + firstChar = vars.text.current.charAt(0); + if (firstChar !== vars.text.words[0].charAt(0)) { + vars.text.words[0] = firstChar + vars.text.words[0]; + } + vars.container.value.html(""); + if (vars.resize.value) { + resize(vars); + } else { + flow(vars); + } + } +}; + +module.exports = wrap; + +resize = function(vars) { + var addon, areaMod, areaRatio, boxArea, height, heightMax, i, lineWidth, maxWidth, mirror, sizeMax, sizeRatio, sizes, textArea, width, widthRatio, words; + words = []; + i = 0; + while (i < vars.text.words.length) { + addon = (i === vars.text.words.length - 1 ? "" : " "); + words.push(vars.text.words[i] + addon); + i++; + } + mirror = vars.rotate.value === -90 || vars.rotate.value === 90; + width = mirror ? vars.height.inner : vars.width.inner; + height = mirror ? vars.width.inner : vars.height.inner; + sizeMax = Math.floor(vars.size.value[1]); + lineWidth = vars.shape.value === "circle" ? width * 0.75 : width; + sizes = fontSizes(words, { + "font-size": sizeMax + "px" + }, { + parent: vars.container.value + }); + maxWidth = d3.max(sizes, function(d) { + return d.width; + }); + areaMod = 1.165 + (width / height * 0.11); + textArea = d3.sum(sizes, function(d) { + var h; + h = vars.container.dy || sizeMax * 1.2; + return d.width * h; + }) * areaMod; + if (vars.shape.value === "circle") { + boxArea = Math.PI * Math.pow(width / 2, 2); + } else { + boxArea = lineWidth * height; + } + if (maxWidth > lineWidth || textArea > boxArea) { + areaRatio = Math.sqrt(boxArea / textArea); + widthRatio = lineWidth / maxWidth; + sizeRatio = d3.min([areaRatio, widthRatio]); + sizeMax = d3.max([vars.size.value[0], Math.floor(sizeMax * sizeRatio)]); + } + heightMax = Math.floor(height * 0.8); + if (sizeMax > heightMax) { + sizeMax = heightMax; + } + if (maxWidth * (sizeMax / vars.size.value[1]) <= lineWidth) { + if (sizeMax !== vars.size.value[1]) { + vars.self.size([vars.size.value[0], sizeMax]); + } + flow(vars); + } else { + wrap(vars); + } +}; + + +},{"../../font/sizes.coffee":104,"./flow.coffee":180}],186:[function(require,module,exports){ +module.exports = { + accepted: [false, "start", "middle", "end", "left", "center", "right"], + process: function(value) { + var css; + css = ["left", "center", "right"].indexOf(value); + if (css >= 0) { + value = this.accepted[css + 1]; + } + return value; + }, + value: false +}; + + +},{}],187:[function(require,module,exports){ +arguments[4][110][0].apply(exports,arguments) +},{"dup":110}],188:[function(require,module,exports){ +var d3selection; + +d3selection = require("../../util/d3selection.coffee"); + +module.exports = { + accepted: [false, Array, Object, String], + element: false, + id: "default", + process: function(value) { + if (value === false) { + return false; + } else if (d3selection(value)) { + return value; + } else if (value instanceof Array) { + return d3.select(value[0][0]); + } else { + this.selector = value; + return d3.select(value); + } + }, + value: false +}; + + +},{"../../util/d3selection.coffee":211}],189:[function(require,module,exports){ +arguments[4][114][0].apply(exports,arguments) +},{"dup":114}],190:[function(require,module,exports){ +var print, stringFormat; + +print = require("../../core/console/print.coffee"); + +stringFormat = require("../../string/format.js"); + +module.exports = { + accepted: [void 0], + process: function(value, vars) { + var selector, str; + if (this.initialized === false) { + return value; + } + if (vars.container.value === false) { + str = vars.format.locale.value.dev.setContainer; + print.warning(str, "container"); + } else if (vars.container.value.empty()) { + str = vars.format.locale.value.dev.noContainer; + selector = vars.container.selector || ""; + print.warning(stringFormat(str, "\"" + selector + "\""), "container"); + } else { + if (vars.dev.value) { + print.time("total draw time"); + } + vars.container.value.call(vars.self); + } + return value; + }, + value: void 0 +}; + + +},{"../../core/console/print.coffee":54,"../../string/format.js":176}],191:[function(require,module,exports){ +var locale, mergeObject; + +locale = require("../../core/locale/locale.coffee"); + +mergeObject = require("../../object/merge.coffee"); + +module.exports = { + accepted: [Function, String], + locale: { + accepted: function() { + return d3.keys(locale); + }, + process: function(value) { + var defaultLocale, returnObject; + defaultLocale = "en_US"; + returnObject = locale[defaultLocale]; + if (value !== defaultLocale) { + returnObject = mergeObject(returnObject, locale[value]); + } + this.language = value; + return returnObject; + }, + value: "en_US" + }, + process: function(value, vars) { + if (this.initialized && typeof value === "string") { + vars.self.format({ + locale: value + }); + } else { + if (typeof value === "function") { + return value; + } + } + return this.value; + }, + value: "en_US" +}; + + +},{"../../core/locale/locale.coffee":81,"../../object/merge.coffee":174}],192:[function(require,module,exports){ +module.exports = { + accepted: [false, Number], + value: false +}; + + +},{}],193:[function(require,module,exports){ +arguments[4][192][0].apply(exports,arguments) +},{"dup":192}],194:[function(require,module,exports){ +arguments[4][114][0].apply(exports,arguments) +},{"dup":114}],195:[function(require,module,exports){ +module.exports = { + accepted: [-180, -90, 0, 90, 180], + value: 0 +}; + + +},{}],196:[function(require,module,exports){ +module.exports = { + accepted: ["circle", "square"], + value: false +}; + + +},{}],197:[function(require,module,exports){ +module.exports = { + accepted: [Array, false], + value: false +}; + + +},{}],198:[function(require,module,exports){ +module.exports = { + accepted: [false, Array, Number, String], + html: { + accepted: [Boolean], + value: false + }, + init: function(vars) { + var s; + s = this.split.value; + this.split["break"] = new RegExp("[^\\s\\" + s.join("\\") + "]+\\" + s.join("?\\") + "?", "g"); + return false; + }, + split: { + accepted: [Array], + process: function(s) { + this["break"] = new RegExp("[^\\s\\" + s.join("\\") + "]+\\" + s.join("?\\") + "?", "g"); + return s; + }, + value: ["-", "/", ";", ":", "&"] + } +}; + + +},{}],199:[function(require,module,exports){ +module.exports = { + accepted: [false, "top", "middle", "bottom"], + value: false +}; + + +},{}],200:[function(require,module,exports){ +arguments[4][192][0].apply(exports,arguments) +},{"dup":192}],201:[function(require,module,exports){ +arguments[4][192][0].apply(exports,arguments) +},{"dup":192}],202:[function(require,module,exports){ +arguments[4][192][0].apply(exports,arguments) +},{"dup":192}],203:[function(require,module,exports){ +var attach, print, sizes, text, wrap; + +attach = require("../core/methods/attach.coffee"); + +sizes = require("./helpers/parseSize.coffee"); + +print = require("../core/console/print.coffee"); + +text = require("./helpers/parseText.coffee"); + +wrap = require("./helpers/wrap.coffee"); + +module.exports = function() { + var vars; + vars = { + self: function(selection) { + selection.each(function() { + sizes(vars); + if (vars.size.value[0] <= vars.height.inner) { + text(vars); + wrap(vars); + } else { + vars.container.value.html(""); + } + if (vars.dev.value) { + print.timeEnd("total draw time"); + } + }); + return vars.self; + } + }; + attach(vars, { + align: require("./methods/align.coffee"), + config: require("./methods/config.coffee"), + container: require("./methods/container.coffee"), + dev: require("./methods/dev.coffee"), + draw: require("./methods/draw.coffee"), + format: require("./methods/format.coffee"), + height: require("./methods/height.coffee"), + padding: require("./methods/padding.coffee"), + resize: require("./methods/resize.coffee"), + rotate: require("./methods/rotate.coffee"), + text: require("./methods/text.coffee"), + shape: require("./methods/shape.coffee"), + size: require("./methods/size.coffee"), + valign: require("./methods/valign.coffee"), + width: require("./methods/width.coffee"), + x: require("./methods/x.coffee"), + y: require("./methods/y.coffee") + }); + return vars.self; +}; + + +},{"../core/console/print.coffee":54,"../core/methods/attach.coffee":82,"./helpers/parseSize.coffee":182,"./helpers/parseText.coffee":183,"./helpers/wrap.coffee":185,"./methods/align.coffee":186,"./methods/config.coffee":187,"./methods/container.coffee":188,"./methods/dev.coffee":189,"./methods/draw.coffee":190,"./methods/format.coffee":191,"./methods/height.coffee":192,"./methods/padding.coffee":193,"./methods/resize.coffee":194,"./methods/rotate.coffee":195,"./methods/shape.coffee":196,"./methods/size.coffee":197,"./methods/text.coffee":198,"./methods/valign.coffee":199,"./methods/width.coffee":200,"./methods/x.coffee":201,"./methods/y.coffee":202}],204:[function(require,module,exports){ +var defaultLocale = require("../core/locale/languages/en_US.coffee"), + events = require("../client/pointer.coffee"), + legible = require("../color/legible.coffee"), + move = require("./move.coffee"), + prefix = require("../client/prefix.coffee"), + rtl = require("../client/rtl.coffee"), + removeTooltip = require("./remove.coffee"), + scroll = require("../client/scroll.js"), + scrollBar = require("../client/scrollbar.coffee"), + stringList = require("../string/list.coffee"), + textColor = require("../color/text.coffee") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Create a Tooltip +//------------------------------------------------------------------- +module.exports = function(params) { + + var default_width = params.fullscreen ? 250 : 200 + , vendor = prefix() + params.width = params.width || default_width + params.max_width = params.max_width || 386 + params.id = params.id || "default" + params.size = params.fullscreen || params.html ? "large" : "small" + params.offset = params.offset || 0 + params.arrow_offset = params.arrow ? 8 : 0 + params.x = params.x || 0 + params.y = params.y || 0 + params.parent = params.parent || d3.select("body") + params.curtain = params.curtain || "#fff" + params.curtainopacity = params.curtainopacity || 0.8 + params.background = params.background || "#fff" + params.fontcolor = params.fontcolor || "#444" + params.fontfamily = params.fontfamily || "sans-serif" + params.fontweight = params.fontweight || "normal" + params.fontsize = params.fontsize || "12px" + params.style = params.style || "default" + params.zindex = params.size == "small" ? 2000 : 500 + params.locale = params.locale || defaultLocale + params.stacked = params.stacked || false; + + + var parentHeight = params.parent ? params.parent.node().offsetHeight + || params.parent.node().getBoundingClientRect().height : 0 + + if (!params.iconsize) { + params.iconsize = params.size == "small" ? 22 : 50 + } + + if (params.parent.node() === document.body) { + params.limit = [window.innerWidth + scroll.x(), window.innerHeight + scroll.y()]; + var sb = scrollBar(); + if (document.body.scrollHeight > window.innerHeight) params.limit[0] -= sb; + } + else { + params.limit = [ + parseFloat(params.parent.style("width"),10), + parseFloat(params.parent.style("height"),10) + ]; + } + + if ( params.title instanceof Array ) { + + var and = params.locale.ui.and + , more = params.locale.ui.more + + params.title = stringList( params.title , and , 3 , more ) + + } + + removeTooltip(params.id) + + params.anchor = {} + if (params.fullscreen) { + params.anchor.x = "center" + params.anchor.y = "center" + params.x = params.parent ? params.parent.node().offsetWidth/2 : window.innerWidth/2 + params.y = params.parent ? parentHeight/2 : window.innerHeight/2 + } + else if (params.align) { + var a = params.align.split(" ") + params.anchor.y = a[0] + if (a[1]) params.anchor.x = a[1] + else params.anchor.x = "center" + } + else { + params.anchor.x = "center" + params.anchor.y = "top" + } + + var title_width = params.width - 30 + + if (params.fullscreen) { + var curtain = params.parent.append("div") + .attr("id","d3plus_tooltip_curtain_"+params.id) + .attr("class","d3plus_tooltip_curtain") + .style("background-color",params.curtain) + .style("opacity",params.curtainopacity) + .style("position","absolute") + .style("z-index",499) + .style("top","0px") + .style("right","0px") + .style("bottom","0px") + .style("left","0px") + .on(events.click,function(){ + removeTooltip(params.id) + }) + } + + var tooltip = params.parent.append("div") + .datum(params) + .attr("id","d3plus_tooltip_id_"+params.id) + .attr("class","d3plus_tooltip d3plus_tooltip_"+params.size) + .style("color",params.fontcolor) + .style("font-family",params.fontfamily) + .style("font-weight",params.fontweight) + .style("font-size",params.fontsize+"px") + .style(vendor+"box-shadow","0px 1px 3px rgba(0, 0, 0, 0.25)") + .style("position","absolute") + // .style("z-index",params.zindex) + .on(events.out, close_descriptions) + + if (params.max_height) { + tooltip.style("max-height",params.max_height+"px") + } + + if (params.fixed) { + tooltip.style("z-index",500) + params.mouseevents = true + } + else { + tooltip.style("z-index",2000) + } + + var container = tooltip.append("div") + .datum(params) + .attr("class","d3plus_tooltip_container") + .style("background-color",params.background) + .style("padding","6px") + + if (params.fullscreen && params.html && !params.stacked) { + + w = params.parent ? params.parent.node().offsetWidth*0.75 : window.innerWidth*0.75 + h = params.parent ? parentHeight*0.75 : window.innerHeight*0.75 + + container + .style("width",w+"px") + .style("height",h+"px") + + var body = container.append("div") + .attr("class","d3plus_tooltip_body") + .style("padding-right","6px") + .style("display","inline-block") + .style("z-index",1) + .style("width",params.width+"px") + + } + else { + + if (params.width == "auto") { + var w = "auto" + container.style("max-width",params.max_width+"px") + } + else var w = params.width-14+"px" + + var body = container + .style("width",w) + + } + + if (params.title || params.icon) { + var header = body.append("div") + .attr("class","d3plus_tooltip_header") + .style("position","relative") + .style("z-index",1) + } + + if (params.fullscreen) { + var close = tooltip.append("div") + .attr("class","d3plus_tooltip_close") + .style("background-color",params.color) + .style("color",textColor(params.color)) + .style("position","absolute") + .style(vendor+"box-shadow","0 1px 3px rgba(0, 0, 0, 0.25)") + .style("font-size","20px") + .style("height","18px") + .style("line-height","14px") + .style("text-align","center") + .style("right","16px") + .style("top","-10px") + .style("width","18px") + .style("z-index",10) + .html("\×") + .on(events.over,function(){ + d3.select(this) + .style("cursor","pointer") + .style(vendor+"box-shadow","0 1px 3px rgba(0, 0, 0, 0.5)") + }) + .on(events.out,function(){ + d3.select(this) + .style("cursor","auto") + .style(vendor+"box-shadow","0 1px 3px rgba(0, 0, 0, 0.25)") + }) + .on(events.click,function(){ + removeTooltip(params.id) + }) + + d3.select("body").on("keydown.esc_" + params.id, function(){ + if (d3.event.keyCode === 27) { + removeTooltip(params.id); + d3.select("body").on("keydown.esc_" + params.id, null); + } + }) + + } + + if (!params.mouseevents) { + tooltip.style("pointer-events","none") + } + else if (params.mouseevents !== true) { + + var oldout = d3.select(params.mouseevents).on(events.out) + + var newout = function() { + + var target = d3.event.toElement || d3.event.relatedTarget + if (target) { + var c = typeof target.className == "string" ? target.className : target.className.baseVal + var istooltip = c.indexOf("d3plus_tooltip") == 0 + } + else { + var istooltip = false + } + if (!target || (!ischild(tooltip.node(),target) && !ischild(params.mouseevents,target) && !istooltip)) { + oldout(d3.select(params.mouseevents).datum()) + close_descriptions() + d3.select(params.mouseevents).on(events.out,oldout) + } + } + + var ischild = function(parent, child) { + var node = child.parentNode; + while (node !== null) { + if (node == parent) { + return true; + } + node = node.parentNode; + } + return false; + } + + d3.select(params.mouseevents).on(events.out,newout) + tooltip.on(events.out,newout) + + var move_event = d3.select(params.mouseevents).on(events.move) + if (move_event) { + tooltip.on(events.move,move_event) + } + + } + + if (params.arrow) { + var arrow = tooltip.append("div") + .attr("class","d3plus_tooltip_arrow") + .style("background-color",params.background) + .style(vendor+"box-shadow","0px 1px 3px rgba(0, 0, 0, 0.25)") + .style("position","absolute") + .style("bottom","-5px") + .style("height","10px") + .style("left","50%") + .style("margin-left","-5px") + .style("width","10px") + .style(vendor+"transform","rotate(45deg)") + .style("z-index",-1) + } + + if (params.icon) { + + var title_icon = header.append("div") + .attr("class","d3plus_tooltip_icon") + .style("width",params.iconsize+"px") + .style("height",params.iconsize+"px") + .style("z-index",1) + .style("background-position","50%") + .style("background-size","100%") + .style("background-image","url("+params.icon+")") + .style("display","inline-block") + .style("margin","0px 3px 3px 0px") + + if (params.style == "knockout") { + title_icon.style("background-color",params.color) + } + + title_width -= title_icon.node().offsetWidth + } + + if (params.title) { + var mw = params.max_width-6 + if ( params.icon ) mw -= (params.iconsize+6) + mw += "px" + + var title = header.append("div") + .attr("class","d3plus_tooltip_title") + .style("max-width",mw) + .style("color",!params.icon ? legible(params.color) : params.fontcolor) + .style("vertical-align","top") + .style("width",title_width+"px") + .style("display","inline-block") + .style("overflow","hidden") + .style("text-overflow","ellipsis") + .style("word-wrap","break-word") + .style("z-index",1) + .style("font-size",params.size === "large" ? "18px" : "16px") + .style("line-height",params.size === "large" ? "20px" : "17px") + .style("padding",params.size === "large" ? "3px 6px" : "3px") + .text(params.title) + } + + if (params.description) { + var description = body.append("div") + .attr("class","d3plus_tooltip_description") + .style("font-size","12px") + .style("padding","6px") + .text(params.description) + } + + if (params.data || params.html && !params.fullscreen) { + + var data_container = body.append("div") + .attr("class","d3plus_tooltip_data_container") + .style("overflow-y","auto") + .style("z-index",-1) + } + + if (params.data) { + + var val_width = 0, val_heights = {} + + var last_group = null + params.data.forEach(function(d,i){ + + if (d.group) { + if (last_group != d.group) { + last_group = d.group + data_container.append("div") + .attr("class","d3plus_tooltip_data_title") + .style("font-size","12px") + .style("font-weight","bold") + .style("padding","6px 3px 0px 3px") + .text(d.group) + } + } + + var block = data_container.append("div") + .attr("class","d3plus_tooltip_data_block") + .style("font-size","12px") + .style("padding","3px 6px") + .style("position","relative") + .datum(d) + + if ( d.highlight === true ) { + block.style("color",legible(params.color)) + } + else if ( d.allColors || d.highlight !== params.color ) { + block.style("color",legible(d.highlight)) + } + + var name = block.append("div") + .attr("class","d3plus_tooltip_data_name") + .style("display","inline-block") + .html(d.name) + .on(events.out,function(){ + d3.event.stopPropagation() + }) + + if (d.link) { + name + .style("cursor","pointer") + .on(events.click,d.link) + } + + if ( d.value instanceof Array ) { + + var and = params.locale.ui.and + , more = params.locale.ui.more + + d.value = list( d.value , and , 3 , more ) + + } + + var val = block.append("div") + .attr("class","d3plus_tooltip_data_value") + .style("display","block") + .style("position","absolute") + .style("text-align","right") + .style("top","3px") + .html(d.value) + .on(events.out,function(){ + d3.event.stopPropagation() + }) + + if (rtl) { + val.style("left","6px") + } + else { + val.style("right","6px") + } + + if (params.mouseevents && d.desc) { + var desc = block.append("div") + .attr("class","d3plus_tooltip_data_desc") + .style("color","#888") + .style("overflow","hidden") + .style(vendor+"transition","height 0.5s") + .style("width","85%") + .text(d.desc) + .on(events.out,function(){ + d3.event.stopPropagation() + }) + + var dh = desc.node().offsetHeight || desc.node().getBoundingClientRect().height + + desc.style("height","0px") + + var help = name.append("div") + .attr("class","d3plus_tooltip_data_help") + .style("background-color","#ccc") + .style(vendor+"border-radius","5px") + .style("color","#fff") + .style("cursor","pointer") + .style("display","inline-block") + .style("font-size","8px") + .style("font-weight","bold") + .style("height","10px") + .style("margin","3px 0px 0px 3px") + .style("padding-right","1px") + .style("text-align","center") + .style("width","10px") + .style("vertical-align","top") + .style(prefix+"transition","background-color 0.5s") + .text("?") + .on(events.over,function(){ + var c = d3.select(this.parentNode.parentNode).style("color") + d3.select(this).style("background-color",c) + desc.style("height",dh+"px") + }) + .on(events.out,function(){ + d3.event.stopPropagation() + }) + + name + .style("cursor","pointer") + .on(events.over,function(){ + close_descriptions() + var c = d3.select(this.parentNode).style("color") + help.style("background-color",c) + desc.style("height",dh+"px") + }) + + block.on(events.out,function(){ + d3.event.stopPropagation() + close_descriptions() + }) + } + + var w = parseFloat(val.style("width"),10) + if (w > params.width/2) w = params.width/2 + if (w > val_width) val_width = w + + if (i != params.data.length-1) { + if ((d.group && d.group == params.data[i+1].group) || !d.group && !params.data[i+1].group) + data_container.append("div") + .attr("class","d3plus_tooltip_data_seperator") + .style("background-color","#ddd") + .style("display","block") + .style("height","1px") + .style("margin","0px 3px") + } + + }) + + data_container.selectAll(".d3plus_tooltip_data_name") + .style("width",function(){ + var w = parseFloat(d3.select(this.parentNode).style("width"),10) + return (w-val_width-30)+"px" + }) + + data_container.selectAll(".d3plus_tooltip_data_value") + .style("width",val_width+"px") + .each(function(d){ + var h = parseFloat(d3.select(this).style("height"),10) + val_heights[d.name] = h + }) + + data_container.selectAll(".d3plus_tooltip_data_name") + .style("min-height",function(d){ + return val_heights[d.name]+"px" + }) + + } + + if (params.html && (!params.fullscreen || params.stacked)) { + data_container.append("div") + .html(params.html) + if (params.js) { + params.js(container) + } + } + + var footer = body.append("div") + .attr("class","d3plus_tooltip_footer") + .style("font-size","10px") + .style("position","relative") + .style("text-align","center") + + if (params.footer) { + footer.html(params.footer) + } + + params.height = tooltip.node().offsetHeight || tooltip.node().getBoundingClientRect().height + + if (params.html && params.fullscreen && !params.stacked) { + var h = params.height-12 + var w = tooltip.node().offsetWidth-params.width-44 + container.append("div") + .attr("class","d3plus_tooltip_html") + .style("width",w+"px") + .style("height",h+"px") + .style("display","inline-block") + .style("vertical-align","top") + .style("overflow-y","auto") + .style("padding","0px 12px") + .style("position","absolute") + .html(params.html) + if (params.js) { + params.js(container) + } + } + + params.width = tooltip.node().offsetWidth + + if (params.anchor.y != "center") params.height += params.arrow_offset + else params.width += params.arrow_offset + + if (params.data || ((!params.fullscreen || params.stacked) && params.html)) { + + if (!params.fullscreen || params.stacked) { + var limit = params.fixed ? parentHeight-params.y-10 : parentHeight-10 + var h = params.height < limit ? params.height : limit + } + else { + var h = params.height + } + h -= parseFloat(container.style("padding-top"),10) + h -= parseFloat(container.style("padding-bottom"),10) + if (header) { + h -= header.node().offsetHeight || header.node().getBoundingClientRect().height + h -= parseFloat(header.style("padding-top"),10) + h -= parseFloat(header.style("padding-bottom"),10) + } + if (footer) { + h -= footer.node().offsetHeight || footer.node().getBoundingClientRect().height + h -= parseFloat(footer.style("padding-top"),10) + h -= parseFloat(footer.style("padding-bottom"),10) + } + + data_container + .style("max-height",h+"px") + } + + params.height = tooltip.node().offsetHeight || tooltip.node().getBoundingClientRect().height + + move(params.x, params.y, params.id); + +} + + + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Function that closes ALL Descriptions +//------------------------------------------------------------------- +function close_descriptions() { + d3.selectAll("div.d3plus_tooltip_data_desc").style("height","0px"); + d3.selectAll("div.d3plus_tooltip_data_help").style("background-color","#ccc"); +} + +},{"../client/pointer.coffee":40,"../client/prefix.coffee":41,"../client/rtl.coffee":42,"../client/scroll.js":43,"../client/scrollbar.coffee":44,"../color/legible.coffee":46,"../color/text.coffee":52,"../core/locale/languages/en_US.coffee":72,"../string/list.coffee":177,"./move.coffee":205,"./remove.coffee":206}],205:[function(require,module,exports){ +var arrowStyle, scroll; + +scroll = require("../client/scroll.js"); + +module.exports = function(x, y, id) { + var d, mins, tooltip; + if (!id) { + id = "default"; + } + tooltip = d3.select("div#d3plus_tooltip_id_" + id); + if (tooltip.node()) { + d = tooltip.datum(); + d.cx = x; + d.cy = y; + if (!d.fixed) { + if (d.parent.node().tagName.toLowerCase() === "body") { + mins = [scroll.x(), scroll.y()]; + } else { + mins = [0, 0]; + } + if (d.anchor.y !== "center") { + if (d.anchor.x === "right") { + d.x = d.cx - d.arrow_offset - 4; + } else if (d.anchor.x === "center") { + d.x = d.cx - d.width / 2; + } else { + if (d.anchor.x === "left") { + d.x = d.cx - d.width + d.arrow_offset + 2; + } + } + if (d.anchor.y === "bottom") { + d.flip = d.cy + d.height + d.offset <= d.limit[1]; + } else { + if (d.anchor.y === "top") { + d.flip = d.cy - d.height - d.offset < mins[1]; + } + } + if (d.flip) { + d.y = d.cy + d.offset + d.arrow_offset; + } else { + d.y = d.cy - d.height - d.offset - d.arrow_offset; + } + } else { + d.y = d.cy - d.height / 2; + if (d.anchor.x === "right") { + d.flip = d.cx + d.width + d.offset <= d.limit[0]; + } else { + if (d.anchor.x === "left") { + d.flip = d.cx - d.width - d.offset < mins[0]; + } + } + if (d.anchor.x === "center") { + d.flip = false; + d.x = d.cx - d.width / 2; + } else if (d.flip) { + d.x = d.cx + d.offset + d.arrow_offset; + } else { + d.x = d.cx - d.width - d.offset; + } + } + if (d.x < mins[0]) { + d.x = mins[0]; + } else { + if (d.x + d.width > d.limit[0]) { + d.x = d.limit[0] - d.width; + } + } + if (d.y < mins[1]) { + d.y = mins[1]; + } else { + if (d.y + d.height > d.limit[1]) { + d.y = d.limit[1] - d.height; + } + } + } + tooltip.style("top", d.y + "px").style("left", d.x + "px"); + if (d.arrow) { + tooltip.selectAll(".d3plus_tooltip_arrow").call(arrowStyle); + } + } + return tooltip; +}; + +arrowStyle = function(arrow) { + return arrow.style("bottom", function(d) { + if (d.anchor.y !== "center" && !d.flip) { + return "-5px"; + } else { + return "auto"; + } + }).style("right", function(d) { + if (d.anchor.y === "center" && !d.flip) { + return "-5px"; + } else { + return "auto"; + } + }).style("top", function(d) { + if (d.anchor.y !== "center" && d.flip) { + return "-5px"; + } else if (d.anchor.y === "center") { + return "50%"; + } else { + return "auto"; + } + }).style("left", function(d) { + if (d.anchor.y === "center" && d.flip) { + return "-5px"; + } else if (d.anchor.y !== "center") { + return "50%"; + } else { + return "auto"; + } + }).style("margin-left", function(d) { + var arrow_x; + if (d.anchor.y === "center") { + return "auto"; + } else { + if (d.anchor.x === "right") { + arrow_x = -d.width / 2 + d.arrow_offset / 2; + } else if (d.anchor.x === "left") { + arrow_x = d.width / 2 - d.arrow_offset * 2 - 5; + } else { + arrow_x = -5; + } + if (d.cx - d.width / 2 - 5 < arrow_x) { + arrow_x = d.cx - d.width / 2 - 5; + if (arrow_x < 2 - d.width / 2) { + arrow_x = 2 - d.width / 2; + } + } else if (-(d.limit[0] - d.cx - d.width / 2 + 5) > arrow_x) { + arrow_x = -(d.limit[0] - d.cx - d.width / 2 + 5); + if (arrow_x > d.width / 2 - 11) { + arrow_x = d.width / 2 - 11; + } + } + return arrow_x + "px"; + } + }).style("margin-top", function(d) { + var arrow_y; + if (d.anchor.y !== "center") { + return "auto"; + } else { + if (d.anchor.y === "bottom") { + arrow_y = -d.height / 2 + d.arrow_offset / 2 - 1; + } else if (d.anchor.y === "top") { + arrow_y = d.height / 2 - d.arrow_offset * 2 - 2; + } else { + arrow_y = -9; + } + if (d.cy - d.height / 2 - d.arrow_offset < arrow_y) { + arrow_y = d.cy - d.height / 2 - d.arrow_offset; + if (arrow_y < 4 - d.height / 2) { + arrow_y = 4 - d.height / 2; + } + } else if (-(d.limit[1] - d.cy - d.height / 2 + d.arrow_offset) > arrow_y) { + arrow_y = -(d.limit[1] - d.cy - d.height / 2 + d.arrow_offset); + if (arrow_y > d.height / 2 - 22) { + arrow_y = d.height / 2 - 22; + } + } + return arrow_y + "px"; + } + }); +}; + + +},{"../client/scroll.js":43}],206:[function(require,module,exports){ +module.exports = function(id) { + if (id) { + d3.selectAll("div#d3plus_tooltip_curtain_" + id).remove(); + return d3.selectAll("div#d3plus_tooltip_id_" + id).remove(); + } else { + d3.selectAll("div.d3plus_tooltip_curtain").remove(); + return d3.selectAll("div.d3plus_tooltip").remove(); + } +}; + + +},{}],207:[function(require,module,exports){ +module.exports = function(arr, n) { + var buckets, step; + buckets = []; + step = 1 / (n - 1) * (arr[1] - arr[0]); + return d3.range(arr[0], arr[1] + step, step); +}; + + +},{}],208:[function(require,module,exports){ +var d3selection; + +d3selection = require("./d3selection.coffee"); + +module.exports = function(parent, child) { + var node; + if (!parent || !child) { + return false; + } + if (d3selection(parent)) { + parent = parent.node(); + } + if (d3selection(parent)) { + child = child.node(); + } + node = child.parentNode; + while (node !== null) { + if (node === parent) { + return true; + } + node = node.parentNode; + } + return false; +}; + + +},{"./d3selection.coffee":211}],209:[function(require,module,exports){ +module.exports = function(arr, value) { + var closest, i; + if (value.constructor === String) { + i = arr.indexOf(value); + if (i > -1) { + return arr[i]; + } else { + return arr[0]; + } + } + closest = arr[0]; + arr.forEach(function(p) { + if (Math.abs(value - p) < Math.abs(value - closest)) { + return closest = p; + } + }); + return closest; +}; + + +},{}],210:[function(require,module,exports){ +var copy, objectMerge, objectValidate; + +objectMerge = require("../object/merge.coffee"); + +objectValidate = require("../object/validate.coffee"); + +copy = function(variable) { + var ret; + if (objectValidate(variable)) { + return objectMerge(variable); + } else if (variable instanceof Array) { + ret = []; + variable.forEach(function(o) { + return ret.push(copy(o)); + }); + return ret; + } else { + return variable; + } +}; + +module.exports = copy; + + +},{"../object/merge.coffee":174,"../object/validate.coffee":175}],211:[function(require,module,exports){ +var ie; + +ie = require("../client/ie.js"); + +module.exports = function(elem) { + if (ie) { + return typeof elem === "object" && elem instanceof Array && "size" in elem && "select" in elem; + } else { + return elem instanceof d3.selection; + } +}; + + +},{"../client/ie.js":39}],212:[function(require,module,exports){ +module.exports = function(url, callback) { + var img; + img = new Image(); + img.src = url; + img.crossOrigin = "Anonymous"; + img.onload = function() { + var canvas, context; + canvas = document.createElement("canvas"); + canvas.width = this.width; + canvas.height = this.height; + context = canvas.getContext("2d"); + context.drawImage(this, 0, 0); + callback.call(this, canvas.toDataURL("image/png")); + canvas = null; + }; +}; + + +},{}],213:[function(require,module,exports){ +var objectValidate, uniques; + +objectValidate = require("../object/validate.coffee"); + +uniques = function(data, value, fetch, vars, depth, sorted) { + var check, d, i, j, k, len, len1, len2, len3, lookups, m, v, val, vals; + if (data === void 0) { + return []; + } + if (vars && depth === void 0) { + depth = vars.id.value; + } + sorted = (true === sorted && sorted === void 0); + if (!(data instanceof Array)) { + data = [data]; + } + lookups = []; + if (value === void 0) { + return data.reduce(function(p, c) { + var lookup; + lookup = JSON.stringify(c); + if (lookups.indexOf(lookup) < 0) { + if (p.indexOf(c) < 0) { + p.push(c); + } + lookups.push(lookup); + } + return p; + }, []); + } + vals = []; + check = function(v) { + var l; + if (v !== void 0 && v !== null) { + l = JSON.stringify(v); + if (lookups.indexOf(l) < 0) { + vals.push(v); + return lookups.push(l); + } + } + }; + if (typeof fetch === "function" && vars) { + for (i = 0, len = data.length; i < len; i++) { + d = data[i]; + val = uniques(fetch(vars, d, value, depth)); + for (j = 0, len1 = val.length; j < len1; j++) { + v = val[j]; + check(v); + } + } + } else if (typeof value === "function") { + for (k = 0, len2 = data.length; k < len2; k++) { + d = data[k]; + val = value(d); + check(val); + } + } else { + for (m = 0, len3 = data.length; m < len3; m++) { + d = data[m]; + if (objectValidate(d)) { + val = d[value]; + check(val); + } + } + } + if (sorted) { + return vals.sort(function(a, b) { + return a - b; + }); + } else { + return vals; + } +}; + +module.exports = uniques; + + +},{"../object/validate.coffee":175}],214:[function(require,module,exports){ +module.exports = function(vars) { + var checkParent, i, len, ref, s; + vars.container.value.style("position", function() { + var current, remain; + current = d3.select(this).style("position"); + remain = ["absolute", "fixed"].indexOf(current) >= 0; + if (remain) { + return current; + } else { + return "relative"; + } + }); + if (vars.container.changed) { + vars.container.value.html(""); + } + ref = ["width", "height"]; + for (i = 0, len = ref.length; i < len; i++) { + s = ref[i]; + if (!vars[s].value) { + checkParent = function(element) { + var elem, val; + if (element.tagName === void 0 || ["BODY", "HTML"].indexOf(element.tagName) >= 0) { + val = window["inner" + s.charAt(0).toUpperCase() + s.slice(1)]; + elem = document !== element ? d3.select(element) : false; + if (elem) { + if (s === "width") { + val -= parseFloat(elem.style("margin-left"), 10); + val -= parseFloat(elem.style("margin-right"), 10); + val -= parseFloat(elem.style("padding-left"), 10); + val -= parseFloat(elem.style("padding-right"), 10); + } else { + val -= parseFloat(elem.style("margin-top"), 10); + val -= parseFloat(elem.style("margin-bottom"), 10); + val -= parseFloat(elem.style("padding-top"), 10); + val -= parseFloat(elem.style("padding-bottom"), 10); + } + } + return vars[s].value = val <= 20 ? vars[s].small : val; + } else { + val = parseFloat(d3.select(element).style(s), 10); + if (typeof val === "number" && val > 0) { + return vars[s].value = val; + } else if (element.tagName !== "BODY") { + return checkParent(element.parentNode); + } + } + }; + checkParent(vars.container.value.node()); + if (d3.selectAll("body > *:not(script)").size() === 1) { + d3.select("body").style("overflow", "hidden"); + } + } + } + vars.container.value.style("width", vars.width.value + "px").style("height", vars.height.value + "px"); +}; + + +},{}],215:[function(require,module,exports){ +var dataFormat = require("../../core/data/format.js"), + dataColor = require("../../core/data/color.js"), + dataKeys = require("../../core/data/keys.coffee"), + dataLoad = require("../../core/data/load.coffee"), + drawDrawer = require("./ui/drawer.js"), + drawLegend = require("./ui/legend.js"), + drawTimeline = require("./ui/timeline.coffee"), + errorCheck = require("./errorCheck.js"), + fetchData = require("../../core/fetch/data.js"), + finish = require("./finish.js"), + focusTooltip = require("./focus/tooltip.coffee"), + history = require("./ui/history.coffee"), + parseEdges = require("../../core/parse/edges.js"), + parseNodes = require("../../core/parse/nodes.js"), + print = require("../../core/console/print.coffee"), + removeTooltip = require("../../tooltip/remove.coffee"), + runType = require("./types/run.coffee"), + shapes = require("./shapes/draw.js"), + stringFormat = require("../../string/format.js"), + svgSetup = require("./svg/enter.js"), + svgUpdate = require("./svg/update.js"), + titles = require("./ui/titles.js"), + validObject = require("../../object/validate.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Calculate steps needed to redraw the visualization +//------------------------------------------------------------------------------ +module.exports = function(vars) { + + var steps = [] + , appType = vars.type.value + , locale = vars.format.locale.value + , uiMessage = locale.message.ui + , drawMessage = locale.message.draw + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check to see if any data needs to be loaded with JSON + //---------------------------------------------------------------------------- + var urlLoads = [ "data" , "attrs" , "coords" , "nodes" , "edges" ] + urlLoads.forEach(function(u){ + + if (!vars.error.value && !vars[u].loaded && vars[u].url) { + + steps.push({ + "function": function( vars , next ){ + dataLoad( vars , u , next ) + }, + "message": locale.message.loading, + "wait": true + }) + + } + + }) + + if (vars.draw.update) { + + var appName = locale.visualization[appType] || appType + , appSetup = vars.types[appType].setup || false + , appReqs = vars.types[appType].requirements || [] + , appMessage = stringFormat(locale.message.initializing,appName) + , dataMessage = locale.message.data + + if (!(appReqs instanceof Array)) appReqs = [appReqs] + appName = appName.toLowerCase() + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If it has one, run the current app's setup function. + //-------------------------------------------------------------------------- + if (!vars.error.value && typeof appSetup === "function") { + + steps.push({ + "function": function( vars ) { + + if ( vars.dev.value ) { + var timerString = "running " + appName + " setup" + print.time( timerString ) + } + + appSetup( vars ) + + if ( vars.dev.value ) print.timeEnd( timerString ) + + }, + "message": appMessage + }) + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create SVG group elements if the container is new or has changed + //-------------------------------------------------------------------------- + if (vars.container.changed) { + + steps.push({ "function" : svgSetup , "message" : appMessage }) + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create group for current app, if it doesn't exist. + //-------------------------------------------------------------------------- + if (!(appType in vars.g.apps)) { + + steps.push({ + "function": function( vars ) { + + if ( vars.dev.value ) { + var timerString = "creating " + appName + " group" + print.time( timerString ) + } + + vars.g.apps[appType] = vars.g.app.append("g") + .attr("id", appType) + .attr("opacity", 0); + + if ( vars.dev.value ) print.timeEnd( timerString ) + + }, + "message": appMessage + }) + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If new data is detected, analyze and reset it. + //-------------------------------------------------------------------------- + if (vars.data.changed) { + + steps.push({ + "function": function(vars) { + vars.data.cache = {} + delete vars.nodes.restricted + delete vars.edges.restricted + dataKeys(vars, "data") + }, + "message": dataMessage + }) + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If new attributes are detected, analyze them. + //-------------------------------------------------------------------------- + if (vars.attrs.changed) { + + steps.push({ + "function": function( vars ) { + dataKeys(vars, "attrs") + }, + "message": dataMessage + }) + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Determine color type + //-------------------------------------------------------------------------- + steps.push({ + "function": function(vars) { + + if (!vars.color.type || vars.color.changed || vars.data.changed || + vars.attrs.changed || vars.id.changed || vars.depth.changed || + vars.id.solo.changed || + (!vars.time.fixed.value && (vars.time.solo.changed || vars.time.mute.changed))) { + + vars.color.valueScale = false; + + if ( vars.dev.value ) { + var timerString = "checking color type"; + print.time(timerString); + } + + vars.color.type = false; + + if (vars.color.value) { + + var colorKey = vars.color.value; + + if ( validObject(colorKey) ) { + if (colorKey[vars.id.value]) { + colorKey = colorKey[vars.id.value]; + } + else { + colorKey = colorKey[d3.keys(colorKey)[0]]; + } + } + + if (vars.data.keys && colorKey in vars.data.keys) { + vars.color.type = vars.data.keys[colorKey]; + } + else if (vars.attrs.keys && colorKey in vars.attrs.keys) { + vars.color.type = vars.attrs.keys[colorKey]; + } + + } + else if (vars.data.keys) { + vars.color.type = vars.data.keys[vars.id.value]; + } + + if (vars.dev.value) print.timeEnd(timerString); + + } + + }, + "message": dataMessage + }) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Format nodes/edges if needed + //-------------------------------------------------------------------------- + if ( appReqs.indexOf("edges") >= 0 && vars.edges.value + && ( !vars.edges.linked || vars.edges.changed ) ) { + steps.push({ "function" : parseEdges, "message" : dataMessage }) + } + + if ( appReqs.indexOf("nodes") >= 0 && vars.edges.value + && ( !vars.nodes.positions || vars.nodes.changed || vars.type.changed ) ) { + steps.push({ "function" : parseNodes , "message" : dataMessage }) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Groups data by time and nesting. + //-------------------------------------------------------------------------- + if (vars.data.changed || vars.time.changed || vars.time.format.changed || vars.type.changed || vars.id.changed || (vars.x.scale.changed && [vars.x.scale.value, vars.x.scale.previous].indexOf("discrete") >= 0) || (vars.y.scale.changed && [vars.y.scale.value, vars.y.scale.previous].indexOf("discrete") >= 0)) { + steps.push({ "function" : dataFormat , "message" : dataMessage }) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Fetches data for app and "pool" + //-------------------------------------------------------------------------- + if (!vars.error.value) { + steps.push({ + "function": function(vars) { + + var year = vars.time.fixed.value ? ["all"] : null + if (vars.dev.value) { + var timerString = year ? "fetching pool data" : "fetching data" + print.time( timerString ) + } + vars.data.pool = fetchData( vars , year ) + if (vars.dev.value) print.timeEnd( timerString ) + if ( !year ) { + vars.data.viz = vars.data.pool + } + else { + if ( vars.dev.value ) print.time("fetching data for current year") + vars.data.viz = fetchData( vars ) + if ( vars.dev.value ) print.timeEnd("fetching data for current year") + } + + vars.draw.timing = vars.data.viz.length < vars.data.large ? + vars.timing.transitions : 0; + + }, + "message": dataMessage + }) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Calculate color scale if type is number + //-------------------------------------------------------------------------- + if (!vars.error.value) { + steps.push({ + "check": function(vars) { + + return vars.color.value && vars.color.type === "number" && + vars.color.valueScale === false + + }, + "function": dataColor, + "message": dataMessage + }) + + } + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Remove any lingering tooltips. + //---------------------------------------------------------------------------- + steps.push({ + "function": function(vars) { + if ( vars.dev.value ) { + var str = vars.format.locale.value.message.tooltipReset + print.time(str) + } + if ( vars.type.previous && appType !== vars.type.previous ) { + removeTooltip(vars.type.previous) + } + removeTooltip(appType) + if ( vars.dev.value ) print.timeEnd(str) + }, + "message": uiMessage + }) + + if (!vars.error.value) { + steps.push({"function": errorCheck, "message": uiMessage}) + } + + steps.push({ + "function": function(vars) { + + vars.margin.process() + titles(vars) + + if (!vars.error.value) { + if (vars.draw.update) { + + drawDrawer(vars) + drawTimeline(vars) + drawLegend(vars) + + } + else { + + if ( vars.dev.value ) print.time("calculating margins") + + var drawer = vars.container.value.select("div#d3plus_drawer").node().offsetHeight + || vars.container.value.select("div#d3plus_drawer").node().getBoundingClientRect().height + + var timeline = vars.g.timeline.node().getBBox() + timeline = vars.timeline.value ? timeline.height+vars.ui.padding : 0 + + var legend = vars.g.legend.node().getBBox() + legend = vars.legend.value ? legend.height+vars.ui.padding : 0 + + vars.margin.bottom += drawer+timeline+legend + + if ( vars.dev.value ) print.timeEnd("calculating margins") + + } + } + + history(vars) + vars.height.viz -= (vars.margin.top+vars.margin.bottom) + vars.width.viz -= (vars.margin.left+vars.margin.right) + + }, + "message": uiMessage + }) + + if (!vars.error.value) { + steps.push({ + "function": focusTooltip, + "message": uiMessage + }) + } + + steps.push({ + "function": svgUpdate, + "message": drawMessage + }) + + if (!vars.error.value && vars.draw.update) { + steps.push({ + "function" : [ runType, shapes ], + "message" : drawMessage + }) + } + + steps.push({ + "function" : finish, + "message" : drawMessage + }) + + return steps + +} + +},{"../../core/console/print.coffee":54,"../../core/data/color.js":56,"../../core/data/format.js":58,"../../core/data/keys.coffee":60,"../../core/data/load.coffee":61,"../../core/fetch/data.js":66,"../../core/parse/edges.js":97,"../../core/parse/nodes.js":100,"../../object/validate.coffee":175,"../../string/format.js":176,"../../tooltip/remove.coffee":206,"./errorCheck.js":216,"./finish.js":217,"./focus/tooltip.coffee":218,"./shapes/draw.js":228,"./svg/enter.js":241,"./svg/update.js":242,"./types/run.coffee":245,"./ui/drawer.js":246,"./ui/history.coffee":247,"./ui/legend.js":248,"./ui/timeline.coffee":250,"./ui/titles.js":251}],216:[function(require,module,exports){ +var fetchText = require("../../core/fetch/text.js"), + print = require("../../core/console/print.coffee"), + rejected = require("../../core/methods/rejected.coffee"), + stringFormat = require("../../string/format.js"), + stringList = require("../../string/list.coffee") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Miscellaneous Error Checks +//------------------------------------------------------------------------------ +module.exports = function(vars) { + + if ( vars.dev.value ) print.time("checking for errors") + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check to see if we have all required variables set + //---------------------------------------------------------------------------- + var reqs = ["id"] + , app_reqs = vars.types[vars.type.value].requirements + if (app_reqs) { + if (!(app_reqs instanceof Array)) reqs.push(app_reqs) + else reqs = reqs.concat(vars.types[vars.type.value].requirements) + } + + var missing = [] + reqs.forEach(function(r){ + if (typeof r === "string") { + if (!vars[r].value) missing.push("\""+r+"\"") + } + else if (typeof r === "function") { + var reqReturn = r(vars) + if (!reqReturn.status && reqReturn.text) { + missing.push("\""+reqReturn.text+"\"") + } + } + }) + + if ( missing.length > 1 ) { + var str = vars.format.locale.value.error.methods + , app = vars.format.locale.value.visualization[vars.type.value] || vars.type.value + , and = vars.format.locale.value.ui.and + missing = stringList(missing,and) + vars.error.internal = stringFormat(str,app,missing) + } + else if ( missing.length === 1 ) { + var str = vars.format.locale.value.error.method + , app = vars.format.locale.value.visualization[vars.type.value] || vars.type.value + vars.error.internal = stringFormat(str,app,missing[0]) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check to see if we have focus connections, if needed + //---------------------------------------------------------------------------- + if (!vars.error.internal && reqs.indexOf("edges") >= 0 && reqs.indexOf("focus") >= 0) { + var connections = vars.edges.connections(vars.focus.value[0],vars.id.value) + if (connections.length == 0) { + var name = fetchText(vars,vars.focus.value[0],vars.depth.value) + , str = vars.format.locale.value.error.connections + vars.error.internal = stringFormat(str,"\""+name+"\"") + } + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check to see if we have all required libraries + //---------------------------------------------------------------------------- + var reqs = ["d3"] + if (vars.types[vars.type.value].libs) { + reqs = reqs.concat(vars.types[vars.type.value].libs) + } + var missing = [] + reqs.forEach(function(r){ + if (!window[r]) missing.push("\""+r+"\"") + }) + + if ( missing.length > 1 ) { + var str = vars.format.locale.value.error.libs + , app = vars.format.locale.value.visualization[vars.type.value] + , and = vars.format.locale.value.ui.and + missing = stringList(missing,and) + vars.error.internal = stringFormat(str,app,missing) + } + else if ( missing.length === 1 ) { + var str = vars.format.locale.value.error.lib + , app = vars.format.locale.value.visualization[vars.type.value] + vars.error.internal = stringFormat(str,app,missing[0]) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check to see if the requested app supports the set shape + //---------------------------------------------------------------------------- + var shapes = vars.shape.accepted(vars); + if (!(shapes instanceof Array)) shapes = [shapes] + var shape = vars.shape.value; + + if (!shape || rejected(vars, shapes, shape, "shape")) { + vars.self.shape(shapes[0]); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check to see if the requested app supports the set "mode" + //---------------------------------------------------------------------------- + if ("modes" in vars.types[vars.type.value]) { + + var modes = vars.types[vars.type.value].modes + if (!(modes instanceof Array)) modes = [modes] + var mode = vars.type.mode.value + + if (!mode || rejected(vars, modes, mode, "mode")) { + vars.self.type({"mode": modes[0]}) + } + + } + + if ( vars.dev.value ) print.timeEnd("checking for errors") + +} + +},{"../../core/console/print.coffee":54,"../../core/fetch/text.js":68,"../../core/methods/rejected.coffee":93,"../../string/format.js":176,"../../string/list.coffee":177}],217:[function(require,module,exports){ +var edges = require("./shapes/edges.js"), + paths = require("./shapes/paths.js"), + flash = require("./ui/message.js"), + focusViz = require("./focus/viz.js"), + methodReset = require("../../core/methods/reset.coffee"), + print = require("../../core/console/print.coffee"), + shapeLabels = require("./shapes/labels.js"), + titleCase = require("../../string/title.coffee") + +var bounds = require("./zoom/bounds.coffee") +var labels = require("./zoom/labels.coffee") +var mouse = require("./zoom/mouse.coffee") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Finalize Visualization +//------------------------------------------------------------------------------ +module.exports = function(vars) { + + // Highlight focus nodes/edges + if (vars.draw.first) { + setTimeout(function(){ + focusViz(vars); + }, vars.draw.timing); + } + else { + focusViz(vars); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Zoom to fit bounds, if applicable + //---------------------------------------------------------------------------- + if (!vars.error.value) { + + var zoom = vars.zoom.viewport || vars.zoom.bounds + if (vars.types[vars.type.value].zoom && vars.zoom.value && zoom) { + + if ( vars.dev.value ) print.time("calculating zoom") + + if (vars.draw.first || vars.zoom.reset) { + bounds(vars, zoom, 0); + } + else if (vars.type.changed || vars.focus.changed || vars.height.changed || vars.width.changed || vars.nodes.changed || vars.legend.changed || vars.timeline.changed || vars.ui.changed) { + bounds(vars, zoom); + } + + if ( vars.dev.value ) print.timeEnd("calculating zoom") + + } + else { + vars.zoom.bounds = [[0,0],[vars.width.viz,vars.height.viz]] + vars.zoom.scale = 1 + bounds(vars) + } + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Resize/Reposition Overlay Rect for Mouse events + //---------------------------------------------------------------------------- + var w = vars.zoom.size ? vars.zoom.size.width : vars.width.viz, + h = vars.zoom.size ? vars.zoom.size.height : vars.height.viz, + x = vars.zoom.bounds ? vars.zoom.bounds[0][0] : 0, + y = vars.zoom.bounds ? vars.zoom.bounds[0][1] : 0 + + vars.g.overlay + .attr("width",w) + .attr("height",h) + .attr("x",x) + .attr("y",y) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create labels + //---------------------------------------------------------------------------- + if (!vars.error.value) { + if (vars.draw.update) { + if (vars.edges.path) { + paths(vars); + } + else { + edges(vars); + } + // if (vars.draw.timing || (!vars.types[vars.type.value].zoom && !vars.draw.timing)) { + shapeLabels(vars, "data"); + if (vars.edges.label && !vars.edges.path) { + setTimeout(function(){ + shapeLabels(vars, "edges"); + }, vars.draw.timing + 200); + } + // } + } + else if ((vars.labels.value || vars.labels.changed) && vars.types[vars.type.value].zoom && vars.zoom.value && vars.draw.timing) { + setTimeout(function(){ + labels(vars) + },vars.draw.timing) + } + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check for Errors + //---------------------------------------------------------------------------- + if (!vars.error.value) { + var reqs = vars.types[vars.type.value].requirements || [] + if (!(reqs instanceof Array)) reqs = [reqs] + var data_req = reqs.indexOf("data") >= 0 + if (!vars.error.internal) { + if ((!vars.data.viz || !vars.returned.nodes.length) && data_req) { + vars.error.internal = vars.format.locale.value.error.data + } + } + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Hide the previous app, if applicable + //---------------------------------------------------------------------------- + var prev = vars.type.previous + if (prev && vars.type.value != prev && vars.g.apps[prev]) { + if ( vars.dev.value ) print.time("hiding \"" + prev + "\"") + if (vars.draw.timing) { + vars.g.apps[prev].transition().duration(vars.draw.timing) + .attr("opacity",0) + } + else { + vars.g.apps[prev].attr("opacity",0) + } + if ( vars.dev.value ) print.timeEnd() + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Show the current app, data, and edges groups + //---------------------------------------------------------------------------- + if (!vars.error.value) { + var new_opacity = (data_req && vars.data.viz.length === 0) || + vars.error.internal || vars.error.value ? 0 : vars.focus.value.length && + vars.types[vars.type.value].zoom && vars.zoom.value ? + 1 - vars.tooltip.curtain.opacity : 1; + + var timing = vars.draw.timing; + + vars.group.transition().duration(timing) + .attr("opacity",new_opacity); + + vars.g.data.transition().duration(timing) + .attr("opacity",new_opacity); + + vars.g.edges.transition().duration(timing) + .attr("opacity",new_opacity); + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Display and reset internal_error, if applicable + //---------------------------------------------------------------------------- + if (vars.error.value) { + flash(vars, vars.error.value); + } + else if (vars.error.internal) { + vars.error.internal = titleCase(vars.error.internal); + print.warning(vars.error.internal); + flash(vars, vars.error.internal); + vars.error.internal = null; + } + else { + flash(vars); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Unfreeze controls and apply zoom behavior, if applicable + //---------------------------------------------------------------------------- + setTimeout(function(){ + + methodReset( vars ) + + if (vars.types[vars.type.value].zoom && vars.zoom.value) { + vars.g.zoom + .datum(vars) + .call(vars.zoom.behavior.on("zoom",mouse)) + if (!vars.zoom.scroll.value) { + vars.g.zoom + .on("mousewheel.zoom",null) + .on("MozMousePixelScroll.zoom",null) + .on("wheel.zoom",null) + } + if (!vars.zoom.click.value) { + vars.g.zoom.on("dblclick.zoom",null) + } + if (!vars.zoom.pan.value) { + vars.g.zoom + .on("mousedown.zoom",null) + .on("mousemove.zoom",null) + } + } + else { + vars.g.zoom + .call(vars.zoom.behavior.on("zoom",null)) + .on("dblclick.zoom",null) + .on("mousedown.zoom",null) + .on("mousemove.zoom",null) + .on("mousewheel.zoom",null) + .on("MozMousePixelScroll.zoom",null) + .on("touchstart.zoom",null) + .on("wheel.zoom",null) + } + + },vars.draw.timing) + +} + +},{"../../core/console/print.coffee":54,"../../core/methods/reset.coffee":95,"../../string/title.coffee":179,"./focus/viz.js":219,"./shapes/edges.js":229,"./shapes/labels.js":231,"./shapes/paths.js":233,"./ui/message.js":249,"./zoom/bounds.coffee":252,"./zoom/labels.coffee":254,"./zoom/mouse.coffee":255}],218:[function(require,module,exports){ +var createTooltip, fetchValue, print, removeTooltip; + +createTooltip = require("../tooltip/create.js"); + +fetchValue = require("../../../core/fetch/value.coffee"); + +print = require("../../../core/console/print.coffee"); + +removeTooltip = require("../../../tooltip/remove.coffee"); + +module.exports = function(vars) { + var data, focus, offset; + focus = vars.focus; + if (!vars.error.internal && focus.value.length === 1 && focus.value.length && !vars.small && focus.tooltip.value) { + if (vars.dev.value) { + print.time("drawing focus tooltip"); + } + data = vars.data.pool.filter(function(d) { + return fetchValue(vars, d, vars.id.value) === focus.value[0]; + }); + if (data.length >= 1) { + data = data[0]; + } else { + data = {}; + data[vars.id.value] = focus.value[0]; + } + offset = vars.labels.padding; + createTooltip({ + anchor: "top left", + arrow: false, + data: data, + fullscreen: false, + id: "visualization_focus", + length: "long", + maxheight: vars.height.viz - offset * 2, + mouseevents: true, + offset: 0, + vars: vars, + width: vars.tooltip.large, + x: vars.width.value - vars.margin.right - offset, + y: vars.margin.top + offset + }); + vars.width.viz -= vars.tooltip.large + offset * 2; + if (vars.dev.value) { + print.timeEnd("drawing focus tooltip"); + } + } else { + removeTooltip("visualization_focus"); + } +}; + + +},{"../../../core/console/print.coffee":54,"../../../core/fetch/value.coffee":69,"../../../tooltip/remove.coffee":206,"../tooltip/create.js":243}],219:[function(require,module,exports){ +var events = require("../../../client/pointer.coffee"), + ie = require("../../../client/ie.js"), + fetchValue = require("../../../core/fetch/value.coffee"), + print = require("../../../core/console/print.coffee"), + uniqueValues = require("../../../util/uniques.coffee") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates focus elements, if available +//------------------------------------------------------------------------------ +module.exports = function(vars) { + + vars.g.edge_focus + .selectAll("g") + .remove() + + vars.g.data_focus + .selectAll("g") + .remove() + + if (vars.focus.value.length && vars.types[vars.type.value].zoom && vars.zoom.value) { + + if ( vars.dev.value ) print.time("drawing focus elements") + + var edges = vars.g.edges.selectAll("g") + + if (edges.size() > 0) { + + edges.each(function(l){ + + var source = l[vars.edges.source][vars.id.value], + target = l[vars.edges.target][vars.id.value] + + if (source == vars.focus.value[0] || target == vars.focus.value[0]) { + var elem = vars.g.edge_focus.node().appendChild(this.cloneNode(true)) + d3.select(elem).datum(l).attr("opacity",1) + .selectAll("line, path").datum(l) + } + + }) + + + var marker = vars.edges.arrows.value + + vars.g.edge_focus.selectAll("line, path") + .attr("vector-effect","non-scaling-stroke") + .style("stroke",vars.color.focus) + .style("stroke-width",function(){ + if (ie && vars.types[vars.type.value].zoom) return 0; + return vars.edges.size.value ? d3.select(this).style("stroke-width") + : vars.data.stroke.width*2 + }) + .attr("marker-start",function(e){ + + var direction = vars.edges.arrows.direction.value + + if ("bucket" in e.d3plus) { + var d = "_"+e.d3plus.bucket + } + else { + var d = "" + } + + return direction == "source" && marker + ? "url(#d3plus_edge_marker_focus"+d+")" : "none" + + }) + .attr("marker-end",function(e){ + + var direction = vars.edges.arrows.direction.value + + if ("bucket" in e.d3plus) { + var d = "_"+e.d3plus.bucket + } + else { + var d = "" + } + + return direction == "target" && marker + ? "url(#d3plus_edge_marker_focus"+d+")" : "none" + + }) + + vars.g.edge_focus.selectAll("text") + .style("fill",vars.color.focus) + + } + + var focii = uniqueValues(vars.edges.connections(vars.focus.value[0],vars.id.value,true),vars.id.value, fetchValue, vars) + focii.push(vars.focus.value[0]) + + var x_bounds = [], y_bounds = [], x_buffer = [0], y_buffer = [0] + + var groups = vars.g.data.selectAll("g") + .each(function(d){ + if (focii.indexOf(d[vars.id.value]) >= 0) { + var elem = vars.g.data_focus.node().appendChild(this.cloneNode(true)) + var elem = d3.select(elem).datum(d).attr("opacity",1) + + if (vars.shape.value == "coordinates") { + + vars.zoom.viewport = vars.path.bounds(vars.zoom.coords[d.d3plus.id]) + + } + else if ("d3plus" in d) { + if ("x" in d.d3plus) { + x_bounds.push(d.d3plus.x) + } + if ("y" in d.d3plus) { + y_bounds.push(d.d3plus.y) + } + if ("r" in d.d3plus) { + x_buffer.push(d.d3plus.r) + y_buffer.push(d.d3plus.r) + } + else { + if ("width" in d.d3plus) { + x_buffer.push(d.d3plus.width/2) + } + if ("height" in d.d3plus) { + y_buffer.push(d.d3plus.height/2) + } + } + } + + for (e in events) { + var evt = d3.select(this).on(events[e]) + if (evt) { + elem.on(events[e],evt) + } + } + + } + }) + + if (x_bounds.length && y_bounds.length) { + + var xcoords = d3.extent(x_bounds), + ycoords = d3.extent(y_bounds), + xmax = d3.max(x_buffer), + ymax = d3.max(y_buffer) + + vars.zoom.viewport = [ + [xcoords[0]-xmax,ycoords[0]-ymax], + [xcoords[1]+xmax,ycoords[1]+ymax] + ] + + } + + vars.g.data_focus.selectAll("path") + .style("stroke-width", ie && vars.types[vars.type.value].zoom ? + 0 : vars.data.stroke.width * 2); + + if ( vars.dev.value ) print.timeEnd("drawing focus elements") + + } + else { + vars.zoom.viewport = false + } + +} + +},{"../../../client/ie.js":39,"../../../client/pointer.coffee":40,"../../../core/console/print.coffee":54,"../../../core/fetch/value.coffee":69,"../../../util/uniques.coffee":213}],220:[function(require,module,exports){ +var angles, largestRect, path2poly, shapeStyle; + +shapeStyle = require("./style.coffee"); + +largestRect = require("../../../geom/largestRect.coffee"); + +path2poly = require("../../../geom/path2poly.coffee"); + +angles = { + start: {}, + end: {} +}; + +module.exports = function(vars, selection, enter, exit) { + var arc, arcTween, data, newarc; + arc = d3.svg.arc().innerRadius(0).outerRadius(function(d) { + return d.d3plus.r; + }).startAngle(function(d) { + return d.d3plus.startAngle; + }).endAngle(function(d) { + return d.d3plus.endAngle; + }); + data = function(d) { + var poly, rect; + if (vars.labels.value) { + if (d.d3plus.label) { + d.d3plus_label = d.d3plus.label; + } else { + poly = path2poly(arc(d)); + rect = largestRect(poly, { + angle: 0 + }); + if (rect[0]) { + d.d3plus_label = { + w: rect[0].width, + h: rect[0].height, + x: rect[0].cx, + y: rect[0].cy + }; + } else { + delete d.d3plus_label; + } + } + } + return [d]; + }; + if (vars.draw.timing) { + newarc = d3.svg.arc().innerRadius(0).outerRadius(function(d) { + return d.d3plus.r; + }).startAngle(function(d) { + if (angles.start[d.d3plus.id] === void 0) { + angles.start[d.d3plus.id] = 0; + } + if (isNaN(angles.start[d.d3plus.id])) { + angles.start[d.d3plus.id] = d.d3plus.startAngle; + } + return angles.start[d.d3plus.id]; + }).endAngle(function(d) { + if (angles.end[d.d3plus.id] === void 0) { + angles.end[d.d3plus.id] = 0; + } + if (isNaN(angles.end[d.d3plus.id])) { + angles.end[d.d3plus.id] = d.d3plus.endAngle; + } + return angles.end[d.d3plus.id]; + }); + arcTween = function(arcs, newAngle) { + return arcs.attrTween("d", function(d) { + var e, interpolateE, interpolateS, s; + if (newAngle === void 0) { + s = d.d3plus.startAngle; + e = d.d3plus.endAngle; + } else if (newAngle === 0) { + s = 0; + e = 0; + } + interpolateS = d3.interpolate(angles.start[d.d3plus.id], s); + interpolateE = d3.interpolate(angles.end[d.d3plus.id], e); + return function(t) { + angles.start[d.d3plus.id] = interpolateS(t); + angles.end[d.d3plus.id] = interpolateE(t); + return newarc(d); + }; + }); + }; + enter.append("path").attr("class", "d3plus_data").call(shapeStyle, vars).attr("d", newarc); + selection.selectAll("path.d3plus_data").data(data).transition().duration(vars.draw.timing).call(shapeStyle, vars).call(arcTween); + exit.selectAll("path.d3plus_data").transition().duration(vars.draw.timing).call(arcTween, 0); + } else { + enter.append("path").attr("class", "d3plus_data"); + selection.selectAll("path.d3plus_data").data(data).call(shapeStyle, vars).attr("d", arc); + } +}; + + +},{"../../../geom/largestRect.coffee":162,"../../../geom/path2poly.coffee":164,"./style.coffee":237}],221:[function(require,module,exports){ +var fetchText = require("../../../core/fetch/text.js"), + fontSizes = require("../../../font/sizes.coffee"), + largestRect = require("../../../geom/largestRect.coffee"), + shapeStyle = require("./style.coffee"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "square" and "circle" shapes using svg:rect +//------------------------------------------------------------------------------ +module.exports = function(vars, selection, enter, exit) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // D3 area definition + //---------------------------------------------------------------------------- + var area = d3.svg.area() + .x(function(d) { return d.d3plus.x; }) + .y0(function(d) { return d.d3plus.y0; }) + .y1(function(d) { return d.d3plus.y; }) + .interpolate(vars.shape.interpolate.value); + + var startArea = d3.svg.area() + .x(function(d) { return d.d3plus.x; }) + .y0(function(d) { return d.d3plus.y0; }) + .y1(function(d) { return d.d3plus.y0; }) + .interpolate(vars.shape.interpolate.value); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Enter + //---------------------------------------------------------------------------- + enter.append("path").attr("class","d3plus_data") + .attr("d",function(d){ return startArea(d.values); }) + .call(shapeStyle,vars); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Update + //---------------------------------------------------------------------------- + + var style = { + "font-weight": vars.labels.font.weight, + "font-family": vars.labels.font.family.value + }; + + selection.selectAll("path.d3plus_data") + .data(function(d) { + + if (vars.labels.value && d.values.length > 1) { + + var max = d3.max(d.values, function(v){ + return v.d3plus.y0 - v.d3plus.y; + }), lr = false; + + if (max > vars.labels.font.size) { + + var tops = [], bottoms = [], names = fetchText(vars, d); + + d.values.forEach(function(v){ + tops.push([v.d3plus.x,v.d3plus.y]); + bottoms.push([v.d3plus.x,v.d3plus.y0]); + }); + tops = tops.concat(bottoms.reverse()); + + var ratio = null; + if (names.length) { + var size = fontSizes(names[0],style); + ratio = size[0].width/size[0].height; + } + + lr = largestRect(tops,{ + "angle": d3.range(-70, 71, 1), + "aspectRatio": ratio, + "tolerance": 0 + }); + + } + + if (lr && lr[0]) { + + var label = { + "w": ~~(lr[0].width), + "h": ~~(lr[0].height), + "x": ~~(lr[0].cx), + "y": ~~(lr[0].cy), + "angle": lr[0].angle*-1, + "padding": 2, + "names": names + } + + if (lr[0].angle !== 0) { + label.translate = { + "x":label.x, + "y":label.y + } + } + else { + label.translate = false + } + + if (label.w >= 10 && label.h >= 10) { + d.d3plus_label = label + } + + } + + } + + return [d]; + }) + + if (vars.draw.timing) { + selection.selectAll("path.d3plus_data") + .transition().duration(vars.draw.timing) + .attr("d",function(d){ return area(d.values) }) + .call(shapeStyle,vars) + } + else { + selection.selectAll("path.d3plus_data") + .attr("d",function(d){ return area(d.values) }) + .call(shapeStyle,vars) + } + +} + +},{"../../../core/fetch/text.js":68,"../../../font/sizes.coffee":104,"../../../geom/largestRect.coffee":162,"./style.coffee":237}],222:[function(require,module,exports){ +var fetchText = require("../../../core/fetch/text.js"), + largestRect = require("../../../geom/largestRect.coffee"), + shapeStyle = require("./style.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "square" and "circle" shapes using svg:rect +//------------------------------------------------------------------------------ +module.exports = function(vars,selection,enter,exit) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialize check scale on enter and exit. + //---------------------------------------------------------------------------- + function init(paths){ + paths.attr("transform", "scale(1)") + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Change scale of check on update. + //--------------------------------------------------------------------------- + function update(paths){ + paths.attr("transform", function(d){ + var smaller_dim = Math.min(d.d3plus.width, d.d3plus.height); + var scale = Math.floor(smaller_dim / 16); + return "scale("+scale+")"; + }) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Enter + //---------------------------------------------------------------------------- + enter.append("path").attr("class","d3plus_data") + .attr("d", "M5-6.844L3.594-5.407L-2,0.188l-1.594-1.594L-5-2.844L-7.844,0l1.438,1.406l3,3L-2,5.843l1.406-1.438l7-7L7.844-4L5-6.844z") + .call(init) + .call(shapeStyle,vars) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Update + //---------------------------------------------------------------------------- + selection.selectAll("path.d3plus_data") + .data(function(d) { + return [d]; + }) + + if (vars.draw.timing) { + selection.selectAll("path.d3plus_data") + .transition().duration(vars.draw.timing) + .call(update) + .call(shapeStyle,vars) + } + else { + selection.selectAll("path.d3plus_data") + .call(update) + .call(shapeStyle,vars) + } + +} + +},{"../../../core/fetch/text.js":68,"../../../geom/largestRect.coffee":162,"./style.coffee":237}],223:[function(require,module,exports){ +var fetchColor, fetchValue, lighter, segments; + +fetchValue = require("../../../core/fetch/value.coffee"); + +fetchColor = require("../../../core/fetch/color.coffee"); + +lighter = require("../../../color/lighter.coffee"); + +segments = require("./segments.coffee"); + +module.exports = function(d, vars, stroke) { + var active, shape, temp, total; + shape = d.d3plus.shape || vars.shape.value; + if (vars.shape.value === "line" && shape !== "circle") { + return "none"; + } else if (vars.shape.value === "area" || shape === "active" || vars.shape.value === "line") { + return fetchColor(vars, d); + } else if (shape === "temp") { + if (stroke) { + return fetchColor(vars, d); + } else { + return "url(#d3plus_hatch_" + d.d3plus.id + ")"; + } + } else if (d.d3plus["static"]) { + return lighter(fetchColor(vars, d), .75); + } + active = segments(vars, d, "active"); + temp = segments(vars, d, "temp"); + total = segments(vars, d, "total"); + if ((!vars.active.value && !vars.temp.value) || active === true || (active && total && active >= total && !temp) || (active && !total)) { + return fetchColor(vars, d); + } else if (vars.active.spotlight.value) { + return vars.color.missing; + } else { + return lighter(fetchColor(vars, d), .75); + } +}; + + +},{"../../../color/lighter.coffee":47,"../../../core/fetch/color.coffee":65,"../../../core/fetch/value.coffee":69,"./segments.coffee":236}],224:[function(require,module,exports){ +var copy, distance, fetchText, fontSizes, labels, largestRect, path2poly, shapeStyle; + +copy = require("../../../util/copy.coffee"); + +distance = require("../../../network/distance.coffee"); + +fetchText = require("../../../core/fetch/text.js"); + +fontSizes = require("../../../font/sizes.coffee"); + +largestRect = require("../../../geom/largestRect.coffee"); + +path2poly = require("../../../geom/path2poly.coffee"); + +shapeStyle = require("./style.coffee"); + +labels = {}; + +module.exports = function(vars, selection, enter, exit) { + var projection, size_change; + projection = d3.geo[vars.coords.projection.value](); + if (projection.center) { + projection.center(vars.coords.center); + } + if (!vars.zoom.scale) { + vars.zoom.scale = 1; + } + vars.zoom.area = 1 / vars.zoom.scale / vars.zoom.scale; + vars.path = d3.geo.path().projection(projection); + if (vars.draw.timing) { + selection.selectAll("path.d3plus_data").attr("d", vars.path).transition().duration(vars.draw.timing).call(shapeStyle, vars); + } else { + selection.selectAll("path.d3plus_data").attr("d", vars.path).call(shapeStyle, vars); + } + enter.append("path").attr("id", function(d) { + return d.id; + }).attr("class", "d3plus_data").attr("d", vars.path).call(shapeStyle, vars); + size_change = vars.old_height !== vars.height.viz || vars.height.changed || vars.old_width !== vars.width.viz || vars.width.changed; + vars.old_height = vars.height.viz; + vars.old_width = vars.width.viz; + if (vars.coords.changed || size_change || vars.coords.mute.changed || vars.coords.solo.changed || vars.type.changed || vars.text.changed || vars.coords.projection.changed || vars.labels.changed) { + vars.zoom.bounds = null; + vars.zoom.reset = true; + vars.zoom.coords = {}; + return selection.each(function(d) { + var areaM, areas, b, c, center, coords, dist_cutoff, dist_values, distances, i, j, largest, len, names, path, ratio, rect, reduced, ref, size, style; + if (vars.coords.simplify.value && d.geometry.coordinates.length > 1) { + distances = []; + areas = []; + areaM = 0; + largest = copy(d); + reduced = copy(d); + d.geometry.coordinates = d.geometry.coordinates.filter(function(c, i) { + var a; + reduced.geometry.coordinates = [c]; + a = vars.path.area(reduced); + if (a > 0) { + areas.push(a); + if (a > areaM) { + largest.geometry.coordinates = [c]; + areaM = a; + } + return true; + } else { + return false; + } + }); + center = vars.path.centroid(largest); + ref = d.geometry.coordinates; + for (i = j = 0, len = ref.length; j < len; i = ++j) { + c = ref[i]; + reduced.geometry.coordinates = [c]; + distances.push(distance(vars.path.centroid(reduced), center)); + } + dist_values = distances.reduce(function(arr, dist, i) { + if (dist) { + arr.push(areas[i] / dist); + } + return arr; + }, []); + dist_cutoff = d3.quantile(dist_values, vars.coords.threshold.value); + reduced.geometry.coordinates = d.geometry.coordinates.filter(function(c, i) { + var a, dist; + dist = distances[i]; + a = areas[i]; + return dist === 0 || a / dist >= dist_cutoff; + }); + coords = largest.geometry.coordinates[0]; + if (coords && largest.geometry.type === "MultiPolygon") { + coords = coords[0]; + largest.geometry.coordinates[0] = coords; + largest.geometry.type = "Polygon"; + } + } else { + reduced = d; + largest = d; + coords = d.geometry.coordinates[0]; + } + vars.zoom.coords[d.d3plus.id] = reduced; + delete d.d3plus_label; + if (vars.labels.value) { + names = fetchText(vars, d); + if (coords && names.length) { + path = path2poly(vars.path(largest)); + style = { + "font-weight": vars.labels.font.weight, + "font-family": vars.labels.font.family.value + }; + ratio = null; + if (names[0].split(" ").length === 1) { + size = fontSizes(names[0], style)[0]; + ratio = size.width / size.height; + } + rect = largestRect(path, { + angle: 0, + aspectRatio: ratio + }); + if (rect) { + rect = rect[0]; + d.d3plus_label = { + anchor: "middle", + valign: "center", + h: rect.height, + w: rect.width, + x: rect.cx, + y: rect.cy, + names: names + }; + } + } + } + labels[d.id] = d.d3plus_label; + b = vars.path.bounds(reduced); + if (!vars.zoom.bounds) { + return vars.zoom.bounds = b; + } else { + if (vars.zoom.bounds[0][0] > b[0][0]) { + vars.zoom.bounds[0][0] = b[0][0]; + } + if (vars.zoom.bounds[0][1] > b[0][1]) { + vars.zoom.bounds[0][1] = b[0][1]; + } + if (vars.zoom.bounds[1][0] < b[1][0]) { + vars.zoom.bounds[1][0] = b[1][0]; + } + if (vars.zoom.bounds[1][1] < b[1][1]) { + return vars.zoom.bounds[1][1] = b[1][1]; + } + } + }); + } else if (!vars.focus.value.length) { + vars.zoom.viewport = false; + return selection.each(function(d) { + return d.d3plus_label = labels[d.id]; + }); + } +}; + + +},{"../../../core/fetch/text.js":68,"../../../font/sizes.coffee":104,"../../../geom/largestRect.coffee":162,"../../../geom/path2poly.coffee":164,"../../../network/distance.coffee":168,"../../../util/copy.coffee":210,"./style.coffee":237}],225:[function(require,module,exports){ +var shapeStyle = require("./style.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "square" and "circle" shapes using svg:rect +//------------------------------------------------------------------------------ +module.exports = function(vars,selection,enter,exit) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialize check scale on enter and exit. + //---------------------------------------------------------------------------- + function init(paths){ + paths.attr("d", d3.svg.symbol().type("cross").size(10)) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Change scale of check on update. + //--------------------------------------------------------------------------- + function update(paths){ + paths.attr("d", d3.svg.symbol().type("cross").size(function(d){ + var smaller_dim = Math.min(d.d3plus.width, d.d3plus.height); + return d3.scale.pow().exponent(2)(smaller_dim/2); + })) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Enter + //---------------------------------------------------------------------------- + enter.append("path").attr("class","d3plus_data") + .call(init) + .call(shapeStyle,vars) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Update + //---------------------------------------------------------------------------- + selection.selectAll("path.d3plus_data") + .data(function(d) { + return [d]; + }) + + if (vars.draw.timing) { + selection.selectAll("path.d3plus_data") + .transition().duration(vars.draw.timing) + .call(update) + .call(shapeStyle,vars) + } + else { + selection.selectAll("path.d3plus_data") + .call(update) + .call(shapeStyle,vars) + } + +} + +},{"./style.coffee":237}],226:[function(require,module,exports){ +var shapeStyle = require("./style.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "square" and "circle" shapes using svg:rect +//------------------------------------------------------------------------------ +module.exports = function(vars,selection,enter,exit) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialize check scale on enter and exit. + //---------------------------------------------------------------------------- + function init(paths){ + paths.attr("d", d3.svg.symbol().type("diamond").size(10)) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Change scale of check on update. + //--------------------------------------------------------------------------- + function update(paths){ + paths.attr("d", d3.svg.symbol().type("diamond").size(function(d){ + var smaller_dim = Math.min(d.d3plus.width, d.d3plus.height); + return d3.scale.pow().exponent(2)(smaller_dim/2); + })) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Enter + //---------------------------------------------------------------------------- + enter.append("path").attr("class","d3plus_data") + .call(init) + .call(shapeStyle,vars) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Update + //---------------------------------------------------------------------------- + selection.selectAll("path.d3plus_data") + .data(function(d) { + return [d]; + }) + + if (vars.draw.timing) { + selection.selectAll("path.d3plus_data") + .transition().duration(vars.draw.timing) + .call(update) + .call(shapeStyle,vars) + } + else { + selection.selectAll("path.d3plus_data") + .call(update) + .call(shapeStyle,vars) + } + +} + +},{"./style.coffee":237}],227:[function(require,module,exports){ +var shapeStyle = require("./style.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "donut" shapes using svg:path with arcs +//------------------------------------------------------------------------------ +module.exports = function(vars,selection,enter,exit) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // In order to correctly animate each donut's size and arcs, we need to store + // it's previous values in a lookup object that does not get destroyed when + // redrawing the visualization. + //---------------------------------------------------------------------------- + if (!vars.arcs) { + vars.arcs = { + "donut": {}, + "active": {}, + "temp": {} + } + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // This is the main arc function that determines what values to use for each + // arc angle and radius. + //---------------------------------------------------------------------------- + var arc = d3.svg.arc() + .startAngle(0) + .endAngle(function(d){ + var a = vars.arcs[d.d3plus.shape][d.d3plus.id].a; + return a > Math.PI*2 ? Math.PI*2 : a; + }) + .innerRadius(function(d){ + if (d.d3plus.static) return 0; + var r = vars.arcs[d.d3plus.shape][d.d3plus.id].r; + return r * vars.data.donut.size; + }) + .outerRadius(function(d){ + return vars.arcs[d.d3plus.shape][d.d3plus.id].r; + }) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // This is the main "arcTween" function where all of the animation happens + // for each arc. + //---------------------------------------------------------------------------- + function size(path,mod,rad,ang) { + if (!mod) var mod = 0 + if (typeof rad != "number") var rad = undefined + if (typeof ang != "number") var ang = undefined + path.attrTween("d", function(d){ + if (rad == undefined) var r = d.d3plus.r ? d.d3plus.r : d3.max([d.d3plus.width,d.d3plus.height]) + else var r = rad + if (ang == undefined) var a = d.d3plus.segments[d.d3plus.shape] + else var a = ang + if (!vars.arcs[d.d3plus.shape][d.d3plus.id]) { + vars.arcs[d.d3plus.shape][d.d3plus.id] = {"r": 0} + vars.arcs[d.d3plus.shape][d.d3plus.id].a = Math.PI * 2 + } + var radius = d3.interpolate(vars.arcs[d.d3plus.shape][d.d3plus.id].r,r+mod), + angle = d3.interpolate(vars.arcs[d.d3plus.shape][d.d3plus.id].a,a) + return function(t) { + vars.arcs[d.d3plus.shape][d.d3plus.id].r = radius(t) + vars.arcs[d.d3plus.shape][d.d3plus.id].a = angle(t) + return arc(d) + } + }) + } + + function data(d) { + + if (d.d3plus.label) { + d.d3plus_label = d.d3plus.label; + } + else { + delete d.d3plus_label; + } + + return [d]; + } + + if (vars.draw.timing) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Exit + //---------------------------------------------------------------------------- + exit.selectAll("path.d3plus_data").transition().duration(vars.draw.timing) + .call(size,0,0) + .each("end",function(d){ + delete vars.arcs[d.d3plus.shape][d.d3plus.id]; + }); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Update + //---------------------------------------------------------------------------- + selection.selectAll("path.d3plus_data") + .data(data) + .transition().duration(vars.draw.timing) + .call(size) + .call(shapeStyle,vars); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Enter + //---------------------------------------------------------------------------- + enter.append("path") + .attr("class","d3plus_data") + .transition().duration(0) + .call(size,0,0) + .call(shapeStyle,vars) + .transition().duration(vars.draw.timing) + .call(size) + .call(shapeStyle,vars); + + } + else { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Exit + //---------------------------------------------------------------------------- + exit.selectAll("path.d3plus_data") + .each(function(d){ + delete vars.arcs[d.d3plus.shape][d.d3plus.id]; + }); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Enter + //---------------------------------------------------------------------------- + enter.append("path") + .attr("class","d3plus_data"); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Update + //---------------------------------------------------------------------------- + selection.selectAll("path.d3plus_data") + .data(data) + .call(size) + .call(shapeStyle,vars); + } + +}; + +},{"./style.coffee":237}],228:[function(require,module,exports){ +var child = require("../../../util/child.coffee"), + closest = require("../../../util/closest.coffee"), + createTooltip = require("../tooltip/create.js"), + events = require("../../../client/pointer.coffee"), + fetchValue = require("../../../core/fetch/value.coffee"), + fetchColor = require("../../../core/fetch/color.coffee"), + fetchText = require("../../../core/fetch/text.js"), + legible = require("../../../color/legible.coffee"), + print = require("../../../core/console/print.coffee"), + removeTooltip = require("../../../tooltip/remove.coffee"), + segments = require("./segments.coffee"), + shapeFill = require("./fill.js"), + stringStrip = require("../../../string/strip.js"), + touch = require("../../../client/touch.coffee"), + touchEvent = require("../zoom/propagation.coffee"), + uniqueValues = require("../../../util/uniques.coffee"), + validObject = require("../../../object/validate.coffee"), + zoomDirection = require("../zoom/direction.coffee"); + +var drawShape = { + "arc": require("./arc.coffee"), + "area": require("./area.js"), + "check": require("./check.js"), + "coordinates": require("./coordinates.coffee"), + "cross": require("./cross.js"), + "diamond": require("./diamond.js"), + "donut": require("./donut.js"), + "line": require("./line.js"), + "radial": require("./radial.coffee"), + "rect": require("./rect.coffee"), + "triangle_down": require("./triangle_down.js"), + "triangle_up": require("./triangle_up.js"), + "whisker": require("./whisker.coffee") +}; + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws the appropriate shape based on the data +//------------------------------------------------------------------------------ +module.exports = function(vars) { + + var data = vars.returned.nodes || [], + edges = vars.returned.edges || []; + + vars.draw.timing = data.length < vars.data.large && + edges.length < vars.edges.large ? + vars.timing.transitions : 0; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Match vars.shape types to their respective d3plus.shape functions. For + // example, both "square", and "circle" shapes use "rect" as their drawing + // class. + //---------------------------------------------------------------------------- + var shapeLookup = { + "arc": "arc", + "area": "area", + "check": "check", + "circle": "rect", + "coordinates": "coordinates", + "cross": "cross", + "donut": "donut", + "diamond": "diamond", + "line": "line", + "plus": "cross", + "radial": "radial", + "rect": "rect", + "square": "rect", + "triangle_down": "triangle_down", + "triangle": "triangle_up", + "triangle_up": "triangle_up", + "whisker": "whisker" + }; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Split the data by each shape type in the data. + //---------------------------------------------------------------------------- + var shapes = {}; + data.forEach(function(d){ + var s = d.d3plus && d.d3plus.shape ? d.d3plus.shape : vars.shape.value; + if (s in shapeLookup) { + if (d.d3plus) d.d3plus.shape = s + s = shapeLookup[s] + if (!shapes[s]) shapes[s] = [] + shapes[s].push(d) + } + }) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Resets the "id" of each data point to use with matching. + //---------------------------------------------------------------------------- + function id(d) { + + if (!d.d3plus.id) { + d.d3plus.id = ""; + for (var i = 0; i <= vars.depth.value; i++) { + d.d3plus.id += fetchValue(vars,d,vars.id.nesting[i])+"_" + } + + d.d3plus.id += shape; + + ["x", "y", "x2", "y2"].forEach(function(axis){ + if (vars[axis].scale.value == "discrete") { + var val = fetchValue(vars, d, vars[axis].value) + if (val.constructor === Date) val = val.getTime() + d.d3plus.id += "_"+val + } + }) + + if (d.d3plus.suffix) { + d.d3plus.id += "_" + d.d3plus.suffix; + } + + d.d3plus.id = stringStrip(d.d3plus.id) + } + + return d + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Transforms the positions and scale of each group. + //---------------------------------------------------------------------------- + function transform(g,grow) { + + var scales = vars.types[vars.type.value].scale, + scale = 1; + if (scales) { + if (validObject[scales] && vars.shape.value in scales) { + scale = scales[vars.shape.value]; + } + else if (typeof scales == "function") { + scale = scales(vars, vars.shape.value); + } + else if (typeof scales == "number") { + scale = scales; + } + } + + scale = grow ? scale : 1; + g.attr("transform", function(d){ + + if (["line", "area", "coordinates"].indexOf(shape) < 0) { + var x = d.d3plus.x || 0, y = d.d3plus.y || 0; + return "translate("+x+","+y+")scale("+scale+")"; + } + else { + return "scale("+scale+")"; + } + + }); + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Sets the class name for a group + //---------------------------------------------------------------------------- + function className(g) { + g + .attr("id", function(d){ + return "d3plus_group_" + d.d3plus.id; + }) + .attr("class", function(d){ + var c = vars.class.value ? " " + fetchValue(vars, d, vars.class.value) : ""; + return "d3plus_" + shape + c; + }); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Remove old groups + //---------------------------------------------------------------------------- + for (var s in shapeLookup) { + if (!(shapeLookup[s] in shapes) || d3.keys(shapes).length === 0) { + var oldShapes = vars.g.data.selectAll("g.d3plus_"+shapeLookup[s]); + if (vars.draw.timing) { + oldShapes + .transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove(); + } + else { + oldShapes + .remove(); + } + } + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialize arrays for labels and sizes + //---------------------------------------------------------------------------- + var labels = [], shares = []; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create groups by shape, apply data, and call specific shape drawing class. + //---------------------------------------------------------------------------- + for (var shape in shapes) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Bind Data to Groups + //-------------------------------------------------------------------------- + var selection = vars.g.data.selectAll("g.d3plus_"+shape) + .data(shapes[shape],function(d){ + + if (!d.d3plus) d.d3plus = {} + + if ( shape === "coordinates" ) { + d.d3plus.id = d.id + return d.id + } + + if ( !d.d3plus.id ) { + + if (d.values) { + + d.values.forEach(function(v){ + v = id(v) + v.d3plus.shape = "circle" + }) + d.d3plus.id = d.key + + } + else { + + d = id(d) + + if (!d.d3plus.segments) { + + d.d3plus.segments = {"donut": Math.PI*2} + var active = segments(vars, d, "active"), + temp = segments(vars, d, "temp"), + total = segments(vars, d, "total"); + + if (total) { + if (active) { + d.d3plus.segments.active = (active/total) * (Math.PI * 2) + } + else { + d.d3plus.segments.active = 0 + } + if (temp) { + d.d3plus.segments.temp = ((temp/total) * (Math.PI * 2)) + d.d3plus.segments.active + } + else { + d.d3plus.segments.temp = 0 + } + } + + } + + } + + } + + return d.d3plus ? d.d3plus.id : false; + + }) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Groups Exit + //-------------------------------------------------------------------------- + if (vars.draw.timing) { + var exit = selection.exit() + .transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove() + } + else { + var exit = selection.exit() + .remove() + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Existing Groups Update + //-------------------------------------------------------------------------- + if (vars.draw.timing) { + selection + .transition().duration(vars.draw.timing) + .call(transform) + .call(className); + } + else { + selection.call(transform).call(className); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Groups Enter + //-------------------------------------------------------------------------- + var opacity = vars.draw.timing ? 0 : 1 + var enter = selection.enter().append("g") + .attr("opacity",opacity) + .call(transform) + .call(className); + + if (vars.draw.timing) { + enter.transition().duration(vars.draw.timing) + .attr("opacity",1) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // All Groups Sort Order + //-------------------------------------------------------------------------- + selection.order() + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Draw appropriate graphics inside of each group + //-------------------------------------------------------------------------- + if ( vars.dev.value ) print.time("drawing \"" + shape + "\" shapes") + drawShape[shape]( vars , selection , enter , exit , transform ) + if ( vars.dev.value ) print.timeEnd("drawing \"" + shape + "\" shapes") + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check for active and temp fills for rects and donuts + //-------------------------------------------------------------------------- + if (["rect","donut"].indexOf(shape) >= 0 && vars.types[vars.type.value].fill) { + if ( vars.dev.value ) print.time("filling \"" + shape + "\" shapes") + shapeFill( vars , selection , enter , exit , transform ) + if ( vars.dev.value ) print.timeEnd("filling \"" + shape + "\" shapes") + } + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Function to Update Edges + //---------------------------------------------------------------------------- + function edge_update(d) { + + if (d && vars.g.edges.selectAll("g").size() > 0) { + + vars.g.edge_hover + .selectAll("*") + .remove() + + vars.g.edges.selectAll("g") + .each(function(l){ + + var id = d[vars.id.value], + source = l[vars.edges.source][vars.id.value], + target = l[vars.edges.target][vars.id.value]; + + if (source == id || source == "left_" + id || source == "right_" + id || + target == id || target == "left_" + id || target == "right_" + id) { + var elem = vars.g.edge_hover.node().appendChild(this.cloneNode(true)) + d3.select(elem).datum(l).attr("opacity",1) + .selectAll("line, path").datum(l) + } + + }) + + + var marker = vars.edges.arrows.value + + vars.g.edge_hover + .attr("opacity",0) + .selectAll("line, path") + .style("stroke",vars.color.primary) + .style("stroke-width",function(d){ + if (vars.edges.path && d.dy) { + return Math.max(1, d.dy); + } + return vars.edges.size.value ? d3.select(this).style("stroke-width") + : vars.data.stroke.width*2 + }) + .attr("marker-start",function(e){ + + var direction = vars.edges.arrows.direction.value + + if ("bucket" in e.d3plus) { + var d = "_"+e.d3plus.bucket + } + else { + var d = "" + } + + return direction == "source" && marker + ? "url(#d3plus_edge_marker_highlight"+d+")" : "none" + + }) + .attr("marker-end",function(e){ + + var direction = vars.edges.arrows.direction.value + + if ("bucket" in e.d3plus) { + var d = "_"+e.d3plus.bucket + } + else { + var d = "" + } + + return direction == "target" && marker + ? "url(#d3plus_edge_marker_highlight"+d+")" : "none" + + }) + + + vars.g.edge_hover.selectAll("text") + .style("fill",vars.color.primary) + + if (vars.draw.timing) { + + vars.g.edge_hover + .transition().duration(vars.timing.mouseevents) + .attr("opacity",1) + + vars.g.edges + .transition().duration(vars.timing.mouseevents) + .attr("opacity",0.5) + + } + else { + + vars.g.edge_hover + .attr("opacity",1) + + } + + } + else { + + if (vars.draw.timing) { + + vars.g.edge_hover + .transition().duration(vars.timing.mouseevents) + .attr("opacity",0) + .transition() + .selectAll("*") + .remove() + + vars.g.edges + .transition().duration(vars.timing.mouseevents) + .attr("opacity",1) + + } + else { + + vars.g.edge_hover + .selectAll("*") + .remove() + + } + + } + + } + + edge_update() + + if (vars.tooltip.value) { + + vars.g.data.selectAll("g") + .on(events.over,function(d){ + + if (touch) touchEvent(vars, d3.event); + + if (!d3.event.buttons && vars.mouse.value && vars.mouse.over.value && !vars.draw.frozen && (!d.d3plus || !d.d3plus.static)) { + + var defaultClick = typeof vars.mouse.over.value !== "function"; + if (typeof vars.mouse.over.value === "function") { + defaultClick = vars.mouse.over.value(d, vars.self); + } + if (defaultClick) { + + var zoomDir = zoomDirection(d.d3plus_data || d, vars) + var pointer = typeof vars.mouse.viz === "function" || + typeof vars.mouse.viz[events.click] === "function" || + (vars.zoom.value && (vars.types[vars.type.value].zoom || + (d.d3plus.threshold && d.d3plus.merged) || + zoomDir === 1 || + (zoomDir === -1 && vars.history.states.length && !vars.tooltip.value.long))); + + d3.select(this) + .style("cursor", pointer ? "pointer" : "auto") + .transition().duration(vars.timing.mouseevents) + .call(transform,true) + + d3.select(this).selectAll(".d3plus_data") + .transition().duration(vars.timing.mouseevents) + .attr("opacity",1) + + vars.covered = false + + if (d.values && vars.axes.discrete) { + + var index = vars.axes.discrete === "x" ? 0 : 1 + , mouse = d3.mouse(vars.container.value.node())[index] + , positions = uniqueValues(d.values,function(x){return x.d3plus[vars.axes.discrete]}) + , match = closest(positions,mouse) + + d.d3plus_data = d.values[positions.indexOf(match)] + d.d3plus = d.values[positions.indexOf(match)].d3plus + + } + + var tooltip_data = d.d3plus_data ? d.d3plus_data : d + + createTooltip({ + "vars": vars, + "data": tooltip_data + }) + + if (typeof vars.mouse.viz == "function") { + vars.mouse.viz(d.d3plus_data || d, vars) + } + else if (vars.mouse.viz[events.over]) { + vars.mouse.viz[events.over](d.d3plus_data || d, vars) + } + + edge_update(d) + + } + + } + else { + removeTooltip(vars.type.value); + } + + }) + .on(events.move,function(d){ + + if (touch) touchEvent(vars, d3.event); + + if (!d3.event.buttons && vars.mouse.value && vars.mouse.move.value && !vars.draw.frozen && (!d.d3plus || !d.d3plus.static)) { + + var defaultClick = typeof vars.mouse.move.value !== "function"; + if (typeof vars.mouse.move.value === "function") { + defaultClick = vars.mouse.move.value(d, vars.self); + } + if (defaultClick) { + + var zoomDir = zoomDirection(d.d3plus_data || d, vars) + var pointer = typeof vars.mouse.viz === "function" || + typeof vars.mouse.viz[events.click] === "function" || + (vars.zoom.value && (vars.types[vars.type.value].zoom || + (d.d3plus.threshold && d.d3plus.merged) || + zoomDir === 1 || + (zoomDir === -1 && vars.history.states.length && !vars.tooltip.value.long))); + + + d3.select(this).style("cursor", pointer ? "pointer" : "auto"); + + // vars.covered = false + var tooltipType = vars.types[vars.type.value].tooltip || "follow" + + if (d.values && vars.axes.discrete) { + + var index = vars.axes.discrete === "x" ? 0 : 1 + , mouse = d3.mouse(vars.container.value.node())[index] + , positions = uniqueValues(d.values,function(x){return x.d3plus[vars.axes.discrete]}) + , match = closest(positions,mouse) + + d.d3plus_data = d.values[positions.indexOf(match)] + d.d3plus = d.values[positions.indexOf(match)].d3plus + + } + + var tooltip_data = d.d3plus_data ? d.d3plus_data : d + createTooltip({ + "vars": vars, + "data": tooltip_data + }) + + if (typeof vars.mouse.viz == "function") { + vars.mouse.viz(d.d3plus_data || d, vars) + } + else if (vars.mouse.viz[events.move]) { + vars.mouse.viz[events.move](d.d3plus_data || d, vars) + } + + } + + } + else { + removeTooltip(vars.type.value); + } + + }) + .on(events.out,function(d){ + + if (touch) touchEvent(vars, d3.event); + + if (!d3.event.buttons && vars.mouse.value && vars.mouse.out.value) { + + var defaultClick = typeof vars.mouse.out.value !== "function"; + if (typeof vars.mouse.out.value === "function") { + defaultClick = vars.mouse.out.value(d, vars.self); + } + if (defaultClick) { + + var childElement = child(this,d3.event.toElement) + + if (!childElement && !vars.draw.frozen && (!d.d3plus || !d.d3plus.static)) { + + d3.select(this) + .transition().duration(vars.timing.mouseevents) + .call(transform) + + d3.select(this).selectAll(".d3plus_data") + .transition().duration(vars.timing.mouseevents) + .attr("opacity",vars.data.opacity) + + if (!vars.covered) { + removeTooltip(vars.type.value) + } + + if (typeof vars.mouse.viz == "function") { + vars.mouse.viz(d.d3plus_data || d, vars) + } + else if (vars.mouse.viz[events.out]) { + vars.mouse.viz[events.out](d.d3plus_data || d, vars) + } + + edge_update() + + } + + } + + } + else { + removeTooltip(vars.type.value); + } + + }) + + } + else { + + var mouseEvent = function() { + touchEvent(vars, d3.event) + } + + vars.g.data.selectAll("g") + .on(events.over, mouseEvent) + .on(events.move, mouseEvent) + .on(events.out , mouseEvent) + + } + + d3.select(window).on("scroll.d3plus", function(){ + removeTooltip(vars.type.value); + }); + + vars.g.data.selectAll("g") + .on(events.click,function(d){ + + if (!(vars.mouse.viz && vars.mouse.viz.click === false) && vars.mouse.value && vars.mouse.click.value && !d3.event.defaultPrevented && !vars.draw.frozen && (!d.d3plus || !d.d3plus.static)) { + + var defaultClick = typeof vars.mouse.click.value !== "function"; + if (typeof vars.mouse.click.value === "function") { + defaultClick = vars.mouse.click.value(d, vars.self); + } + if (defaultClick) { + + if (d.values && vars.axes.discrete) { + + var index = vars.axes.discrete === "x" ? 0 : 1 + , mouse = d3.mouse(vars.container.value.node())[index] + , positions = uniqueValues(d.values,function(x){return x.d3plus[vars.axes.discrete]}) + , match = closest(positions,mouse) + + d.d3plus_data = d.values[positions.indexOf(match)] + d.d3plus = d.values[positions.indexOf(match)].d3plus + + } + + if (typeof vars.mouse.viz == "function") { + vars.mouse.viz(d.d3plus_data || d, vars) + } + else if (vars.mouse.viz[events.out]) { + vars.mouse.viz[events.out](d.d3plus_data || d, vars) + } + else if (vars.mouse.viz[events.click]) { + vars.mouse.viz[events.click](d.d3plus_data || d, vars) + } + + var depth_delta = zoomDirection(d.d3plus_data || d, vars) + , previous = vars.id.solo.value + , title = fetchText(vars,d)[0] + , color = legible(fetchColor(vars,d)) + , prev_sub = vars.title.sub.value || false + , prev_color = vars.title.sub.font.color + , prev_total = vars.title.total.font.color + + if (d.d3plus.threshold && d.d3plus.merged && vars.zoom.value) { + + vars.history.states.push(function(){ + + vars.self + .id({"solo": previous}) + .title({ + "sub": { + "font": { + "color": prev_color + }, + "value": prev_sub + }, + "total": { + "font": { + "color": prev_total + } + } + }) + .draw() + + }) + + vars.self + .id({"solo": previous.concat(uniqueValues(d.d3plus.merged, vars.id.value, fetchValue, vars))}) + .title({ + "sub": { + "font": { + "color": color + }, + "value": title + }, + "total": { + "font": { + "color": color + } + } + }) + .draw() + + } + else if (depth_delta === 1 && vars.zoom.value) { + + var id = fetchValue(vars, d.d3plus_data || d, vars.id.value) + + vars.history.states.push(function(){ + + vars.self + .depth(vars.depth.value-1) + .id({"solo": previous}) + .title({ + "sub": { + "font": { + "color": prev_color + }, + "value": prev_sub + }, + "total": { + "font": { + "color": prev_total + } + } + }) + .draw() + + }) + + vars.self + .depth(vars.depth.value+1) + .id({"solo": previous.concat(id)}) + .title({ + "sub": { + "font": { + "color": color + }, + "value": title + }, + "total": { + "font": { + "color": color + } + } + }) + .draw() + + } + else if (depth_delta === -1 && vars.zoom.value && + vars.history.states.length && !vars.tooltip.value.long) { + + vars.history.back() + + } + else if (vars.types[vars.type.value].zoom && vars.zoom.value) { + + edge_update() + + d3.select(this) + .transition().duration(vars.timing.mouseevents) + .call(transform) + + d3.select(this).selectAll(".d3plus_data") + .transition().duration(vars.timing.mouseevents) + .attr("opacity",vars.data.opacity) + + removeTooltip(vars.type.value) + vars.draw.update = false + + if (!d || d[vars.id.value] == vars.focus.value[0]) { + vars.self.focus(false).draw() + } + else { + vars.self.focus(d[vars.id.value]).draw() + } + + } + else if (vars.types[vars.type.value].requirements.indexOf("focus") < 0) { + + edge_update() + + var tooltip_data = d.d3plus_data ? d.d3plus_data : d + + createTooltip({ + "vars": vars, + "data": tooltip_data + }) + + } + + } + + } + + }) + +} + +},{"../../../client/pointer.coffee":40,"../../../client/touch.coffee":45,"../../../color/legible.coffee":46,"../../../core/console/print.coffee":54,"../../../core/fetch/color.coffee":65,"../../../core/fetch/text.js":68,"../../../core/fetch/value.coffee":69,"../../../object/validate.coffee":175,"../../../string/strip.js":178,"../../../tooltip/remove.coffee":206,"../../../util/child.coffee":208,"../../../util/closest.coffee":209,"../../../util/uniques.coffee":213,"../tooltip/create.js":243,"../zoom/direction.coffee":253,"../zoom/propagation.coffee":256,"./arc.coffee":220,"./area.js":221,"./check.js":222,"./coordinates.coffee":224,"./cross.js":225,"./diamond.js":226,"./donut.js":227,"./fill.js":230,"./line.js":232,"./radial.coffee":234,"./rect.coffee":235,"./segments.coffee":236,"./triangle_down.js":238,"./triangle_up.js":239,"./whisker.coffee":240}],229:[function(require,module,exports){ +var buckets = require("../../../util/buckets.coffee"), + offset = require("../../../geom/offset.coffee"); + +module.exports = function(vars) { + + var edges = vars.returned.edges || [], + scale = vars.zoom.behavior.scaleExtent()[0]; + + if (typeof vars.edges.size.value === "string") { + + var strokeDomain = d3.extent(edges, function(e){ + return e[vars.edges.size.value]; + }), + maxSize = d3.min(vars.returned.nodes || [], function(n){ + return n.d3plus.r; + }) * (vars.edges.size.scale * 2); + + vars.edges.scale = d3.scale.sqrt() + .domain(strokeDomain) + .range([vars.edges.size.min,maxSize*scale]); + + } + else { + + var defaultWidth = typeof vars.edges.size.value == "number" ? + vars.edges.size.value : vars.edges.size.min; + + vars.edges.scale = function(){ + return defaultWidth; + }; + + } + + var o = vars.edges.opacity.value; + var o_type = typeof o; + + if (vars.edges.opacity.changed && o_type === "string") { + vars.edges.opacity.scale.value + .domain(d3.extent(edges, function(d){ + return d[o]; + })) + .range([vars.edges.opacity.min.value,1]); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialization of Lines + //---------------------------------------------------------------------------- + function init(l) { + + l + .attr("opacity", 0) + .style("stroke-width",0) + .style("stroke",vars.background.value) + .style("fill","none"); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Styling of Lines + //---------------------------------------------------------------------------- + function style(edges) { + + var marker = vars.edges.arrows.value; + + edges + .attr("opacity", function(d){ + return o_type === "number" ? o : + o_type === "function" ? o(d, vars) : + vars.edges.opacity.scale.value(d[o]); + }) + .style("stroke-width",function(e){ + return vars.edges.scale(e[vars.edges.size.value]); + }) + .style("stroke",vars.edges.color) + .attr("marker-start",function(e){ + + var direction = vars.edges.arrows.direction.value; + + if ("bucket" in e.d3plus) { + var d = "_"+e.d3plus.bucket; + } + else { + var d = ""; + } + + return direction == "source" && marker + ? "url(#d3plus_edge_marker_default"+d+")" : "none" + + }) + .attr("marker-end",function(e){ + + var direction = vars.edges.arrows.direction.value + + if ("bucket" in e.d3plus) { + var d = "_"+e.d3plus.bucket + } + else { + var d = "" + } + + return direction == "target" && marker + ? "url(#d3plus_edge_marker_default"+d+")" : "none" + + }) + .attr("vector-effect","non-scaling-stroke") + .attr("pointer-events","none") + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Positioning of Lines + //---------------------------------------------------------------------------- + function line(l) { + l + .attr("x1",function(d){ + return d[vars.edges.source].d3plus.edges[d[vars.edges.target][vars.id.value]].x; + }) + .attr("y1",function(d){ + return d[vars.edges.source].d3plus.edges[d[vars.edges.target][vars.id.value]].y; + }) + .attr("x2",function(d){ + return d[vars.edges.target].d3plus.edges[d[vars.edges.source][vars.id.value]].x; + }) + .attr("y2",function(d){ + return d[vars.edges.target].d3plus.edges[d[vars.edges.source][vars.id.value]].y; + }); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Positioning of Splines + //---------------------------------------------------------------------------- + var curve = d3.svg.line().interpolate(vars.edges.interpolate.value); + + function spline(l) { + l + .attr("d", function(d) { + + return curve(d.d3plus.spline); + + }); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Calculates and Draws Label for edge + //---------------------------------------------------------------------------- + function label(d) { + + delete d.d3plus_label + + if (vars.g.edges.selectAll("line, path").size() < vars.edges.large && vars.edges.label && d[vars.edges.label]) { + + if ("spline" in d.d3plus) { + + var length = this.getTotalLength(), + center = this.getPointAtLength(length/2), + prev = this.getPointAtLength((length/2)-(length*.1)), + next = this.getPointAtLength((length/2)+(length*.1)), + radians = Math.atan2(next.y-prev.y,next.x-prev.x), + angle = radians*(180/Math.PI), + bounding = this.parentNode.getBBox(), + width = length*.8, + x = center.x, + y = center.y + + } + else { + + var bounds = this.getBBox(), + source = d[vars.edges.source], + target = d[vars.edges.target], + start = {"x": source.d3plus.edges[target[vars.id.value]].x, "y": source.d3plus.edges[target[vars.id.value]].y}, + end = {"x": target.d3plus.edges[source[vars.id.value]].x, "y": target.d3plus.edges[source[vars.id.value]].y}, + xdiff = end.x-start.x, + ydiff = end.y-start.y, + center = {"x": end.x-(xdiff)/2, "y": end.y-(ydiff)/2}, + radians = Math.atan2(ydiff,xdiff), + angle = radians*(180/Math.PI), + length = Math.sqrt((xdiff*xdiff)+(ydiff*ydiff)), + width = length, + x = center.x, + y = center.y + + } + + width += vars.labels.padding*2 + + var m = 0 + if (vars.edges.arrows.value) { + m = typeof vars.edges.arrows.value === "number" + ? vars.edges.arrows.value : 8 + m = m/vars.zoom.behavior.scaleExtent()[1] + width -= m*2 + } + + if (angle < -90 || angle > 90) { + angle -= 180 + } + + if (width*vars.zoom.behavior.scaleExtent()[0] > 20) { + + d.d3plus_label = { + "x": x, + "y": y, + "translate": {"x": x, "y": y}, + "w": width, + "h": 15+vars.labels.padding*2, + "angle": angle, + "anchor": "middle", + "valign": "center", + "color": vars.edges.color, + "resize": false, + "names": [vars.format.value(d[vars.edges.label])], + "background": 1 + } + + } + + } + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Enter/update/exit the Arrow Marker + //---------------------------------------------------------------------------- + var markerData = vars.edges.arrows.value ? typeof vars.edges.size.value == "string" + ? [ "default_0", "default_1", "default_2", + "highlight_0", "highlight_1", "highlight_2", + "focus_0", "focus_1", "focus_2" ] + : [ "default", "highlight", "focus" ] : [] + + if (typeof vars.edges.size.value == "string") { + var b = buckets(vars.edges.scale.range(),4) + , markerSize = [] + for (var i = 0; i < 3; i++) { + markerSize.push(b[i+1]+(b[1]-b[0])*(i+2)*2) + } + } + else { + var m = typeof vars.edges.arrows.value === "number" + ? vars.edges.arrows.value : 8 + + var markerSize = typeof vars.edges.size.value === "number" + ? vars.edges.size.value/m : m + } + + var marker = vars.defs.selectAll(".d3plus_edge_marker") + .data(markerData, String) + + var marker_style = function(path) { + path + .attr("d",function(id){ + + var depth = id.split("_") + + if (depth.length == 2 && vars.edges.scale) { + depth = parseInt(depth[1]) + var m = markerSize[depth] + } + else { + var m = markerSize + } + + if (vars.edges.arrows.direction.value == "target") { + return "M 0,-"+m/2+" L "+m*.85+",0 L 0,"+m/2+" L 0,-"+m/2 + } + else { + return "M 0,-"+m/2+" L -"+m*.85+",0 L 0,"+m/2+" L 0,-"+m/2 + } + }) + .attr("fill",function(d){ + + var type = d.split("_")[0] + + if (type == "default") { + return vars.edges.color + } + else if (type == "focus") { + return vars.color.focus + } + else { + return vars.color.primary + } + }) + .attr("transform","scale("+1/scale+")") + } + + if (vars.draw.timing) { + marker.exit().transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove() + + marker.select("path").transition().duration(vars.draw.timing) + .attr("opacity",1) + .call(marker_style) + } + else { + marker.exit().remove() + + marker.select("path") + .attr("opacity",1) + .call(marker_style) + } + + var opacity = vars.draw.timing ? 0 : 1 + var enter = marker.enter().append("marker") + .attr("id",function(d){ + return "d3plus_edge_marker_"+d + }) + .attr("class","d3plus_edge_marker") + .attr("orient","auto") + .attr("markerUnits","userSpaceOnUse") + .style("overflow","visible") + .append("path") + .attr("opacity",opacity) + .attr("vector-effect","non-scaling-stroke") + .call(marker_style) + + if (vars.draw.timing) { + enter.transition().duration(vars.draw.timing) + .attr("opacity",1) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Bind "edges" data to lines in the "edges" group + //---------------------------------------------------------------------------- + var strokeBuckets = typeof vars.edges.size.value == "string" + ? buckets(vars.edges.scale.domain(),4) + : null + , direction = vars.edges.arrows.direction.value + + var line_data = edges.filter(function(l){ + + if (!l.d3plus) l.d3plus = {} + + l.d3plus.id = "edge_"+l[vars.edges.source][vars.id.value]+"_"+l[vars.edges.target][vars.id.value] + + if ( l.d3plus.spline !== true ) { + + if (strokeBuckets) { + var size = l[vars.edges.size.value] + l.d3plus.bucket = size < strokeBuckets[1] ? 0 + : size < strokeBuckets[2] ? 1 : 2 + var marker = markerSize[l.d3plus.bucket]*.85/scale + } + else { + delete l.d3plus.bucket + var marker = markerSize*.85/scale + } + + var source = l[vars.edges.source] + , target = l[vars.edges.target] + + if (!source.d3plus || !target.d3plus) return false + + var sourceAngle = Math.atan2( source.d3plus.y - target.d3plus.y + , source.d3plus.x - target.d3plus.x ) + , targetAngle = Math.atan2( target.d3plus.y - source.d3plus.y + , target.d3plus.x - source.d3plus.x ) + , sourceRadius = direction == "source" && vars.edges.arrows.value + ? source.d3plus.r + marker + : source.d3plus.r + , targetRadius = direction == "target" && vars.edges.arrows.value + ? target.d3plus.r + marker + : target.d3plus.r + , sourceOffset = offset( sourceAngle + , sourceRadius + , vars.shape.value ) + , targetOffset = offset( targetAngle + , targetRadius + , vars.shape.value ) + + if (!("edges" in source.d3plus)) source.d3plus.edges = {} + source.d3plus.edges[target[vars.id.value]] = { + "x": source.d3plus.x - sourceOffset.x, + "y": source.d3plus.y - sourceOffset.y + } + + if (!("edges" in target.d3plus)) target.d3plus.edges = {} + target.d3plus.edges[source[vars.id.value]] = { + "x": target.d3plus.x - targetOffset.x, + "y": target.d3plus.y - targetOffset.y + } + + return true + } + + return false + + }) + + var lines = vars.g.edges.selectAll("g.d3plus_edge_line") + .data(line_data,function(d){ + + return d.d3plus.id + + }) + + var spline_data = edges.filter(function(l){ + + if (l.d3plus.spline) { + + if (strokeBuckets) { + var size = l[vars.edges.size.value] + l.d3plus.bucket = size < strokeBuckets[1] ? 0 + : size < strokeBuckets[2] ? 1 : 2 + var marker = markerSize[l.d3plus.bucket]*.85/scale + } + else { + delete l.d3plus.bucket + var marker = markerSize*.85/scale + } + + var source = l[vars.edges.source] + , target = l[vars.edges.target] + , sourceEdge = source.d3plus.edges ? source.d3plus.edges[target[vars.id.value]] || {} : {} + , targetEdge = target.d3plus.edges ? target.d3plus.edges[source[vars.id.value]] || {} : {} + , sourceMod = vars.edges.arrows.value && direction == "source" ? marker : 0 + , targetMod = vars.edges.arrows.value && direction == "target" ? marker : 0 + , angleTweak = 0.1 + , sourceTweak = source.d3plus.x > target.d3plus.x ? 1-angleTweak : 1+angleTweak + , targetTweak = source.d3plus.x > target.d3plus.x ? 1+angleTweak : 1-angleTweak + , sourceAngle = typeof sourceEdge.angle === "number" ? sourceEdge.angle + : Math.atan2( source.d3plus.y - target.d3plus.y + , source.d3plus.x - target.d3plus.x ) * sourceTweak + , sourceOffset = offset(sourceAngle, source.d3plus.r + sourceMod, vars.shape.value ) + , targetAngle = typeof targetEdge.angle === "number" ? targetEdge.angle + : Math.atan2( target.d3plus.y - source.d3plus.y + , target.d3plus.x - source.d3plus.x ) * targetTweak + , targetOffset = offset(targetAngle, target.d3plus.r + targetMod, vars.shape.value ) + , start = [source.d3plus.x-sourceOffset.x, source.d3plus.y-sourceOffset.y] + , startOffset = sourceEdge.offset ? offset(sourceAngle,sourceEdge.offset) : false + , startPoint = startOffset ? [start[0]-startOffset.x,start[1]-startOffset.y] : start + , end = [target.d3plus.x-targetOffset.x, target.d3plus.y-targetOffset.y] + , endOffset = targetEdge.offset ? offset(targetAngle,targetEdge.offset) : false + , endPoint = endOffset ? [end[0]-endOffset.x,end[1]-endOffset.y] : end + , xd = endPoint[0] - startPoint[0] + , yd = endPoint[1] - startPoint[1] + , sourceDistance = typeof sourceEdge.radius === "number" ? sourceEdge.radius : Math.sqrt(xd*xd+yd*yd)/4 + , targetDistance = typeof targetEdge.radius === "number" ? targetEdge.radius : Math.sqrt(xd*xd+yd*yd)/4 + , startAnchor = offset(sourceAngle,sourceDistance-source.d3plus.r-sourceMod*2) + , endAnchor = offset(targetAngle,targetDistance-target.d3plus.r-targetMod*2) + + l.d3plus.spline = [ start, end ] + var testAngle = Math.abs(Math.atan2( source.d3plus.y - target.d3plus.y + , source.d3plus.x - target.d3plus.x )).toFixed(5) + , testStart = Math.abs(sourceAngle).toFixed(5) + , testEnd = Math.abs(targetAngle - Math.PI).toFixed(5) + + if (testStart !== testEnd || [testStart,testEnd].indexOf(testAngle) < 0) { + + l.d3plus.spline.splice(1,0,[startPoint[0]-startAnchor.x,startPoint[1]-startAnchor.y], + [endPoint[0]-endAnchor.x,endPoint[1]-endAnchor.y]) + + if (startOffset) l.d3plus.spline.splice(1,0,startPoint) + if (endOffset) l.d3plus.spline.splice(l.d3plus.spline.length-1,0,endPoint) + + } + + return true + + } + + return false + + }) + + var splines = vars.g.edges.selectAll("g.d3plus_edge_path") + .data(spline_data,function(d){ + + return d.d3plus.id + + }) + + if (vars.draw.timing) { + + lines.exit().transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove() + + splines.exit().transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove() + + lines.selectAll("text.d3plus_label, rect.d3plus_label_bg") + .transition().duration(vars.draw.timing/2) + .attr("opacity",0) + .remove() + + splines.selectAll("text.d3plus_label, rect.d3plus_label_bg") + .transition().duration(vars.draw.timing/2) + .attr("opacity",0) + .remove() + + lines.selectAll("line") + .data(function(d){ return [d] }) + .transition().duration(vars.draw.timing) + .call(line) + .call(style) + .each("end",label) + + splines.selectAll("path") + .data(function(d){ return [d] }) + .transition().duration(vars.draw.timing) + .call(spline) + .call(style) + .each("end",label) + + lines.enter().append("g") + .attr("class","d3plus_edge_line") + .append("line") + .call(line) + .call(init) + .transition().duration(vars.draw.timing) + .call(style) + .each("end",label) + + splines.enter().append("g") + .attr("class","d3plus_edge_path") + .append("path") + .call(spline) + .call(init) + .transition().duration(vars.draw.timing) + .call(style) + .each("end",label) + + } + else { + + lines.exit().remove() + + splines.exit().remove() + + lines.selectAll("text.d3plus_label, rect.d3plus_label_bg") + .remove() + + splines.selectAll("text.d3plus_label, rect.d3plus_label_bg") + .remove() + + lines.selectAll("line") + .data(function(d){ return [d] }) + .call(line) + .call(style) + .call(label) + + splines.selectAll("path") + .data(function(d){ return [d] }) + .call(spline) + .call(style) + .call(label) + + lines.enter().append("g") + .attr("class","d3plus_edge_line") + .append("line") + .call(line) + .call(init) + .call(style) + .call(label) + + splines.enter().append("g") + .attr("class","d3plus_edge_path") + .append("path") + .call(spline) + .call(init) + .call(style) + .call(label) + + } + +} + +},{"../../../geom/offset.coffee":163,"../../../util/buckets.coffee":207}],230:[function(require,module,exports){ +var copy = require("../../../util/copy.coffee"), + fetchColor = require("../../../core/fetch/color.coffee"), + fetchValue = require("../../../core/fetch/value.coffee"), + segments = require("./segments.coffee"), + shapeStyle = require("./style.coffee"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "square" and "circle" shapes using svg:rect +//------------------------------------------------------------------------------ +module.exports = function(vars,selection,enter,exit) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // The position and size of each rectangle on enter and exit. + //---------------------------------------------------------------------------- + function init(nodes) { + + nodes + .attr("x",0) + .attr("y",0) + .attr("width",0) + .attr("height",0); + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // The position and size of each rectangle on update. + //---------------------------------------------------------------------------- + function update(nodes,mod) { + if (!mod) mod = 0; + nodes + .attr("x",function(d){ + var w = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.width; + return (-w/2)-(mod/2); + }) + .attr("y",function(d){ + var h = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.height; + return (-h/2)-(mod/2); + }) + .attr("width",function(d){ + var w = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.width; + return w+mod; + }) + .attr("height",function(d){ + var h = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.height; + return h+mod; + }) + .attr("rx",function(d){ + var w = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.width; + var rounded = ["circle","donut"].indexOf(vars.shape.value) >= 0; + return rounded ? (w+mod)/2 : 0; + }) + .attr("ry",function(d){ + var h = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.height; + var rounded = ["circle","donut"].indexOf(vars.shape.value) >= 0; + return rounded ? (h+mod)/2 : 0; + }) + .attr("shape-rendering",function(d){ + if (["square"].indexOf(vars.shape.value) >= 0) { + return vars.shape.rendering.value; + } + else { + return "auto"; + } + }); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // In order to correctly animate each donut's size and arcs, we need to store + // it's previous values in a lookup object that does not get destroyed when + // redrawing the visualization. + //---------------------------------------------------------------------------- + if (!vars.arcs) { + vars.arcs = { + "donut": {}, + "active": {}, + "temp": {} + }; + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // This is the main arc function that determines what values to use for each + // arc angle and radius. + //---------------------------------------------------------------------------- + var arc = d3.svg.arc() + .startAngle(0) + .endAngle(function(d){ + var a = vars.arcs[d.d3plus.shape][d.d3plus.id].a; + return a > Math.PI*2 ? Math.PI*2 : a; + }) + .innerRadius(function(d){ + if (!d.d3plus.static && vars.shape.value === "donut") { + var r = vars.arcs[d.d3plus.shape][d.d3plus.id].r; + return r * vars.data.donut.size; + } + else { + return 0; + } + }) + .outerRadius(function(d){ + var r = vars.arcs[d.d3plus.shape][d.d3plus.id].r; + return vars.shape.value === "donut" ? r : r*2; + }); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // This is the main "arcTween" function where all of the animation happens + // for each arc. + //---------------------------------------------------------------------------- + function size(path,mod,rad,ang) { + if (!mod) mod = 0; + if (typeof rad != "number") rad = undefined; + if (typeof ang != "number") ang = undefined; + path.attrTween("d", function(d){ + if (rad === undefined) var r = d.d3plus.r ? d.d3plus.r : d3.max([d.d3plus.width,d.d3plus.height]); + else var r = rad; + if (ang === undefined) var a = d.d3plus.segments[d.d3plus.shape]; + else var a = ang; + if (!vars.arcs[d.d3plus.shape][d.d3plus.id]) { + vars.arcs[d.d3plus.shape][d.d3plus.id] = {"r": 0}; + vars.arcs[d.d3plus.shape][d.d3plus.id].a = d.d3plus.shape === "donut" ? Math.PI * 2 : 0; + } + var radius = d3.interpolate(vars.arcs[d.d3plus.shape][d.d3plus.id].r,r+mod), + angle = d3.interpolate(vars.arcs[d.d3plus.shape][d.d3plus.id].a,a); + + return function(t) { + vars.arcs[d.d3plus.shape][d.d3plus.id].r = radius(t); + vars.arcs[d.d3plus.shape][d.d3plus.id].a = angle(t); + return arc(d); + }; + }); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check each data point for active and temp data + //---------------------------------------------------------------------------- + selection.each(function(d){ + + var active = segments(vars, d, "active"), + temp = segments(vars, d, "temp"), + total = segments(vars, d, "total"), + group = d3.select(this), + color = fetchColor(vars,d); + + var fill_data = [], hatch_data = []; + + if (total && vars.types[vars.type.value].fill) { + + if (temp) { + var c = copy(d); + c.d3plus.shape = "temp"; + fill_data.push(c); + hatch_data = ["temp"]; + } + + if (active && (active < total || temp)) { + var c = copy(d); + c.d3plus.shape = "active"; + fill_data.push(c); + } + + } + + function hatch_lines(l) { + l + .attr("stroke",color) + .attr("stroke-width",1) + .attr("shape-rendering",vars.shape.rendering.value); + } + + var pattern = vars.defs.selectAll("pattern#d3plus_hatch_"+d.d3plus.id) + .data(hatch_data); + + if (vars.draw.timing) { + + pattern.selectAll("rect") + .transition().duration(vars.draw.timing) + .style("fill",color); + + pattern.selectAll("line") + .transition().duration(vars.draw.timing) + .style("stroke",color); + + } + else { + + pattern.selectAll("rect").style("fill",color); + + pattern.selectAll("line").style("stroke",color); + + } + + var pattern_enter = pattern.enter().append("pattern") + .attr("id","d3plus_hatch_"+d.d3plus.id) + .attr("patternUnits","userSpaceOnUse") + .attr("x","0") + .attr("y","0") + .attr("width","10") + .attr("height","10") + .append("g"); + + pattern_enter.append("rect") + .attr("x","0") + .attr("y","0") + .attr("width","10") + .attr("height","10") + .attr("fill",color) + .attr("fill-opacity",0.25); + + pattern_enter.append("line") + .attr("x1","0") + .attr("x2","10") + .attr("y1","0") + .attr("y2","10") + .call(hatch_lines); + + pattern_enter.append("line") + .attr("x1","-1") + .attr("x2","1") + .attr("y1","9") + .attr("y2","11") + .call(hatch_lines); + + pattern_enter.append("line") + .attr("x1","9") + .attr("x2","11") + .attr("y1","-1") + .attr("y2","1") + .call(hatch_lines); + + var clip_data = fill_data.length ? [d] : []; + + var clip = group.selectAll("#d3plus_clip_"+d.d3plus.id) + .data(clip_data); + + clip.enter().insert("clipPath",".d3plus_mouse") + .attr("id","d3plus_clip_"+d.d3plus.id) + .append("rect") + .attr("class","d3plus_clipping") + .call(init); + + if (vars.draw.timing) { + + clip.selectAll("rect").transition().duration(vars.draw.timing) + .call(update); + + clip.exit().transition().delay(vars.draw.timing) + .remove(); + + } + else { + + clip.selectAll("rect").call(update); + + clip.exit().remove(); + + } + + var fills = group.selectAll("path.d3plus_fill") + .data(fill_data); + + fills.transition().duration(vars.draw.timing) + .call(shapeStyle,vars) + .call(size); + + fills.enter().insert("path","rect.d3plus_mouse") + .attr("class","d3plus_fill") + .attr("clip-path","url(#d3plus_clip_"+d.d3plus.id+")") + .transition().duration(0) + .call(shapeStyle,vars) + .call(size,0,undefined,0) + .transition().duration(vars.draw.timing) + .call(size) + .call(shapeStyle,vars); + + fills.exit().transition().duration(vars.draw.timing) + .call(size,0,undefined,0) + .remove(); + + }); + +}; + +},{"../../../core/fetch/color.coffee":65,"../../../core/fetch/value.coffee":69,"../../../util/copy.coffee":210,"./segments.coffee":236,"./style.coffee":237}],231:[function(require,module,exports){ +var copy = require("../../../util/copy.coffee"), + fetchText = require("../../../core/fetch/text.js"), + fetchValue = require("../../../core/fetch/value.coffee"), + mix = require("../../../color/mix.coffee"), + print = require("../../../core/console/print.coffee"), + rtl = require("../../../client/rtl.coffee"), + segments = require("./segments.coffee"), + shapeColor = require("./color.coffee"), + stringList = require("../../../string/list.coffee"), + textColor = require("../../../color/text.coffee"), + textWrap = require("../../../textwrap/textwrap.coffee"); + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "labels" using svg:text and d3plus.textwrap +//------------------------------------------------------------------------------ +module.exports = function( vars , group ) { + + var scale = vars.types[vars.type.value].zoom ? vars.zoom.behavior.scaleExtent() : [1,1], + selection = vars.g[ group ].selectAll("g"); + + var opacity = function(elem) { + + elem + .attr("opacity",function(d){ + // if (vars.draw.timing) return 1; + var size = parseFloat(d3.select(this).attr("font-size"),10); + d.visible = size * (vars.zoom.scale/scale[1]) >= 2; + return d.visible ? 1 : 0; + }); + + }; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Label Exiting + //---------------------------------------------------------------------------- + var remove = function(text) { + + if (vars.draw.timing) { + text + .transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove(); + } + else { + text.remove(); + } + + }; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Label Styling + //---------------------------------------------------------------------------- + var style = function(text) { + + var salign = vars.labels.valign.value === "bottom" ? "top" : "bottom"; + + text + .attr("font-weight",vars.labels.font.weight) + .attr("font-family",vars.labels.font.family.value) + .attr("stroke", "none") + .attr("pointer-events",function(t){ + return t.mouse ? "auto": "none"; + }) + .attr("fill", function(t){ + + if ( t.color ) return t.color; + + var color = shapeColor(t.parent,vars), + legible = textColor(color), + opacity = t.text ? 0.15 : 1; + + return mix( color , legible , 0.2 , opacity ); + + }) + .each(function(t){ + + if (t.resize instanceof Array) { + var min = t.resize[0], max = t.resize[1]; + } + + var size = t.resize, resize = true; + + if (t.text) { + + if ( !(size instanceof Array) ) { + size = [9, 50]; + resize = t.resize; + } + + var y = t.y - t.h*scale[1]/2 + t.padding/2; + if (salign === "bottom") y += (t.h * scale[1])/2; + + textWrap() + .align("center") + .container(d3.select(this)) + .height((t.h * scale[1])/2) + .padding(t.padding/2) + .resize(resize) + .size(size) + .text(vars.format.value(t.text*100,{"key": "share", "vars": vars})) + .width(t.w * scale[1]) + .valign(salign) + .x(t.x - t.w*scale[1]/2 + t.padding/2) + .y(y) + .draw(); + + } + else { + + if ( !(t.resize instanceof Array) ) { + size = [7, 40*(scale[1]/scale[0])]; + resize = t.resize; + } + + var yOffset = vars.labels.valign.value === "bottom" ? t.share : 0; + + textWrap() + .align(t.anchor || vars.labels.align.value) + .container( d3.select(this) ) + .height(t.h * scale[1] - t.share) + .padding(t.padding/2) + .resize( resize ) + .size( size ) + .shape(t.shape || "square") + .text( t.names ) + .valign(vars.labels.valign.value) + .width(t.w * scale[1]) + .x(t.x - t.w*scale[1]/2 + t.padding/2) + .y(t.y - t.h*scale[1]/2 + t.padding/2 + yOffset) + .draw(); + + } + + }) + .attr("transform",function(t){ + var translate = d3.select(this).attr("transform") || ""; + var a = t.angle || 0, + x = t.translate && t.translate.x ? t.translate.x : 0, + y = t.translate && t.translate.y ? t.translate.y : 0; + + if (translate.length) { + translate = translate.split(")").slice(-3).join(")"); + } + return "rotate("+a+","+x+","+y+")scale("+1/scale[1]+")translate("+(t.x*scale[1]-t.x)+","+(t.y*scale[1]-t.y)+")" + translate; + + }); + + }; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Loop through each selection and analyze the labels + //---------------------------------------------------------------------------- + if (group === "edges" || vars.labels.value) { + + if ( vars.dev.value ) { + var timerString = "drawing " + group + " labels"; + print.time( timerString ); + } + + selection.each(function(d){ + + var disabled = d.d3plus && "label" in d.d3plus && !d.d3plus.label, + label = d.d3plus_label || null, + share = d.d3plus_share, + names = d.d3plus.text ? d.d3plus.text : + label && label.names ? label.names : + vars.labels.text.value ? + fetchValue(vars, d, vars.labels.text.value) : + fetchText(vars,d), + group = label && "group" in label ? label.group : d3.select(this), + share_size = 0, + fill = vars.types[vars.type.value].fill; + + if (!(names instanceof Array)) names = [names]; + + if (label) { + + if (["line","area"].indexOf(vars.shape.value) >= 0) { + var background = true; + } + else if (d && "d3plus" in d) { + var active = segments(vars, d, "active"), + temp = segments(vars, d, "temp"), + total = segments(vars, d, "total"), + background = (!temp && !active) || (active >= total) || (!active && temp >= total); + } + + } + + if (!disabled && ((label && label.force) || background || !fill)) { + + if (share && d.d3plus.share && share.w-vars.labels.padding*2 >= 10 && share.h-vars.labels.padding*2 >= 10 && vars.labels.valign.value != "middle") { + + share.resize = vars.labels.resize.value === false ? false : + share && "resize" in share ? share.resize : true; + + share.padding = vars.labels.padding; + + share.text = d.d3plus.share; + share.parent = d; + + var text = group.selectAll("text#d3plus_share_"+d.d3plus.id) + .data([share],function(t){ + return t.w+""+t.h+""+t.text; + }); + + if (vars.draw.timing && vars.zoom.scale === 1) { + + text + .transition().duration(vars.draw.timing/2) + .call(style); + + text.enter().append("text") + .attr("id","d3plus_share_"+d.d3plus.id) + .attr("class","d3plus_share") + .attr("opacity",0) + .call(style) + .transition().duration(vars.draw.timing/2) + .delay(vars.draw.timing/2) + .attr("opacity",1); + + } + else { + + text + .attr("opacity",1) + .call(style); + + text.enter().append("text") + .attr("id","d3plus_share_"+d.d3plus.id) + .attr("class","d3plus_share") + .attr("opacity",1) + .call(style); + + } + + share_size = text.node().getBBox().height + vars.labels.padding; + + text.exit().call(remove); + + } + else { + group.selectAll("text.d3plus_share") + .call(remove); + } + + if (label) { + + label.resize = vars.labels.resize.value === false ? false : + label && "resize" in label ? label.resize : true; + + label.padding = typeof label.padding === "number" ? label.padding : vars.labels.padding; + + } + + if (label && label.w*scale[1]-label.padding >= 20 && label.h*scale[1]-label.padding >= 10 && names.length) { + + var and = vars.format.locale.value.ui.and, + more = vars.format.locale.value.ui.more; + + for (var i = 0; i < names.length; i++) { + if (names[i] instanceof Array) { + names[i] = stringList(names[i],and,3,more); + } + } + + label.names = names; + + label.share = share_size; + label.parent = d; + + var text = group.selectAll("text#d3plus_label_"+d.d3plus.id) + .data([label],function(t){ + if (!t) return false; + return t.w+"_"+t.h+"_"+t.x+"_"+t.y+"_"+t.names.join("_"); + }), fontSize = label.resize ? undefined : + (vars.labels.font.size * scale[0]) + "px"; + + if (vars.draw.timing && vars.zoom.scale === 1) { + + text + .transition().duration(vars.draw.timing/2) + .call(style) + .call(opacity); + + text.enter().append("text") + .attr("font-size",fontSize) + .attr("id","d3plus_label_"+d.d3plus.id) + .attr("class","d3plus_label") + .attr("opacity",0) + .call(style) + .transition().duration(vars.draw.timing/2) + .delay(vars.draw.timing/2) + .call(opacity); + + } + else { + + text + .attr("opacity",1) + .call(style) + .call(opacity); + + text.enter().append("text") + .attr("font-size",fontSize) + .attr("id","d3plus_label_"+d.d3plus.id) + .attr("class","d3plus_label") + .call(style) + .call(opacity); + + } + + text.exit().call(remove); + + if (text.size() === 0 || text.selectAll("tspan").size() === 0) { + delete d.d3plus_label; + d3.select(this).selectAll("text#d3plus_label_"+d.d3plus.id+", rect#d3plus_label_bg_"+d.d3plus.id) + .call(remove); + vars.g.labels.selectAll("text#d3plus_label_"+d.d3plus.id+", rect#d3plus_label_bg_"+d.d3plus.id) + .call(remove); + } + else { + + if (label.background) { + + var background_data = ["background"]; + + var box = text.node().getBBox(); + var bounds = { + "height": box.height, + "width": box.width, + "x": box.x, + "y": box.y > 0 ? box.y : -box.height/2 + }; + bounds.width += vars.labels.padding*scale[0]; + bounds.height += vars.labels.padding*scale[0]; + bounds.x -= (vars.labels.padding*scale[0])/2; + bounds.y -= (vars.labels.padding*scale[0])/2; + var y = text.attr("transform").match(/translate\(([^a-z]+)\)/gi)[0]; + y = y.replace(/([^a-z])\s([^a-z])/gi, "$1,$2"); + y = y.split(","); + if (y.length > 1) { + y = y[y.length - 1]; + y = y.substring(0, y.length - 1); + bounds.y += parseFloat(y); + } + + } + else { + var background_data = [], + bounds = {}; + } + + var bg = group.selectAll("rect#d3plus_label_bg_"+d.d3plus.id) + .data(background_data), + bg_opacity = typeof label.background === "number" ? + label.background : + typeof label.background === "string" ? 1 : 0.6; + + function bg_style(elem) { + + var color = typeof label.background === "string" ? label.background : vars.background.value === "none" + ? "#ffffff" : vars.background.value + , fill = typeof label.background === "string" + ? label.background : color + , transform = text.attr("transform").split(")"); + transform.pop(); + transform.pop(); + transform.push(""); + transform = transform.join(")"); + + elem + .attr("fill",fill) + .attr(bounds) + .attr("transform",transform); + + } + + if (vars.draw.timing) { + + bg.exit().transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove(); + + bg.transition().duration(vars.draw.timing) + .attr("opacity",bg_opacity) + .call(bg_style); + + bg.enter().insert("rect",".d3plus_label") + .attr("id","d3plus_label_bg_"+d.d3plus.id) + .attr("class","d3plus_label_bg") + .attr("opacity",0) + .call(bg_style) + .transition().duration(vars.draw.timing) + .attr("opacity",bg_opacity); + + } + else { + + bg.exit().remove(); + + bg.enter().insert("rect",".d3plus_label") + .attr("id","d3plus_label_bg_"+d.d3plus.id) + .attr("class","d3plus_label_bg"); + + bg.attr("opacity",bg_opacity) + .call(bg_style); + + } + + } + + } + else { + delete d.d3plus_label; + d3.select(this).selectAll("text#d3plus_label_"+d.d3plus.id+", rect#d3plus_label_bg_"+d.d3plus.id) + .call(remove); + vars.g.labels.selectAll("text#d3plus_label_"+d.d3plus.id+", rect#d3plus_label_bg_"+d.d3plus.id) + .call(remove); + } + + } + else { + delete d.d3plus_label; + d3.select(this).selectAll("text#d3plus_label_"+d.d3plus.id+", rect#d3plus_label_bg_"+d.d3plus.id) + .call(remove); + vars.g.labels.selectAll("text#d3plus_label_"+d.d3plus.id+", rect#d3plus_label_bg_"+d.d3plus.id) + .call(remove); + } + }); + + if ( vars.dev.value ) print.timeEnd( timerString ); + + } + else { + + if ( vars.dev.value ) { + var timerString = "removing " + group + " labels"; + print.time( timerString ); + } + + selection.selectAll("text.d3plus_label, rect.d3plus_label_bg") + .call(remove); + + vars.g.labels.selectAll("text.d3plus_label, rect.d3plus_label_bg") + .call(remove); + + if ( vars.dev.value ) print.timeEnd( timerString ); + + } +} + +},{"../../../client/rtl.coffee":42,"../../../color/mix.coffee":48,"../../../color/text.coffee":52,"../../../core/console/print.coffee":54,"../../../core/fetch/text.js":68,"../../../core/fetch/value.coffee":69,"../../../string/list.coffee":177,"../../../textwrap/textwrap.coffee":203,"../../../util/copy.coffee":210,"./color.coffee":223,"./segments.coffee":236}],232:[function(require,module,exports){ +var copy = require("../../../util/copy.coffee"), + closest = require("../../../util/closest.coffee"), + events = require("../../../client/pointer.coffee"), + shapeStyle = require("./style.coffee"), + fetchValue = require("../../../core/fetch/value.coffee"); + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "line" shapes using svg:line +//------------------------------------------------------------------------------ +module.exports = function(vars,selection,enter,exit) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // The D3 line function that determines what variables to use for x and y + // positioning, as well as line interpolation defined by the user. + //---------------------------------------------------------------------------- + var line = d3.svg.line() + .x(function(d){ return d.d3plus.x; }) + .y(function(d){ return d.d3plus.y; }) + .interpolate(vars.shape.interpolate.value); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Divide each line into it's segments. We do this so that there can be gaps + // in the line and mouseover. + // + // Then, create new data group from values to become small nodes at each + // point on the line. + //---------------------------------------------------------------------------- + + var stroke = vars.size.value || vars.data.stroke.width, + discrete = vars[vars.axes.discrete], + hitarea = function(l){ + var s = stroke; + if (s.constructor !== Number) { + var v = fetchValue(vars, l, stroke); + if (v && v.length) s = d3.max(v); + else s = vars.data.stroke.width; + } + return s < 15 ? 15 : s; + }; + + var ticks = discrete.ticks.values.map(function(d){ + if (d.constructor === Date) return d.getTime(); + else return d; + }); + + selection.each(function(d){ + + var lastIndex = false, + segments = [], + nodes = [], + temp = copy(d), + group = d3.select(this); + + temp.values = []; + temp.segment_key = temp.key; + d.values.forEach(function(v,i,arr){ + + var k = fetchValue(vars, v, discrete.value); + + if (k.constructor === Date) k = k.getTime(); + + var index = ticks.indexOf(closest(ticks,k)); + + if (lastIndex === false || lastIndex === index - 1) { + temp.values.push(v); + temp.segment_key += "_" + index; + } + else { + if (temp.values.length > 1) { + segments.push(temp); + } + else { + nodes.push(temp.values[0]); + } + temp = copy(d); + temp.values = [v]; + } + + if ( i === arr.length - 1 ) { + if (temp.values.length > 1) { + segments.push(temp); + } + else { + nodes.push(temp.values[0]); + } + } + + lastIndex = index; + + }); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Bind segment data to "paths" + //-------------------------------------------------------------------------- + var paths = group.selectAll("path.d3plus_line") + .data(segments, function(d){ + if (!d.d3plus) d.d3plus = {}; + d.d3plus.shape = "line"; + return d.segment_key; + }); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Bind node data to "rects" + //-------------------------------------------------------------------------- + var rects = group.selectAll("rect.d3plus_anchor") + .data(nodes, function(d){ + if (!d.d3plus) d.d3plus = {}; + d.d3plus.r = stroke; + return d.d3plus.id; + }); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" and "rects" Enter/Update + //-------------------------------------------------------------------------- + if (vars.draw.timing) { + + paths.exit().transition().duration(vars.draw.timing) + .attr("opacity", 0) + .remove(); + + paths.transition().duration(vars.draw.timing) + .attr("d",function(d){ return line(d.values); }) + .call(shapeStyle,vars); + + paths.enter().append("path") + .attr("class","d3plus_line") + .style("stroke-linecap","round") + .attr("d", function(d){ return line(d.values); }) + .call(shapeStyle,vars) + .attr("opacity", 0) + .transition().duration(vars.draw.timing) + .attr("opacity", 1); + + rects.enter().append("rect") + .attr("class","d3plus_anchor") + .attr("id",function(d){ return d.d3plus.id; }) + .call(init) + .call(shapeStyle,vars); + + rects.transition().duration(vars.draw.timing) + .call(update) + .call(shapeStyle,vars); + + rects.exit().transition().duration(vars.draw.timing) + .call(init) + .remove(); + + } + else { + + paths.exit().remove(); + + paths.enter().append("path") + .attr("class","d3plus_line") + .style("stroke-linecap","round"); + + paths + .attr("d",function(d){ return line(d.values); }) + .call(shapeStyle,vars); + + rects.enter().append("rect") + .attr("class","d3plus_anchor") + .attr("id",function(d){ + return d.d3plus.id; + }); + + rects.exit().remove(); + + rects.call(update) + .call(shapeStyle,vars); + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create mouse event lines + //-------------------------------------------------------------------------- + var mouse = group.selectAll("path.d3plus_mouse") + .data(segments, function(d){ + return d.segment_key; + }); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Mouse "paths" Enter + //-------------------------------------------------------------------------- + mouse.enter().append("path") + .attr("class","d3plus_mouse") + .attr("d", function(l){ return line(l.values); }) + .style("stroke","black") + .style("stroke-width",hitarea) + .style("fill","none") + .style("stroke-linecap","round") + .attr("opacity",0); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Mouse "paths" Update + //-------------------------------------------------------------------------- + mouse + .on(events.over,function(m){ + if (!vars.draw.frozen && vars.mouse.value && vars.mouse.over.value) mouseStyle(vars, this, stroke, 2); + }) + .on(events.out,function(d){ + if (!vars.draw.frozen && vars.mouse.value && vars.mouse.out.value) mouseStyle(vars, this, stroke, 0); + }); + + if (vars.draw.timing) { + + mouse.transition().duration(vars.draw.timing) + .attr("d",function(l){ return line(l.values); }) + .style("stroke-width",hitarea); + + } + else { + + mouse.attr("d",function(l){ return line(l.values); }) + .style("stroke-width",hitarea); + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Mouse "paths" Exit + //-------------------------------------------------------------------------- + mouse.exit().remove(); + + }); + +}; + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// The position and size of each anchor point on enter and exit. +//---------------------------------------------------------------------------- +function init(n) { + + n + .attr("x",function(d){ + return d.d3plus.x; + }) + .attr("y",function(d){ + return d.d3plus.y; + }) + .attr("width",0) + .attr("height",0); + +} + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// The position and size of each anchor point on update. +//---------------------------------------------------------------------------- +function update(n,mod) { + + if (mod === undefined) mod = 0; + + n + .attr("x",function(d){ + var w = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.width; + return d.d3plus.x - ((w/2)+(mod/2)); + }) + .attr("y",function(d){ + var h = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.height; + return d.d3plus.y - ((h/2)+(mod/2)); + }) + .attr("width",function(d){ + var w = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.width; + return w+mod; + }) + .attr("height",function(d){ + var h = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.height; + return h+mod; + }) + .attr("rx",function(d){ + var w = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.width; + return (w+mod)/2; + }) + .attr("ry",function(d){ + var h = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.height; + return (h+mod)/2; + }); + +} + +function mouseStyle(vars, elem, stroke, mod) { + + var timing = vars.draw.timing ? vars.timing.mouseevents : 0; + if (mod === undefined) mod = 0; + + if (timing) { + + d3.select(elem.parentNode).selectAll("path.d3plus_line") + .transition().duration(timing) + .style("stroke-width",function(l){ + var s = stroke; + if (s.constructor !== Number) { + var v = fetchValue(vars, l, stroke); + if (v && v.length) s = d3.max(v); + else s = vars.data.stroke.width; + } + return s + mod; + }); + + d3.select(elem.parentNode).selectAll("rect") + .transition().duration(timing) + .style("stroke-width",function(l){ + var s = stroke; + if (s.constructor !== Number) { + var v = fetchValue(vars, l, stroke); + if (v && v.length) s = d3.max(v); + else s = vars.data.stroke.width; + } + return s; + }) + .call(update, mod); + + } + else { + + d3.select(elem.parentNode).selectAll("path.d3plus_line") + .style("stroke-width",function(l){ + var s = stroke; + if (s.constructor !== Number) { + var v = fetchValue(vars, l, stroke); + if (v && v.length) s = d3.max(v); + else s = vars.data.stroke.width; + } + return s + mod; + }); + + d3.select(elem.parentNode).selectAll("rect") + .style("stroke-width",function(l){ + var s = stroke; + if (s.constructor !== Number) { + var v = fetchValue(vars, l, stroke); + if (v && v.length) s = d3.max(v); + else s = vars.data.stroke.width; + } + return s; + }) + .call(update, mod); + } + +} + +},{"../../../client/pointer.coffee":40,"../../../core/fetch/value.coffee":69,"../../../util/closest.coffee":209,"../../../util/copy.coffee":210,"./style.coffee":237}],233:[function(require,module,exports){ +module.exports = function(vars) { + + var edges = vars.returned.edges || []; + + var paths = vars.g.edges.selectAll("g.d3plus_edge_path") + .data(edges, function(d){ + d.d3plus.id = "path_" + d[vars.edges.source][vars.id.value] + "_" + d[vars.edges.target][vars.id.value]; + return d.d3plus.id; + }); + + function pathStyles(p) { + p + .attr("d", vars.edges.path) + .style("stroke-width", function(d) { + return Math.max(1, d.dy); + }) + .style("stroke", "#ddd") + .style("fill", "none") + .attr("transform", function(d){ + return "translate(" + d.d3plus.x + "," + d.d3plus.y + ")"; + }); + } + + if (vars.draw.timing) { + + paths.exit().transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove(); + + paths.selectAll("text.d3plus_label, rect.d3plus_label_bg") + .transition().duration(vars.draw.timing/2) + .attr("opacity",0) + .remove(); + + paths.selectAll("path") + .data(function(d){ return [d] }) + .transition().duration(vars.draw.timing) + .call(pathStyles); + + paths.enter().append("g") + .attr("class","d3plus_edge_path") + .append("path") + .style("stroke-width", 0) + .transition().duration(vars.draw.timing) + .call(pathStyles); + + } + else { + + paths.exit().remove(); + + paths.selectAll("text.d3plus_label, rect.d3plus_label_bg") + .remove(); + + paths.selectAll("path") + .data(function(d){ return [d] }) + .call(pathStyles); + + paths.enter().append("g") + .attr("class","d3plus_edge_path") + .append("path") + .call(pathStyles); + + } + +} + +},{}],234:[function(require,module,exports){ +var angles, interpolates, radii, shapeStyle; + +shapeStyle = require("./style.coffee"); + +radii = {}; + +angles = {}; + +interpolates = { + r: {}, + a: {} +}; + +module.exports = function(vars, selection, enter, exit) { + var data, newRadial, nextLevel, radial, radialTween; + nextLevel = vars.id.nesting[vars.depth.value + 1]; + radial = d3.svg.line.radial().interpolate("linear-closed").radius(function(d) { + return d.d3plus.r; + }).angle(function(d) { + return d.d3plus.a; + }); + data = function(d) { + if (vars.labels.value) { + if (d.d3plus.label) { + d.d3plus_label = d.d3plus.label; + } else { + delete d.d3plus_label; + } + } + return [d]; + }; + if (vars.draw.timing) { + selection.each(function(d) { + var c, j, len, ref, results; + ref = d[nextLevel]; + results = []; + for (j = 0, len = ref.length; j < len; j++) { + c = ref[j]; + results.push(c.d3plus.id = c[vars.id.value] + "_" + c[nextLevel]); + } + return results; + }); + newRadial = d3.svg.line.radial().interpolate("linear-closed").radius(function(d, i) { + if (radii[d.d3plus.id] === void 0) { + radii[d.d3plus.id] = 0; + } + if (isNaN(radii[d.d3plus.id])) { + radii[d.d3plus.id] = d.d3plus.r; + } + return radii[d.d3plus.id]; + }).angle(function(d, i) { + if (angles[d.d3plus.id] === void 0) { + angles[d.d3plus.id] = d.d3plus.a; + } + if (isNaN(angles[d.d3plus.id])) { + angles[d.d3plus.id] = d.d3plus.a; + } + return angles[d.d3plus.id]; + }); + radialTween = function(arcs, newRadius) { + return arcs.attrTween("d", function(d) { + var a, c, i, j, len, r, ref; + ref = d[nextLevel]; + for (i = j = 0, len = ref.length; j < len; i = ++j) { + c = ref[i]; + a = c.d3plus.a; + if (newRadius === void 0) { + r = c.d3plus.r; + } else if (newRadius === 0) { + r = 0; + } + interpolates.a[c.d3plus.id] = d3.interpolate(angles[c.d3plus.id], a); + interpolates.r[c.d3plus.id] = d3.interpolate(radii[c.d3plus.id], r); + } + return function(t) { + var k, len1, ref1; + ref1 = d[nextLevel]; + for (i = k = 0, len1 = ref1.length; k < len1; i = ++k) { + c = ref1[i]; + angles[c.d3plus.id] = interpolates.a[c.d3plus.id](t); + radii[c.d3plus.id] = interpolates.r[c.d3plus.id](t); + } + return newRadial(d[nextLevel]); + }; + }); + }; + enter.append("path").attr("class", "d3plus_data").call(shapeStyle, vars).attr("d", function(d) { + return newRadial(d[nextLevel]); + }); + selection.selectAll("path.d3plus_data").data(data).transition().duration(vars.draw.timing).call(shapeStyle, vars).call(radialTween); + exit.selectAll("path.d3plus_data").transition().duration(vars.draw.timing).call(radialTween, 0); + } else { + enter.append("path").attr("class", "d3plus_data"); + selection.selectAll("path.d3plus_data").data(data).call(shapeStyle, vars).attr("d", function(d) { + return radial(d[nextLevel]); + }); + } +}; + + +},{"./style.coffee":237}],235:[function(require,module,exports){ +var shapeStyle; + +shapeStyle = require("./style.coffee"); + +module.exports = function(vars, selection, enter, exit) { + var data, init, update; + data = function(d) { + var h, w; + if (vars.labels.value && !d.d3plus.label) { + w = (d.d3plus.r ? d.d3plus.r * 2 : d.d3plus.width); + h = (d.d3plus.r ? d.d3plus.r * 2 : d.d3plus.height); + d.d3plus_label = { + w: w, + h: h, + x: 0, + y: 0 + }; + d.d3plus_share = { + w: w, + h: h, + x: 0, + y: 0 + }; + d.d3plus_label.shape = (d.d3plus.shape === "circle" ? "circle" : "square"); + } else if (d.d3plus.label) { + d.d3plus_label = d.d3plus.label; + } else { + delete d.d3plus_label; + } + return [d]; + }; + init = function(nodes) { + return nodes.attr("x", function(d) { + if (d.d3plus.init && "x" in d.d3plus.init) { + return d.d3plus.init.x; + } else { + if (d.d3plus.init && "width" in d.d3plus.init) { + return -d.d3plus.width / 2; + } else { + return 0; + } + } + }).attr("y", function(d) { + if (d.d3plus.init && "y" in d.d3plus.init) { + return d.d3plus.init.y; + } else { + if (d.d3plus.init && "height" in d.d3plus.init) { + return -d.d3plus.height / 2; + } else { + return 0; + } + } + }).attr("width", function(d) { + if (d.d3plus.init && "width" in d.d3plus.init) { + return d.d3plus.init.width; + } else { + return 0; + } + }).attr("height", function(d) { + if (d.d3plus.init && "height" in d.d3plus.init) { + return d.d3plus.init.height; + } else { + return 0; + } + }); + }; + update = function(nodes) { + return nodes.attr("x", function(d) { + var w; + w = d.d3plus.r ? d.d3plus.r * 2 : d.d3plus.width; + return -w / 2; + }).attr("y", function(d) { + var h; + h = d.d3plus.r ? d.d3plus.r * 2 : d.d3plus.height; + return -h / 2; + }).attr("width", function(d) { + if (d.d3plus.r) { + return d.d3plus.r * 2; + } else { + return d.d3plus.width; + } + }).attr("height", function(d) { + if (d.d3plus.r) { + return d.d3plus.r * 2; + } else { + return d.d3plus.height; + } + }).attr("rx", function(d) { + var rounded, w; + rounded = d.d3plus.shape === "circle"; + w = d.d3plus.r ? d.d3plus.r * 2 : d.d3plus.width; + if (rounded) { + return (w + 2) / 2; + } else { + return 0; + } + }).attr("ry", function(d) { + var h, rounded; + rounded = d.d3plus.shape === "circle"; + h = d.d3plus.r ? d.d3plus.r * 2 : d.d3plus.height; + if (rounded) { + return (h + 2) / 2; + } else { + return 0; + } + }).attr("transform", function(d) { + if ("rotate" in d.d3plus) { + return "rotate(" + d.d3plus.rotate + ")"; + } else { + return ""; + } + }).attr("shape-rendering", function(d) { + if (d.d3plus.shape === "square" && (!("rotate" in d.d3plus))) { + return vars.shape.rendering.value; + } else { + return "auto"; + } + }); + }; + if (vars.draw.timing) { + enter.append("rect").attr("class", "d3plus_data").call(init).call(shapeStyle, vars); + selection.selectAll("rect.d3plus_data").data(data).transition().duration(vars.draw.timing).call(update).call(shapeStyle, vars); + return exit.selectAll("rect.d3plus_data").transition().duration(vars.draw.timing).call(init); + } else { + enter.append("rect").attr("class", "d3plus_data"); + return selection.selectAll("rect.d3plus_data").data(data).call(update).call(shapeStyle, vars); + } +}; + + +},{"./style.coffee":237}],236:[function(require,module,exports){ +var fetchValue; + +fetchValue = require("../../../core/fetch/value.coffee"); + +module.exports = function(vars, d, segment) { + var ret; + ret = vars[segment].value; + if (ret) { + if (segment in d.d3plus) { + return d.d3plus[segment]; + } else { + return fetchValue(vars, d, ret); + } + } else { + return d.d3plus[segment]; + } +}; + + +},{"../../../core/fetch/value.coffee":69}],237:[function(require,module,exports){ +var color, ie, value; + +color = require("./color.coffee"); + +ie = require("../../../client/ie.js"); + +value = require("../../../core/fetch/value.coffee"); + +module.exports = function(nodes, vars) { + return nodes.attr("fill", function(d) { + if (d.d3plus && d.d3plus.spline) { + return "none"; + } else { + return color(d, vars); + } + }).style("stroke", function(d) { + var c; + if (d.d3plus && d.d3plus.stroke) { + return d.d3plus.stroke; + } else { + c = d.values ? color(d.values[0], vars) : color(d, vars, true); + return d3.rgb(c).darker(0.6); + } + }).style("stroke-width", function(d) { + var v; + if (ie && vars.types[vars.type.value].zoom) { + return 0; + } + if (d.d3plus.shape === "line" && vars.size.value) { + if (vars.size.value.constructor === Number) { + return vars.size.value; + } + v = value(vars, d, vars.size.value); + if (v && v.length) { + return d3.max(v); + } + } + return vars.data.stroke.width; + }).attr("opacity", vars.data.opacity).attr("vector-effect", "non-scaling-stroke"); +}; + + +},{"../../../client/ie.js":39,"../../../core/fetch/value.coffee":69,"./color.coffee":223}],238:[function(require,module,exports){ +var shapeStyle = require("./style.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "square" and "circle" shapes using svg:rect +//------------------------------------------------------------------------------ +module.exports = function(vars,selection,enter,exit) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialize check scale on enter and exit. + //---------------------------------------------------------------------------- + function init(paths){ + paths.attr("d", d3.svg.symbol().type("triangle-down").size(10)) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Change scale of check on update. + //--------------------------------------------------------------------------- + function update(paths){ + paths.attr("d", d3.svg.symbol().type("triangle-down").size(function(d){ + var smaller_dim = Math.min(d.d3plus.width, d.d3plus.height); + return d3.scale.pow().exponent(2)(smaller_dim/2); + })) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Enter + //---------------------------------------------------------------------------- + enter.append("path").attr("class","d3plus_data") + .call(init) + .call(shapeStyle,vars) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Update + //---------------------------------------------------------------------------- + selection.selectAll("path.d3plus_data") + .data(function(d) { + return [d]; + }) + + if (vars.draw.timing) { + selection.selectAll("path.d3plus_data") + .transition().duration(vars.draw.timing) + .call(update) + .call(shapeStyle,vars) + } + else { + selection.selectAll("path.d3plus_data") + .call(update) + .call(shapeStyle,vars) + } + +} + +},{"./style.coffee":237}],239:[function(require,module,exports){ +var shapeStyle = require("./style.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "square" and "circle" shapes using svg:rect +//------------------------------------------------------------------------------ +module.exports = function(vars,selection,enter,exit) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialize check scale on enter and exit. + //---------------------------------------------------------------------------- + function init(paths){ + paths.attr("d", d3.svg.symbol().type("triangle-up").size(10)) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Change scale of check on update. + //--------------------------------------------------------------------------- + function update(paths){ + paths.attr("d", d3.svg.symbol().type("triangle-up").size(function(d){ + var smaller_dim = Math.min(d.d3plus.width, d.d3plus.height); + return d3.scale.pow().exponent(2)(smaller_dim/2); + })) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Enter + //---------------------------------------------------------------------------- + enter.append("path").attr("class","d3plus_data") + .call(init) + .call(shapeStyle,vars) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Update + //---------------------------------------------------------------------------- + selection.selectAll("path.d3plus_data") + .data(function(d) { + return [d]; + }) + + if (vars.draw.timing) { + selection.selectAll("path.d3plus_data") + .transition().duration(vars.draw.timing) + .call(update) + .call(shapeStyle,vars) + } + else { + selection.selectAll("path.d3plus_data") + .call(update) + .call(shapeStyle,vars) + } + +} + +},{"./style.coffee":237}],240:[function(require,module,exports){ +module.exports = function(vars, selection, enter, exit) { + var d, data, init, marker, orient, pos, position, size, style; + data = function(d) { + if (d.d3plus.text) { + d.d3plus_label = { + w: size, + h: size, + x: 0, + y: 0, + background: "#fff", + resize: false, + angle: ["left", "right"].indexOf(d.d3plus.position) >= 0 ? 90 : 0 + }; + } else if (d.d3plus.label) { + d.d3plus_label = d.d3plus.label; + } else { + delete d.d3plus_label; + } + return [d]; + }; + style = function(line) { + return line.style("stroke-width", vars.data.stroke.width).style("stroke", "#444").attr("fill", "none").attr("shape-rendering", vars.shape.rendering.value); + }; + init = function(line) { + return line.attr("x1", 0).attr("x2", 0).attr("y1", 0).attr("y2", 0); + }; + position = function(line) { + return line.attr("x1", function(d) { + var offset, w, x; + if (["top", "bottom"].indexOf(d.d3plus.position) >= 0) { + return 0; + } else { + offset = d.d3plus.offset || 0; + w = d.d3plus.width || 0; + x = offset < 0 ? -w : w; + return x + offset; + } + }).attr("x2", function(d) { + if (["top", "bottom"].indexOf(d.d3plus.position) >= 0) { + return 0; + } else { + return d.d3plus.offset || 0; + } + }).attr("y1", function(d) { + var h, offset, y; + if (["left", "right"].indexOf(d.d3plus.position) >= 0) { + return 0; + } else { + offset = d.d3plus.offset || 0; + h = d.d3plus.height || 0; + y = offset < 0 ? -h : h; + return y + offset; + } + }).attr("y2", function(d) { + if (["left", "right"].indexOf(d.d3plus.position) >= 0) { + return 0; + } else { + return d.d3plus.offset || 0; + } + }).attr("marker-start", "url(#d3plus_whisker_marker)"); + }; + marker = vars.defs.selectAll("#d3plus_whisker_marker").data([0]); + marker.enter().append("marker").attr("id", "d3plus_whisker_marker").attr("markerUnits", "userSpaceOnUse").style("overflow", "visible").append("line"); + d = selection.datum(); + if (d) { + pos = d.d3plus.position; + orient = ["top", "bottom"].indexOf(pos) >= 0 ? "horizontal" : "vertical"; + size = orient === "horizontal" ? d.d3plus.width : d.d3plus.height; + } else { + orient = "horizontal"; + size = 0; + } + marker.select("line").attr("x1", orient === "horizontal" ? -size / 2 : 0).attr("x2", orient === "horizontal" ? size / 2 : 0).attr("y1", orient === "vertical" ? -size / 2 : 0).attr("y2", orient === "vertical" ? size / 2 : 0).call(style).style("stroke-width", vars.data.stroke.width * 2); + if (vars.draw.timing) { + enter.append("line").attr("class", "d3plus_data").call(style).call(init); + selection.selectAll("line.d3plus_data").data(data).transition().duration(vars.draw.timing).call(style).call(position); + exit.selectAll("line.d3plus_data").transition().duration(vars.draw.timing).call(init); + } else { + enter.append("line").attr("class", "d3plus_data"); + selection.selectAll("line.d3plus_data").data(data).call(style).call(position); + } +}; + + +},{}],241:[function(require,module,exports){ +var events = require("../../../client/pointer.coffee"), + prefix = require("../../../client/prefix.coffee"), + print = require("../../../core/console/print.coffee"), + touch = require("../../../client/touch.coffee"), + touchEvent = require("../zoom/propagation.coffee"); + +// Enter SVG Elements +module.exports = function(vars) { + + if ( vars.dev.value ) print.time("creating SVG elements"); + + // Enter SVG + vars.svg = vars.container.value.selectAll("svg#d3plus").data([0]); + vars.svg.enter().insert("svg","#d3plus_message") + .attr("id","d3plus") + .attr("width",vars.width.value) + .attr("height",vars.height.value) + .attr("xmlns","http://www.w3.org/2000/svg") + .attr("xmlns:xlink","http://www.w3.org/1999/xlink"); + + // Enter BG Rectangle + vars.g.bg = vars.svg.selectAll("rect#bg").data(["bg"]); + vars.g.bg.enter().append("rect") + .attr("id","bg") + .attr("fill",vars.background.value) + .attr("stroke", "none") + .attr("width",vars.width.value) + .attr("height",vars.height.value); + + // Enter Timeline Group + vars.g.timeline = vars.svg.selectAll("g#timeline").data(["timeline"]); + vars.g.timeline.enter().append("g") + .attr("id","timeline") + .attr("transform","translate(0,"+vars.height.value+")"); + + // Enter Key Group + vars.g.legend = vars.svg.selectAll("g#key").data(["key"]); + vars.g.legend.enter().append("g") + .attr("id","key") + .attr("transform","translate(0,"+vars.height.value+")"); + + // Enter Footer Group + vars.g.footer = vars.svg.selectAll("g#footer").data(["footer"]); + vars.g.footer.enter().append("g") + .attr("id","footer") + .attr("transform","translate(0,"+vars.height.value+")"); + + // Enter App Clipping Mask + var clipID = "clipping_" + vars.container.id; + vars.g.clipping = vars.svg.selectAll("#clipping").data(["clipping"]); + vars.g.clipping.enter().append("clipPath") + .attr("id", clipID) + .append("rect") + .attr("width",vars.width.viz) + .attr("height",vars.height.viz); + + // Enter Container Group + vars.g.container = vars.svg.selectAll("g#container").data(["container"]); + vars.g.container.enter().append("g") + .attr("id","container") + .attr("clip-path","url(#" + clipID + ")") + .attr("transform","translate("+vars.margin.left+","+vars.margin.top+")"); + + // Enter Zoom Group + vars.g.zoom = vars.g.container.selectAll("g#zoom").data(["zoom"]); + vars.g.zoom.enter().append("g") + .attr("id","zoom"); + + // Enter App Background Group + vars.g.viz = vars.g.zoom.selectAll("g#d3plus_viz").data(["d3plus_viz"]); + vars.g.viz.enter().append("g") + .attr("id","d3plus_viz"); + + // Enter App Overlay Rect + vars.g.overlay = vars.g.viz.selectAll("rect#d3plus_overlay").data([{"id":"d3plus_overlay"}]); + vars.g.overlay.enter().append("rect") + .attr("id","d3plus_overlay") + .attr("width",vars.width.value) + .attr("height",vars.height.value) + .attr("opacity",0); + + vars.g.overlay + .on(events.move,function(d){ + + if (touch) touchEvent(vars, d3.event); + + if (vars.types[vars.type.value].zoom && vars.zoom.pan.value && + vars.zoom.behavior.scaleExtent()[0] < vars.zoom.scale) { + d3.select(this).style("cursor",prefix()+"grab"); + } + else { + d3.select(this).style("cursor","auto"); + } + + }) + .on(events.up,function(d){ + + if (touch) touchEvent(vars, d3.event); + + if (vars.types[vars.type.value].zoom && vars.zoom.pan.value && + vars.zoom.behavior.scaleExtent()[0] < vars.zoom.scale) { + d3.select(this).style("cursor",prefix()+"grab"); + } + else { + d3.select(this).style("cursor","auto"); + } + + }) + .on(events.down,function(d){ + + if (touch) touchEvent(vars, d3.event); + + if (vars.types[vars.type.value].zoom && vars.zoom.pan.value && + vars.zoom.behavior.scaleExtent()[0] < vars.zoom.scale) { + d3.select(this).style("cursor",prefix()+"grabbing"); + } + else { + d3.select(this).style("cursor","auto"); + } + + }); + + // Enter App Background Group + vars.g.app = vars.g.viz.selectAll("g#app").data(["app"]); + vars.g.app.enter().append("g") + .attr("id","app"); + + // Enter Edges Group + vars.g.edges = vars.g.viz.selectAll("g#edges").data(["edges"]); + vars.g.edges.enter().append("g") + .attr("id","edges") + .attr("opacity",0); + + // Enter Edge Focus Group + vars.g.edge_focus = vars.g.viz.selectAll("g#focus").data(["focus"]); + vars.g.edge_focus.enter().append("g") + .attr("id","focus"); + + // Enter Edge Hover Group + vars.g.edge_hover = vars.g.viz.selectAll("g#edge_hover").data(["edge_hover"]); + vars.g.edge_hover.enter().append("g") + .attr("id","edge_hover") + .attr("opacity",0); + + // Enter App Data Group + vars.g.data = vars.g.viz.selectAll("g#data").data(["data"]); + vars.g.data.enter().append("g") + .attr("id","data") + .attr("opacity",0); + + // Enter Data Focus Group + vars.g.data_focus = vars.g.viz.selectAll("g#data_focus").data(["data_focus"]); + vars.g.data_focus.enter().append("g") + .attr("id","data_focus"); + + // Enter Top Label Group + vars.g.labels = vars.g.viz.selectAll("g#d3plus_labels").data(["d3plus_labels"]); + vars.g.labels.enter().append("g") + .attr("id","d3plus_labels"); + + vars.defs = vars.svg.selectAll("defs").data(["defs"]); + vars.defs.enter().append("defs"); + + if ( vars.dev.value ) print.timeEnd("creating SVG elements"); + +}; + +},{"../../../client/pointer.coffee":40,"../../../client/prefix.coffee":41,"../../../client/touch.coffee":45,"../../../core/console/print.coffee":54,"../zoom/propagation.coffee":256}],242:[function(require,module,exports){ +var print = require("../../../core/console/print.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Updating Elements +//------------------------------------------------------------------------------ +module.exports = function(vars) { + + if ( vars.dev.value ) print.time("updating SVG elements") + + if ( vars.draw.timing ) { + + // Update Parent Element + vars.container.value.transition().duration(vars.draw.timing) + .style("width",vars.width.value+"px") + .style("height",vars.height.value+"px") + + // Update SVG + vars.svg.transition().duration(vars.draw.timing) + .attr("width",vars.width.value) + .attr("height",vars.height.value) + + // Update Background Rectangle + vars.g.bg.transition().duration(vars.draw.timing) + .attr("width",vars.width.value) + .attr("height",vars.height.value) + .attr("fill",vars.background.value); + + // Update App Clipping Rectangle + vars.g.clipping.select("rect").transition().duration(vars.draw.timing) + .attr("width",vars.width.viz) + .attr("height",vars.height.viz) + + // Update Container Groups + vars.g.container.transition().duration(vars.draw.timing) + .attr("transform","translate("+vars.margin.left+","+vars.margin.top+")") + + } + else { + + // Update Parent Element + vars.container.value + .style("width",vars.width.value+"px") + .style("height",vars.height.value+"px") + + // Update SVG + vars.svg + .attr("width",vars.width.value) + .attr("height",vars.height.value) + + // Update Background Rectangle + vars.g.bg + .attr("width",vars.width.value) + .attr("height",vars.height.value) + .attr("fill",vars.background.value); + + // Update App Clipping Rectangle + vars.g.clipping.select("rect") + .attr("width",vars.width.viz) + .attr("height",vars.height.viz) + + // Update Container Groups + vars.g.container + .attr("transform","translate("+vars.margin.left+","+vars.margin.top+")") + + } + + if ( vars.dev.value ) print.timeEnd("updating SVG elements") + +} + +},{"../../../core/console/print.coffee":54}],243:[function(require,module,exports){ +var arraySort = require("../../../array/sort.coffee"), + createTooltip = require("../../../tooltip/create.js"), + dataNest = require("../../../core/data/nest.js"), + fetchData = require("./data.js"), + fetchColor = require("../../../core/fetch/color.coffee"), + fetchText = require("../../../core/fetch/text.js"), + fetchValue = require("../../../core/fetch/value.coffee"), + mergeObject = require("../../../object/merge.coffee"), + removeTooltip = require("../../../tooltip/remove.coffee"), + segments = require("../shapes/segments.coffee"), + scroll = require("../../../client/scroll.js"), + uniques = require("../../../util/uniques.coffee"), + validObject = require("../../../object/validate.coffee"), + zoomDirection = require("../zoom/direction.coffee"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates correctly formatted tooltip for Apps +//------------------------------------------------------------------- +module.exports = function(params) { + + if ( !( "d3plus" in params.data ) ) { + params.data.d3plus = {} + } + + var vars = params.vars, + d = params.data, + dataDepth = "d3plus" in d && "depth" in d.d3plus ? d.d3plus.depth : vars.depth.value, + ex = params.ex, + mouse = params.mouseevents ? params.mouseevents : false, + arrow = "arrow" in params ? params.arrow : true, + id = fetchValue(vars,d,vars.id.value), + tooltip_id = params.id || vars.type.value + + if ((d3.event && d3.event.type == "click") && (vars.tooltip.html.value || vars.tooltip.value.long) && !("fullscreen" in params)) { + var fullscreen = true, + arrow = false, + mouse = true, + length = "long", + footer = vars.footer.value + + vars.covered = true + } + else { + var fullscreen = false, + align = params.anchor || vars.tooltip.anchor, + length = params.length || "short", + zoom = zoomDirection(d, vars) + + if (zoom === -1) { + var key = vars.id.nesting[dataDepth-1], + parent = fetchValue(vars,id,key) + } + + var text = ""; + if (!(!vars.mouse.click.value || (vars.mouse.viz && vars.mouse.viz.click === false))) { + if (zoom === 1 && vars.zoom.value) { + var text = vars.format.value(vars.format.locale.value.ui.expand) + } + else if (zoom === -1 && vars.zoom.value && vars.history.states.length && !vars.tooltip.value.long) { + var text = vars.format.value(vars.format.locale.value.ui.collapse) + } + else if (!vars.small && length == "short" && (vars.tooltip.html.value || vars.tooltip.value.long) && (vars.focus.value.length !== 1 || vars.focus.value[0] != id)) { + var text = vars.format.locale.value.ui.moreInfo + } + else if (length == "long") { + var text = vars.footer.value || "" + } + } + + var footer = text.length ? vars.format.value(text,{"key": "footer", "vars": vars}) : false + + } + + if ("x" in params) { + var x = params.x; + } + else if (vars.types[vars.type.value].tooltip === "static") { + var x = d.d3plus.x; + if (vars.zoom.translate && vars.zoom.scale) { + x = vars.zoom.translate[0]+x*vars.zoom.scale; + } + x += vars.margin.left; + if (params.length !== "long") { + y += scroll.x(); + x += vars.container.value.node().getBoundingClientRect().left; + x += parseFloat(vars.container.value.style("padding-left"), 10); + } + } + else { + var x = d3.mouse(d3.select("html").node())[0]; + } + + if ("y" in params) { + var y = params.y; + } + else if (vars.types[vars.type.value].tooltip == "static") { + var y = d.d3plus.y; + if (vars.zoom.translate && vars.zoom.scale) { + y = vars.zoom.translate[1]+y*vars.zoom.scale; + } + y += vars.margin.top; + if (params.length !== "long") { + y += scroll.y(); + y += vars.container.value.node().getBoundingClientRect().top; + y += parseFloat(vars.container.value.style("padding-top"), 10); + } + } + else { + var y = d3.mouse(d3.select("html").node())[1]; + } + + if ("offset" in params) { + var offset = params.offset; + } + else if (vars.types[vars.type.value].tooltip == "static") { + var offset = d.d3plus.r ? d.d3plus.r : d.d3plus.height/2; + if (vars.zoom.scale) { + offset = offset * vars.zoom.scale; + } + } + else { + var offset = 3; + } + + function make_tooltip(html) { + + var titleDepth = "depth" in params ? params.depth : dataDepth; + + var ex = {}, + children, + depth = vars.id.nesting[titleDepth+1] in d ? titleDepth + 1 : titleDepth, + nestKey = vars.id.nesting[depth], + nameList = "merged" in d.d3plus ? d.d3plus.merged : d[nestKey]; + + if (!(nameList instanceof Array)) nameList = [nameList]; + + var dataValue = fetchValue( vars , d , vars.size.value ); + + if (vars.tooltip.children.value) { + + nameList = nameList.slice(0); + if (nameList.length > 1 && validObject(nameList[0])) nameList = dataNest(vars, nameList, [nestKey]); + + if (vars.size.value && validObject(nameList[0])) { + + var namesNoValues = []; + var namesWithValues = nameList.filter(function(n){ + var val = fetchValue(vars, n, vars.size.value); + if (val !== null && (!("d3plus" in n) || !n.d3plus.merged)) { + return true; + } + else { + namesNoValues.push(n); + } + }); + + arraySort(namesWithValues, vars.size.value, "desc", [], vars); + + nameList = namesWithValues.concat(namesNoValues); + + } + + var maxChildrenShownInShortMode = vars.tooltip.children.value === true ? 3 : vars.tooltip.children.value; + var limit = length === "short" ? maxChildrenShownInShortMode : vars.data.large, + listLength = nameList.length, + max = d3.min([listLength , limit]), + objs = []; + + children = {"values": []}; + for (var i = 0; i < max; i++) { + + if (!nameList.length) break; + + var obj = nameList.shift(), + name = fetchText(vars, obj, depth)[0], + id = validObject(obj) ? fetchValue(vars, obj, nestKey, depth) : obj; + + if (id !== d[vars.id.nesting[titleDepth]] && name && !children[name]) { + + var value = validObject(obj) ? fetchValue(vars, obj, vars.size.value, nestKey) : null, + color = fetchColor(vars, obj, nestKey); + + children[name] = value && !(value instanceof Array) ? vars.format.value(value, {"key": vars.size.value, "vars": vars, "data": obj}) : ""; + var child = {}; + child[name] = children[name]; + children.values.push(child); + + if (color) { + if ( !children.d3plus_colors ) children.d3plus_colors = {}; + children.d3plus_colors[name] = color; + } + + } + else { + i--; + } + + } + + if ( listLength > max ) { + children.d3plusMore = listLength - max; + } + + } + + if (d.d3plus.tooltip) { + ex = mergeObject(ex, d.d3plus.tooltip); + } + + function getLabel(method) { + return typeof vars[method].value === "string" ? vars[method].value : + vars.format.locale.value.method[method]; + } + + if ( vars.tooltip.size.value ) { + if (dataValue && typeof vars.size.value !== "number") { + ex[getLabel("size")] = dataValue; + } + if (vars.axes.opposite && vars[vars.axes.opposite].value !== vars.size.value) { + ex[getLabel(vars.axes.opposite)] = fetchValue(vars, d, vars[vars.axes.opposite].value); + } + if (vars.axes.opposite && vars[vars.axes.opposite + "2"].value !== vars.size.value) { + ex[getLabel(vars.axes.opposite + "2")] = fetchValue(vars, d, vars[vars.axes.opposite + "2"].value); + } + if (vars.color.valueScale) { + ex[getLabel("color")] = fetchValue(vars, d, vars.color.value); + } + } + + var active = segments(vars, d, "active"), + temp = segments(vars, d, "temp"), + total = segments(vars, d, "total"); + + if (typeof active == "number" && active > 0 && total) { + ex[getLabel("active")] = active+"/"+total+" ("+vars.format.value((active/total)*100, {"key": "share", "vars": vars, "data": d})+")"; + } + + if (typeof temp == "number" && temp > 0 && total) { + ex[getLabel("temp")] = temp+"/"+total+" ("+vars.format.value((temp/total)*100, {"key": "share", "vars": vars, "data": d})+")"; + } + + if ( vars.tooltip.share.value && d.d3plus.share ) { + ex.share = vars.format.value(d.d3plus.share*100, {"key": "share", "vars": vars, "data": d}); + } + + var depth = "depth" in params ? params.depth : dataDepth, + title = params.title || fetchText(vars,d,depth)[0], + icon = uniques(d, vars.icon.value, fetchValue, vars, vars.id.nesting[depth]), + tooltip_data = params.titleOnly ? [] : fetchData(vars,d,length,ex,children,depth); + + if (icon.length === 1 && typeof icon[0] === "string") { + icon = icon[0]; + } + else { + icon = false; + } + + if ((tooltip_data.length > 0 || footer) || ((!d.d3plus_label && length == "short" && title) || (d.d3plus_label && (!("visible" in d.d3plus_label) || ("visible" in d.d3plus_label && d.d3plus_label.visible === false))))) { + + if (!title) { + title = vars.format.value(id, {"key": vars.id.value, "vars": vars}); + } + + var depth = "d3plus" in d && "merged" in d.d3plus ? dataDepth - 1 : "depth" in params ? params.depth : dataDepth; + + if (depth < 0) depth = 0 + + depth = vars.id.nesting[depth] + + if (typeof vars.icon.style.value == "string") { + var icon_style = vars.icon.style.value + } + else if (typeof vars.icon.style.value == "object" && vars.icon.style.value[depth]) { + var icon_style = vars.icon.style.value[depth] + } + else { + var icon_style = "default" + } + + var width = vars.tooltip.small; + if (params.width) { + width = params.width; + } + else if (fullscreen) { + width = vars.tooltip.large; + } + + var parent = (!fullscreen && params.length !== "long") || (fullscreen && vars.tooltip.fullscreen.value) ? d3.select("body") : vars.container.value; + + if (!params.description && d && vars.tooltip.sub.value) { + params.description = fetchValue(vars, d, vars.tooltip.sub.value); + } + + createTooltip({ + "align": align, + "arrow": arrow, + "locale": vars.format.locale.value, + "background": vars.tooltip.background, + "curtain": vars.tooltip.curtain.color, + "curtainopacity": vars.tooltip.curtain.opacity, + "fontcolor": vars.tooltip.font.color, + "fontfamily": vars.tooltip.font.family.value, + "fontsize": vars.tooltip.font.size, + "fontweight": vars.tooltip.font.weight, + "data": tooltip_data, + "color": fetchColor(vars, d), + "allColors": true, + "footer": params.footer === false ? params.footer : footer, + "fullscreen": fullscreen, + "html": html, + "js": params.js, + "icon": icon, + "id": tooltip_id, + "max_height": params.maxheight, + "max_width": width, + "mouseevents": mouse, + "offset": offset, + "parent": parent, + "stacked": vars.tooltip.stacked.value, + "style": icon_style, + "title": title, + "description": params.description, + "width": !params.width && !fullscreen && tooltip_data.length == 0 ? "auto" : width, + "x": x, + "y": y + }) + + } + else { + removeTooltip(tooltip_id) + } + + } + + if (fullscreen || params.length === "long") { + + if (typeof vars.tooltip.html.value == "string") { + make_tooltip(vars.tooltip.html.value) + } + else if (typeof vars.tooltip.html.value == "function") { + make_tooltip(vars.tooltip.html.value(id)) + } + else if (vars.tooltip.html.value && typeof vars.tooltip.html.value == "object" && vars.tooltip.html.value.url) { + var tooltip_url = vars.tooltip.html.value.url; + if (typeof tooltip_url === "function") tooltip_url = tooltip_url(id); + d3.json(tooltip_url,function(data){ + var html = vars.tooltip.html.value.callback ? vars.tooltip.html.value.callback(data) : data + make_tooltip(html) + }) + } + else { + make_tooltip(params.html) + } + + } + else { + make_tooltip(params.html) + } + +} + +},{"../../../array/sort.coffee":36,"../../../client/scroll.js":43,"../../../core/data/nest.js":62,"../../../core/fetch/color.coffee":65,"../../../core/fetch/text.js":68,"../../../core/fetch/value.coffee":69,"../../../object/merge.coffee":174,"../../../object/validate.coffee":175,"../../../tooltip/create.js":204,"../../../tooltip/remove.coffee":206,"../../../util/uniques.coffee":213,"../shapes/segments.coffee":236,"../zoom/direction.coffee":253,"./data.js":244}],244:[function(require,module,exports){ +var copy = require("../../../util/copy.coffee"), + fetchValue = require("../../../core/fetch/value.coffee"), + fetchColor = require("../../../core/fetch/color.coffee"), + fetchText = require("../../../core/fetch/text.js"), + legible = require("../../../color/legible.coffee"), + mergeObject = require("../../../object/merge.coffee"), + prefix = require("../../../client/prefix.coffee"), + stringFormat = require("../../../string/format.js"), + validObject = require("../../../object/validate.coffee"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates a data object for the Tooltip +//------------------------------------------------------------------------------ +module.exports = function(vars, id, length, extras, children, depth) { + + if (vars.small) { + return [] + } + + if (!length) var length = "long" + if (length == "long") { + var other_length = "short" + } + else { + var other_length = "long" + } + + var extra_data = {} + if (extras && typeof extras == "string") extras = [extras] + else if (extras && typeof extras == "object") { + extra_data = mergeObject(extra_data,extras) + var extras = [] + for ( var k in extra_data ) { + extras.push(k) + } + } + else if (!extras) var extras = [] + + var tooltip_highlights = [] + + if (vars.tooltip.value instanceof Array) { + var a = vars.tooltip.value + } + else if (typeof vars.tooltip.value == "string") { + var a = [vars.tooltip.value] + } + else { + + if (vars.tooltip.value[vars.id.nesting[depth]]) { + var a = vars.tooltip.value[vars.id.nesting[depth]] + } + else { + var a = vars.tooltip.value + } + + if (!(a instanceof Array)) { + + if (a[length]) { + a = a[length] + } + else if (a[other_length]) { + a = [] + } + else { + a = mergeObject({"":[]},a) + } + + } + + if (typeof a == "string") { + a = [a] + } + else if (!(a instanceof Array)) { + a = mergeObject({"":[]},a) + } + + } + + function format_key(key,group) { + + if (vars.attrs.value[group]) var id_var = group + else var id_var = null + + if (group) group = vars.format.value(group) + + var value = extra_data[key] || fetchValue(vars,id,key,id_var) + + if (validObject(value)) { + tooltip_data.push({ + "name": vars.format.value(key), + "value": vars.format.value(value.value, {"key": value.key, "vars": vars}), + "group": group + }) + } + else if (value != null && value != "undefined" && !(value instanceof Array) && ((typeof value === "string" && value.indexOf("d3plus_other") < 0) || !(typeof value === "string"))) { + var name = vars.format.locale.value.ui[key] + ? vars.format.value(vars.format.locale.value.ui[key]) + : vars.format.value(key), + h = tooltip_highlights.indexOf(key) >= 0 + + if ( value instanceof Array ) { + value.forEach(function(v){ + v = vars.format.value(v, {"key": key, "vars": vars, "data": id}) + }) + } + else { + value = vars.format.value(value, {"key": key, "vars": vars, "data": id}) + } + + var obj = {"name": name, "value": value, "highlight": h, "group": group} + + if ( vars.descs.value ) { + + if ( typeof vars.descs.value === "function" ) { + var descReturn = vars.descs.value( key ) + if ( typeof descReturn === "string" ) { + obj.desc = descReturn + } + } + else if ( key in vars.descs.value ) { + obj.desc = vars.descs.value[key] + } + + } + + tooltip_data.push(obj) + + } + + } + + var tooltip_data = [] + if (a.constructor === Array) a = {"": a}; + + if (vars.id.nesting.length && depth < vars.id.nesting.length-1) { + var a = copy(a) + vars.id.nesting.forEach(function(n,i){ + if (i > depth && a[n]) delete a[n] + }) + } + + for (var group in a) { + if (a[group].constructor !== Array) a[group] = [a[group]] + for (var i = extras.length; i > 0; i--) { + if (a[group].indexOf(extras[i-1]) >= 0) { + extras.splice(i-1, 1); + } + } + } + + if (vars.tooltip.value.long && typeof vars.tooltip.value.long == "object") { + var placed = [] + + for (var group in vars.tooltip.value.long) { + + for (var i = extras.length; i > 0; i--) { + var e = extras[i-1]; + if (vars.tooltip.value.long[group].indexOf(e) >= 0) { + if (!a[group]) a[group] = []; + a[group].push(e); + extras.splice(i-1, 1); + } + } + + } + + } + + if (extras.length) { + if (!a[""]) a[""] = [] + a[""] = a[""].concat(extras); + } + + for (var group in a) { + a[group].forEach(function(t){ + format_key(t, group); + }); + } + + if ( children ) { + + var title = vars.format.locale.value.ui.including + , colors = children.d3plus_colors + + children.values.forEach(function(child) { + var name = d3.keys(child)[0]; + tooltip_data.push({ + "group": vars.format.value(title), + "highlight": colors && colors[name] ? colors[name] : false, + "name": name, + "value": child[name] + }) + }); + + if (children.d3plusMore) { + + tooltip_data.push({ + "group": vars.format.value(title), + "highlight": true, + "name": stringFormat(vars.format.locale.value.ui.more, children.d3plusMore), + "value": "" + }) + + } + + } + + if ( vars.tooltip.connections.value && length === "long" ) { + + var connections = vars.edges.connections( id[vars.id.value] , vars.id.value , true ) + + if ( connections.length ) { + connections.forEach(function(conn){ + + var c = vars.data.viz.filter(function(d){ + return d[vars.id.value] === conn[vars.id.value] + }) + + var c = c.length ? c[0] : conn + + var name = fetchText(vars,c)[0], + color = fetchColor(vars,c), + size = vars.tooltip.font.size, + radius = vars.shape.value == "square" ? 0 : size + styles = [ + "background-color: "+color, + "border-color: "+legible(color), + "border-style: solid", + "border-width: "+vars.data.stroke.width+"px", + "display: inline-block", + "height: "+size+"px", + "left: 0px", + "position: absolute", + "width: "+size+"px", + "top: 0px", + prefix()+"border-radius: "+radius+"px", + ] + node = "
" + + var nodeClick = function() { + vars.self.focus([c[vars.id.value]]).draw() + } + + tooltip_data.push({ + "group": vars.format.value(vars.format.locale.value.ui.primary), + "highlight": false, + "link": nodeClick, + "name": "" + }) + + }) + } + + } + + return tooltip_data + +} + +},{"../../../client/prefix.coffee":41,"../../../color/legible.coffee":46,"../../../core/fetch/color.coffee":65,"../../../core/fetch/text.js":68,"../../../core/fetch/value.coffee":69,"../../../object/merge.coffee":174,"../../../object/validate.coffee":175,"../../../string/format.js":176,"../../../util/copy.coffee":210}],245:[function(require,module,exports){ +var print; + +print = require("../../../core/console/print.coffee"); + +module.exports = function(vars) { + var app, d, dataRequired, drawable, i, len, ref, requirements, returned, visualization; + vars.group = vars.g.apps[vars.type.value]; + vars.mouse.viz = false; + vars.edges.path = false; + visualization = vars.types[vars.type.value]; + requirements = visualization.requirements || []; + dataRequired = requirements.indexOf("data") >= 0; + drawable = !dataRequired || (dataRequired && vars.data.viz.length); + if (!vars.error.internal && drawable) { + app = vars.format.locale.value.visualization[vars.type.value]; + if (vars.dev.value) { + print.time("running " + app); + } + ref = vars.data.viz; + for (i = 0, len = ref.length; i < len; i++) { + d = ref[i]; + if (d.d3plus) { + delete d.d3plus.shape; + delete d.d3plus.label; + delete d.d3plus.rotate; + delete d.d3plus.share; + } + } + returned = visualization(vars); + if (vars.dev.value) { + print.timeEnd("running " + app); + } + } else { + returned = null; + } + vars.returned = { + nodes: [], + edges: null + }; + if (returned instanceof Array) { + vars.returned.nodes = returned; + } else if (returned) { + if (returned.nodes) { + vars.returned.nodes = returned.nodes; + } + if (returned.edges) { + vars.returned.edges = returned.edges; + } + } +}; + + +},{"../../../core/console/print.coffee":54}],246:[function(require,module,exports){ +var copy = require("../../../util/copy.coffee"), + form = require("../../../form/form.js"), + print = require("../../../core/console/print.coffee"), + validObject = require("../../../object/validate.coffee"); + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws a UI drawer, if defined. +//------------------------------------------------------------------------------ +module.exports = function( vars ) { + + var enabled = vars.ui.value && vars.ui.value.length, + position = vars.ui.position.value; + + if ( vars.dev.value && enabled ) print.time("drawing custom UI elements"); + + var drawer = vars.container.value.selectAll("div#d3plus_drawer") + .data(["d3plus_drawer"]); + + drawer.enter().append("div") + .attr("id","d3plus_drawer"); + + var positionStyles = {}; + vars.ui.position.accepted.forEach(function(p){ + positionStyles[p] = p == position ? vars.margin.bottom+"px" : "auto"; + }); + + drawer + .style("text-align",vars.ui.align.value) + .style("position","absolute") + .style("width",vars.width.value-(vars.ui.padding*2)+"px") + .style("height","auto") + .style(positionStyles); + + var ui = drawer.selectAll("div.d3plus_drawer_ui") + .data(enabled ? vars.ui.value : [], function(d){ + return d.method || false; + }); + + ui.exit().remove(); + + ui.enter().append("div") + .attr("class","d3plus_drawer_ui") + .style("display","inline-block"); + + ui.style("padding",vars.ui.padding+"px") + .each(function(d){ + + if (!d.form) { + + d.form = form() + .container(d3.select(this)) + .data({"sort": false}) + .id("id") + .text("text"); + + } + + var focus, callback; + + if (typeof d.method === "string" && d.method in vars) { + focus = vars[d.method].value; + callback = function(value) { + if ( value !== vars[d.method].value ) { + vars.self[d.method](value).draw(); + } + }; + } + else { + focus = d.focus || d.value[0]; + if (validObject(focus)) focus = focus[d3.keys(focus)[0]]; + if (typeof d.method === "function") { + callback = function(value) { + if (value !== focus) { + focus = value; + d.focus = value; + d.method(value, vars.self); + } + }; + } + } + + var data = [], title; + + if (d.label) { + title = d.label; + } + else if (typeof d.method === "string" && d.method in vars) { + title = vars.format.locale.value.method[d.method] || d.method; + } + + d.value.forEach(function(o){ + + var obj = {}; + + if (validObject(o)) { + obj.id = o[d3.keys(o)[0]]; + obj.text = vars.format.value(d3.keys(o)[0]); + } + else { + obj.id = o; + obj.text = vars.format.value(o); + } + + data.push(obj); + + }); + + var font = copy(vars.ui.font); + font.align = copy(vars.font.align); + font.secondary = copy(font); + + d.form + .data(data) + .font(font) + .focus(d.value.length > 1 ? focus : false) + .focus({"callback": callback}) + .format(vars.format.locale.language) + .format({ + "number": vars.format.number.value, + "text": vars.format.text.value + }) + .title(vars.format.value(title)) + .type(d.type || "auto") + .ui({ + "align": vars.ui.align.value, + "border": vars.ui.border, + "color": { + "primary": vars.ui.color.primary.value, + "secondary": vars.ui.color.secondary.value + }, + "padding": vars.ui.padding, + "margin": 0 + }) + .width(d.width || false) + .draw(); + + }); + + var drawerHeight = drawer.node().offsetHeight || drawer.node().getBoundingClientRect().height; + + if ( drawerHeight ) { + vars.margin[position] += drawerHeight; + } + + if ( vars.dev.value && enabled ) print.timeEnd("drawing custom UI elements"); + +}; + +},{"../../../core/console/print.coffee":54,"../../../form/form.js":106,"../../../object/validate.coffee":175,"../../../util/copy.coffee":210}],247:[function(require,module,exports){ +var events, lighter, print, stylesheet; + +events = require("../../../client/pointer.coffee"); + +lighter = require("../../../color/lighter.coffee"); + +print = require("../../../core/console/print.coffee"); + +stylesheet = require("../../../client/css.coffee"); + +module.exports = function(vars) { + var button, color, containerPadding, enter, family, left, min_height, padding, size, stripY, style, titleClass, titleGroup, top, weight; + if (!vars.small && vars.history.states.length > 0) { + if (vars.dev.value) { + print.time("drawing back button"); + } + button = vars.container.value.selectAll("div#d3plus_back_button").data(["d3plus_back_button"]).style("position", "relative").style("z-index", 1900); + size = vars.title.sub.font.size; + color = vars.title.sub.font.color; + family = vars.title.sub.font.family.value; + weight = vars.title.sub.font.weight; + padding = vars.title.sub.padding; + titleClass = false; + if (vars.title.sub.value && ["start", "left"].indexOf(vars.title.sub.font.align) < 0) { + titleClass = "sub"; + } else if (vars.title.total.value && ["start", "left"].indexOf(vars.title.total.font.align) < 0) { + titleClass = "total"; + } else if (vars.title.value && ["start", "left"].indexOf(vars.title.font.align) < 0) { + titleClass = "title"; + } + if (titleClass) { + stripY = function(elem) { + var y; + y = elem.attr("transform").match(/translate\(([^a-z]+)\)/gi)[0]; + y = y.replace(/([^a-z])\s([^a-z])/gi, "$1,$2"); + y = y.split(","); + y = y[y.length - 1]; + return parseFloat(y.substring(0, y.length - 1)); + }; + titleGroup = vars.svg.select(".d3plus_title." + titleClass); + top = stripY(titleGroup) + stripY(titleGroup.select("text")); + } else { + top = vars.margin.top - vars.title.padding; + min_height = size + padding * 2; + vars.margin.top += min_height; + } + containerPadding = parseFloat(vars.container.value.style("padding-top"), 10); + top += containerPadding; + containerPadding = parseFloat(vars.container.value.style("padding-left"), 10); + left = vars.margin.left + size / 2 + containerPadding; + style = function(elem) { + return elem.style("position", "absolute").style("left", left + "px").style("top", top + "px").style("color", color).style("font-family", family).style("font-weight", weight).style("font-size", size + "px"); + }; + enter = button.enter().append("div").attr("id", "d3plus_back_button").style("opacity", 0).call(style).html(function() { + var arrow; + if (stylesheet("font-awesome") && vars.icon.back.value.indexOf("fa-") === 0) { + arrow = ""; + } else { + arrow = vars.icon.back.value + " "; + } + return arrow + vars.format.value(vars.format.locale.value.ui.back); + }); + button.on(events.over, function() { + if (!vars.small && vars.history.states.length > 0) { + return d3.select(this).style("cursor", "pointer").transition().duration(vars.timing.mouseevents).style("color", lighter(color, .25)); + } + }).on(events.out, function() { + if (!vars.small && vars.history.states.length > 0) { + return d3.select(this).style("cursor", "auto").transition().duration(vars.timing.mouseevents).style("color", color); + } + }).on(events.click, function() { + return vars.history.back(); + }).transition().duration(vars.draw.timing).style("opacity", 1).call(style); + if (vars.dev.value) { + return print.timeEnd("drawing back button"); + } + } else { + return vars.container.value.selectAll("div#d3plus_back_button").transition().duration(vars.draw.timing).style("opacity", 0).remove(); + } +}; + + +},{"../../../client/css.coffee":38,"../../../client/pointer.coffee":40,"../../../color/lighter.coffee":47,"../../../core/console/print.coffee":54}],248:[function(require,module,exports){ +var arraySort = require("../../../array/sort.coffee"), + buckets = require("../../../util/buckets.coffee"), + copy = require("../../../util/copy.coffee"), + createTooltip = require("../tooltip/create.js"), + dataNest = require("../../../core/data/nest.js"), + dataURL = require("../../../util/dataURL.coffee"), + events = require("../../../client/pointer.coffee"), + fetchValue = require("../../../core/fetch/value.coffee"), + fetchColor = require("../../../core/fetch/color.coffee"), + fetchText = require("../../../core/fetch/text.js"), + print = require("../../../core/console/print.coffee"), + removeTooltip = require("../../../tooltip/remove.coffee"), + textColor = require("../../../color/text.coffee"), + uniqueValues = require("../../../util/uniques.coffee"), + scroll = require("../../../client/scroll.js"), + stringStrip = require("../../../string/strip.js"), + textWrap = require("../../../textwrap/textwrap.coffee"), + touch = require("../../../client/touch.coffee"), + validObject = require("../../../object/validate.coffee"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates color key +//------------------------------------------------------------------------------ +module.exports = function(vars) { + + var key_display = true, + square_size = 0; + + if (!vars.error.internal && vars.color.value && !vars.small && vars.legend.value) { + + if (!vars.color.valueScale) { + + if ( vars.dev.value ) print.time("grouping data by colors"); + + var data; + if ( vars.nodes.value && vars.types[vars.type.value].requirements.indexOf("nodes") >= 0 ) { + data = copy(vars.nodes.restriced || vars.nodes.value); + if ( vars.data.viz.length ) { + for (var i = 0 ; i < data.length ; i++) { + var appData = vars.data.viz.filter(function(a){ + return a[vars.id.value] === data[i][vars.id.value]; + }); + if (appData.length) { + data[i] = appData[0]; + } + } + } + } + else { + data = vars.data.viz; + } + + if (data.length && "key" in data[0] && "values" in data[0]) { + data = d3.merge(data.map(function(d){ + return d.values; + })); + } + + var colorFunction = function(d){ + return fetchColor(vars, d, colorDepth); + }, + colorDepth = 0, + colorKey = vars.id.value; + + var colorIndex = vars.id.nesting.indexOf(vars.color.value); + if (colorIndex >= 0) { + colorDepth = colorIndex; + colorKey = vars.id.nesting[colorIndex]; + } + else { + + for (var n = 0; n <= vars.depth.value; n++) { + + colorDepth = n; + colorKey = vars.id.nesting[n]; + + var uniqueIDs = uniqueValues(data , function(d){ + return fetchValue(vars, d, colorKey); + }), + uniqueColors = uniqueValues(data, colorFunction); + + if (uniqueIDs.length >= uniqueColors.length && uniqueColors.length > 1) { + break; + } + + } + + } + + var legendNesting = [vars.color.value]; + // if (vars.icon.value && vars.legend.icons.value) legendNesting.push(vars.icon.value); + var colors = dataNest(vars, data, legendNesting, false); + + if ( vars.dev.value ) print.timeEnd("grouping data by color") + + var available_width = vars.width.value; + + square_size = vars.legend.size; + + var key_width = square_size*colors.length+vars.ui.padding*(colors.length+1) + + if (square_size instanceof Array) { + + if ( vars.dev.value ) print.time("calculating legend size") + + for (var i = square_size[1]; i >= square_size[0]; i--) { + key_width = i*colors.length+vars.ui.padding*(colors.length+1) + if (available_width >= key_width) { + square_size = i; + break; + } + } + + if ( vars.dev.value ) print.timeEnd("calculating legend size"); + + } + else if (typeof square_size != "number" && square_size !== false) { + square_size = 30; + } + + if (available_width < key_width || colors.length == 1) { + key_display = false; + } + else { + + key_width -= vars.ui.padding*2; + + if ( vars.dev.value ) print.time("sorting legend"); + + if(typeof vars.legend.order.value === "function") { + colors = vars.legend.order.value(colors) + } else { + var order = vars[vars.legend.order.value].value; + + var sort_color = vars.color.value; + if (!order) { + order = vars[vars.color.value].value; + } + else if (vars.legend.order.value !== "color") { + sort_color = []; + } + + arraySort(colors, order, vars.legend.order.sort.value, sort_color, vars, colorDepth); + } + + if ( vars.dev.value ) print.timeEnd("sorting legend"); + + if ( vars.dev.value ) print.time("drawing legend"); + + var start_x; + + if (vars.legend.align == "start") { + start_x = vars.ui.padding; + } + else if (vars.legend.align == "end") { + start_x = available_width - vars.ui.padding - key_width; + } + else { + start_x = available_width/2 - key_width/2; + } + + vars.g.legend.selectAll("g.d3plus_scale") + .transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove(); + + function position(group) { + + group + .attr("transform",function(g,i){ + var x = start_x + (i*(vars.ui.padding+square_size)) + return "translate("+x+","+vars.ui.padding+")" + }) + + } + + function style(rect) { + + rect + .attr("width", square_size) + .attr("height", square_size) + .attr("fill",function(g){ + + d3.select(this.parentNode).select("text").remove(); + + var icon = uniqueValues(g, vars.icon.value, fetchValue, vars, colorKey), + color = fetchColor(vars, g, colorKey); + + if (vars.legend.icons.value && icon.length === 1 && + typeof icon[0] === "string") { + icon = icon[0]; + var short_url = stringStrip(icon+"_"+color), + iconStyle = vars.icon.style.value, + icon_style, + pattern = vars.defs.selectAll("pattern#"+short_url) + .data([short_url]); + + if (typeof iconStyle === "string") { + icon_style = vars.icon.style.value; + } + else if (validObject(iconStyle) && iconStyle[colorKey]) { + icon_style = iconStyle[colorKey]; + } + else { + icon_style = "default"; + } + + color = icon_style == "knockout" ? color : "none"; + + pattern.select("rect").transition().duration(vars.draw.timing) + .attr("fill",color) + .attr("width",square_size) + .attr("height",square_size); + + pattern.select("image").transition().duration(vars.draw.timing) + .attr("width",square_size) + .attr("height",square_size); + + var pattern_enter = pattern.enter().append("pattern") + .attr("id",short_url) + .attr("width",square_size) + .attr("height",square_size); + + pattern_enter.append("rect") + .attr("fill",color) + .attr("stroke", "none") + .attr("width",square_size) + .attr("height",square_size); + + pattern_enter.append("image") + .attr("xlink:href",icon) + .attr("width",square_size) + .attr("height",square_size) + .each(function(d){ + + if (icon.indexOf("/") === 0 || icon.indexOf(window.location.hostname) >= 0) { + dataURL(icon,function(base64){ + pattern.select("image").attr("xlink:href",base64); + }); + } + else { + pattern.select("image").attr("xlink:href",icon); + } + + }); + + return "url(#"+short_url+")"; + } + else { + + if (vars.legend.labels.value) { + + var names; + if (vars.legend.text.value) { + names = [fetchValue(vars, g, vars.legend.text.value, colorDepth)]; + } + else { + names = fetchText(vars, g, colorDepth); + } + + if (names.length === 1 && !(names[0] instanceof Array) && names[0].length) { + + var text = d3.select(this.parentNode).append("text"), + size = vars.legend.font.size; + + if (!(size instanceof Array)) { + size = [size] + } + + text + .attr("font-size", size[size.length-1]+"px") + .attr("font-weight", vars.legend.font.weight) + .attr("font-family", vars.legend.font.family.value) + .attr("stroke", "none") + .attr("fill", textColor(color)) + .attr("x", 0) + .attr("y", 0) + .each(function(t){ + + textWrap() + .align("middle") + .container( d3.select(this) ) + .height(square_size) + .padding(vars.ui.padding) + .resize(size.length > 1) + .size(size) + .text( names[0] ) + .width(square_size) + .valign("middle") + .draw(); + + }) + + if (text.select("tspan").empty()) { + text.remove(); + } + + } + + } + + return color; + } + + }); + + } + + var colorInt = {}; + var keys = vars.g.legend.selectAll("g.d3plus_color") + .data(colors,function(d){ + var c = fetchColor(vars, d, colorKey); + if (!(c in colorInt)) colorInt[c] = -1; + colorInt[c]++; + return colorInt[c]+"_"+c; + }); + + keys.enter().append("g") + .attr("class","d3plus_color") + .attr("opacity",0) + .call(position) + .append("rect") + .attr("class","d3plus_color") + .attr("stroke", "none") + .call(style); + + keys.order() + .transition().duration(vars.draw.timing) + .call(position) + .attr("opacity", 1) + .selectAll("rect.d3plus_color") + .call(style); + + keys.exit() + .transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove(); + + if (vars.legend.tooltip.value) { + + keys + .on(events.over,function(d,i){ + + d3.select(this).style("cursor","pointer"); + + var bounds = this.getBoundingClientRect(), + x = bounds.left + square_size/2 + scroll.x(), + y = bounds.top + square_size/2 + scroll.y() + 5; + + var id = fetchValue(vars, d, colorKey), + idIndex = vars.id.nesting.indexOf(colorKey); + + var title; + if (vars.legend.title.value) { + title = fetchValue(vars, d, vars.legend.title.value, colorDepth); + } + else { + title = idIndex >= 0 ? fetchText(vars,d,idIndex)[0] : + vars.format.value(fetchValue(vars,d,vars.color.value,colorKey), {"key": vars.color.value, "vars": vars, "data": d}); + } + + var html, js; + if (vars.legend.filters.value && !(id instanceof Array)) { + html = "
"; + var loc = vars.format.locale.value; + html += "
"+vars.format.value(loc.method.mute)+"
"; + html += "
"+vars.format.value(loc.method.solo)+"
"; + html += "
" + js = function(tooltip) { + var style = { + "border": "1px solid #ccc", + "display": "inline-block", + "margin": "1px 2px", + "padding": "3px 5px" + } + tooltip.select(".mute") + .style(style) + .on(events.over, function(){ + d3.select(this).style("cursor", "pointer"); + }) + .on(events.click, function(){ + var mute = vars.id.mute.value; + vars.history.states.push(function(){ + vars.self.id({"mute": mute}).draw(); + }) + vars.self.id({"mute": id}).draw(); + }); + tooltip.select(".solo") + .style(style) + .on(events.over, function(){ + d3.select(this).style("cursor", "pointer"); + }) + .on(events.click, function(){ + var solo = vars.id.solo.value; + vars.history.states.push(function(){ + vars.self.id({"solo": solo}).draw(); + }) + vars.self.id({"solo": id}).draw(); + }); + } + } + + createTooltip({ + "data": d, + "html": html, + "js": js, + "depth": colorDepth, + "footer": false, + "vars": vars, + "x": x, + "y": y, + "mouseevents": this, + "title": title, + "titleOnly": !vars.legend.data.value, + "offset": square_size*0.4 + }); + + }) + .on(events.out,function(d){ + removeTooltip(vars.type.value); + }); + + } + + if ( vars.dev.value ) print.timeEnd("drawing legend"); + + } + + } + else if (vars.color.valueScale) { + + if ( vars.dev.value ) print.time("drawing color scale"); + + vars.g.legend.selectAll("g.d3plus_color") + .transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove(); + + var values = vars.color.valueScale.domain(), + colors = vars.color.valueScale.range(); + + if (values.length <= 2) { + values = buckets(values,6); + } + + var scale = vars.g.legend.selectAll("g.d3plus_scale") + .data(["scale"]); + + scale.enter().append("g") + .attr("class","d3plus_scale") + .attr("opacity",0); + + var heatmapId = vars.container.id + "_legend_heatmap"; + + var heatmap = scale.selectAll("#" + heatmapId) + .data(["heatmap"]); + + heatmap.enter().append("linearGradient") + .attr("id", heatmapId) + .attr("x1", "0%") + .attr("y1", "0%") + .attr("x2", "100%") + .attr("y2", "0%") + .attr("spreadMethod", "pad"); + + var stops = heatmap.selectAll("stop") + .data(d3.range(0,colors.length)); + + stops.enter().append("stop") + .attr("stop-opacity",1); + + stops + .attr("offset",function(i){ + return Math.round((i/(colors.length-1))*100)+"%"; + }) + .attr("stop-color",function(i){ + return colors[i]; + }); + + stops.exit().remove(); + + var gradient = scale.selectAll("rect#gradient") + .data(["gradient"]); + + gradient.enter().append("rect") + .attr("id","gradient") + .attr("x",function(d){ + if (vars.legend.align == "middle") { + return vars.width.value/2; + } + else if (vars.legend.align == "end") { + return vars.width.value; + } + else { + return 0; + } + }) + .attr("y",vars.ui.padding) + .attr("width", 0) + .attr("height", vars.legend.gradient.height) + .attr("stroke",vars.legend.font.color) + .attr("stroke-width",1) + .style("fill", "url(#" + heatmapId + ")"); + + var text = scale.selectAll("text.d3plus_tick") + .data(d3.range(0,values.length)); + + text.enter().append("text") + .attr("class","d3plus_tick") + .attr("stroke", "none") + .attr("x",function(d){ + if (vars.legend.align == "middle") { + return vars.width.value/2; + } + else if (vars.legend.align == "end") { + return vars.width.value; + } + else { + return 0; + } + }) + .attr("y",function(d){ + return this.getBBox().height+vars.legend.gradient.height+vars.ui.padding*2; + }); + + var label_width = 0; + + text + .order() + .attr("font-weight",vars.legend.font.weight) + .attr("font-family",vars.legend.font.family.value) + .attr("font-size",vars.legend.font.size+"px") + .style("text-anchor",vars.legend.font.align) + .attr("fill",vars.legend.font.color) + .text(function(d){ + return vars.format.value(values[d], {"key": vars.color.value, "vars": vars}); + }) + .attr("y",function(d){ + return this.getBBox().height+vars.legend.gradient.height+vars.ui.padding*2; + }) + .each(function(d){ + var w = Math.ceil(this.getBBox().width); + if (w > label_width) label_width = w; + }); + + label_width += vars.labels.padding*2; + + var key_width = label_width * (values.length-1); + + if (key_width+label_width < vars.width.value) { + + if (key_width+label_width < vars.width.value/2) { + key_width = vars.width.value/2; + label_width = key_width/values.length; + key_width -= label_width; + } + + var start_x; + if (vars.legend.align == "start") { + start_x = vars.ui.padding; + } + else if (vars.legend.align == "end") { + start_x = vars.width.value - vars.ui.padding - key_width; + } + else { + start_x = vars.width.value/2 - key_width/2; + } + + text.transition().duration(vars.draw.timing) + .attr("x",function(d){ + return start_x + (label_width*d); + }); + + text.exit().transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove(); + + var ticks = scale.selectAll("rect.d3plus_tick") + .data(d3.range(0,values.length)); + + ticks.enter().append("rect") + .attr("class","d3plus_tick") + .attr("x",function(d){ + if (vars.legend.align == "middle") { + return vars.width.value/2; + } + else if (vars.legend.align == "end") { + return vars.width.value; + } + else { + return 0; + } + }) + .attr("y",vars.ui.padding) + .attr("width",0) + .attr("height",vars.ui.padding+vars.legend.gradient.height) + .attr("fill",vars.legend.font.color); + + ticks.transition().duration(vars.draw.timing) + .attr("x",function(d){ + var mod = d === 0 ? 1 : 0; + return start_x + (label_width*d) - mod; + }) + .attr("y",vars.ui.padding) + .attr("width",1) + .attr("height",vars.ui.padding+vars.legend.gradient.height) + .attr("fill",vars.legend.font.color); + + ticks.exit().transition().duration(vars.draw.timing) + .attr("width",0) + .remove(); + + gradient.transition().duration(vars.draw.timing) + .attr("x",function(d){ + if (vars.legend.align == "middle") { + return vars.width.value/2 - key_width/2; + } + else if (vars.legend.align == "end") { + return vars.width.value - key_width - vars.ui.padding; + } + else { + return vars.ui.padding; + } + }) + .attr("y",vars.ui.padding) + .attr("width", key_width) + .attr("height", vars.legend.gradient.height); + + scale.transition().duration(vars.draw.timing) + .attr("opacity",1); + + if ( vars.dev.value ) print.timeEnd("drawing color scale"); + + } + else { + key_display = false; + } + + } + else { + key_display = false; + } + + } + else { + key_display = false; + } + if (vars.legend.value && key && key_display) { + + if ( vars.dev.value ) print.time("positioning legend"); + + if (square_size) { + var key_height = square_size+vars.ui.padding; + } + else { + var key_box = vars.g.legend.node().getBBox(), + key_height = key_box.height+key_box.y; + } + + if (vars.margin.bottom === 0) { + vars.margin.bottom += vars.ui.padding; + } + vars.margin.bottom += key_height; + + vars.g.legend.transition().duration(vars.draw.timing) + .attr("transform","translate(0,"+(vars.height.value-vars.margin.bottom)+")") + + if ( vars.dev.value ) print.timeEnd("positioning legend") + + } + else { + + if ( vars.dev.value ) print.time("hiding legend") + + vars.g.legend.transition().duration(vars.draw.timing) + .attr("transform","translate(0,"+vars.height.value+")") + + if ( vars.dev.value ) print.timeEnd("hiding legend") + + } + +} + +},{"../../../array/sort.coffee":36,"../../../client/pointer.coffee":40,"../../../client/scroll.js":43,"../../../client/touch.coffee":45,"../../../color/text.coffee":52,"../../../core/console/print.coffee":54,"../../../core/data/nest.js":62,"../../../core/fetch/color.coffee":65,"../../../core/fetch/text.js":68,"../../../core/fetch/value.coffee":69,"../../../object/validate.coffee":175,"../../../string/strip.js":178,"../../../textwrap/textwrap.coffee":203,"../../../tooltip/remove.coffee":206,"../../../util/buckets.coffee":207,"../../../util/copy.coffee":210,"../../../util/dataURL.coffee":212,"../../../util/uniques.coffee":213,"../tooltip/create.js":243}],249:[function(require,module,exports){ +var events = require("../../../client/pointer.coffee"), + textColor = require("../../../color/text.coffee"); + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates Centered Server Message +//------------------------------------------------------------------------------ +module.exports = function(vars,message) { + + message = vars.messages.value ? message : null; + + var size = vars.messages.style.value || (message === vars.error.internal ? + "large" : vars.messages.style.backup); + + if (size === "large") { + var font = vars.messages, + position = "center" + } + else { + + if (vars.footer.value) { + var font = vars.footer + } + else if (vars.title.value) { + var font = vars.title + } + else if (vars.title.sub.value) { + var font = vars.title.sub + } + else if (vars.title.total.value) { + var font = vars.title.total + } + else { + var font = vars.title.sub + } + + var position = font.position + + } + + var font = { + "color": font.font.color, + "font-family": font.font.family.value, + "font-weight": font.font.weight, + "font-size": font.font.size+"px", + "padding": font.padding+"px" + } + + var bg = vars.messages.background.value; + if (!bg) { + bg = vars.background.value; + if (bg === "none" || bg === "transparent") { + bg = textColor(font.color); + } + } + + function style(elem) { + + elem + .style(font) + .style("position", "absolute") + .style("background-color", bg) + .style("text-align", "center") + .style("left",function(){ + return position == "center" ? "50%" : "0px" + }) + .style("width",function(){ + return position == "center" ? "auto" : vars.width.value+"px" + }) + .style("margin-left",function(){ + return position == "center" ? -(this.offsetWidth/2)+"px" : "0px"; + }) + .style("top",function(){ + if (position == "center") { + return "50%"; + } + else if (position == "top") { + return "0px" + } + else { + return "auto" + } + }) + .style("bottom",function(){ + if (position == "bottom") { + return "0px" + } + else { + return "auto" + } + }) + .style("margin-top",function(){ + if (size == "large") { + var height = this.offsetHeight || this.getBoundingClientRect().height + return -height/2+"px" + } + return "0px" + }) + + } + + // Enter Message Group + vars.g.message = vars.container.value.selectAll("div#d3plus_message") + .data(["message"]) + + var enter = vars.g.message.enter().append("div") + .attr("id","d3plus_message") + .attr("opacity",0); + + enter.append("div") + .attr("class", "d3plus_message_text") + .style("display", "block"); + + vars.g.message.select(".d3plus_message_text") + .text(message ? message : vars.g.message.text()) + + var online = navigator.onLine, square = 75; + + var branding = vars.g.message.selectAll(".d3plus_message_branding") + .data(vars.messages.branding.value && position === "center" ? [0] : []); + + branding.enter().append("div") + .attr("class", "d3plus_message_branding") + .style("margin-top", "15px") + .style("padding-top", "0px") + .style("display", "block") + .style("font-size", "11px") + .style("background-size", square + "px") + .style("background-position", "center 10px") + .style("background-repeat", "no-repeat") + .style("cursor", "pointer") + .on(events.click, function(){ + window.open("http://www.d3plus.org/", "_blank"); + }); + + var logo = d3.hsl(bg).l < 0.5 ? vars.messages.branding.image.dark : vars.messages.branding.image.light; + + branding + .text(online ? "Powered by:" : "Powered by D3plus") + .style("background-color", online ? bg : "transparent") + .style("background-image", online ? "url('" + logo + "')" : "none") + .style("min-width", online ? square + "px" : "auto") + .style("height", online ? square + "px" : "auto"); + + branding.exit().remove(); + + vars.g.message + .style("display", message ? "inline-block" : "none") + .call(style).style("opacity", message ? 1 : 0) + +} + +},{"../../../client/pointer.coffee":40,"../../../color/text.coffee":52}],250:[function(require,module,exports){ +var closest, css, events, fontSizes, mix, playInterval, prefix, print, textColor, timeDetect; + +closest = require("../../../util/closest.coffee"); + +css = require("../../../client/css.coffee"); + +fontSizes = require("../../../font/sizes.coffee"); + +events = require("../../../client/pointer.coffee"); + +mix = require("../../../color/mix.coffee"); + +prefix = require("../../../client/prefix.coffee"); + +print = require("../../../core/console/print.coffee"); + +textColor = require("../../../color/text.coffee"); + +timeDetect = require("../../../core/data/time.coffee"); + +playInterval = false; + +module.exports = function(vars) { + var availableWidth, background, brush, brushExtent, brush_group, brushed, brushend, d, end, handles, i, init, j, labelWidth, labels, len, max_index, min, min_index, oldWidth, playButton, playIcon, playIconChar, playIconStyle, playStyle, playUpdate, playbackWidth, setYears, start, start_x, step, stopPlayback, tallEnough, text, textFill, textStyle, tickColor, tickStep, ticks, timeFormat, timeReturn, timelineBox, timelineHeight, timelineOffset, timelineWidth, visible, x, yearHeight, yearMS, year_ticks, years; + if (vars.timeline.value && (!vars.error.internal || !vars.data.missing) && !vars.small && vars.data.time && vars.data.time.values.length > 1) { + if (vars.dev.value) { + print.time("drawing timeline"); + } + textStyle = { + "font-weight": vars.ui.font.weight, + "font-family": vars.ui.font.family.value, + "font-size": vars.ui.font.size + "px", + "text-anchor": "middle" + }; + years = vars.data.time.ticks.map(function(d) { + return new Date(d); + }); + timeReturn = timeDetect(vars, { + values: years, + style: textStyle + }); + visible = timeReturn.values.map(Number); + timeFormat = timeReturn.format; + if (vars.time.solo.value.length) { + init = d3.extent(vars.time.solo.value); + for (i = j = 0, len = init.length; j < len; i = ++j) { + d = init[i]; + if (d.constructor !== Date) { + d += ""; + if (d.length === 4 && parseInt(d) + "" === d) { + d += "/01/01"; + } + d = new Date(d); + init[i] = d; + } + } + } else { + init = d3.extent(years); + } + year_ticks = years.slice(); + yearHeight = d3.max(timeReturn.sizes.map(function(t) { + return t.height; + })); + labelWidth = ~~(d3.max(timeReturn.sizes.map(function(t) { + return t.width; + }))) + 1; + labelWidth += vars.ui.padding * 2; + timelineHeight = vars.timeline.height.value || yearHeight + vars.ui.padding * 2; + timelineWidth = labelWidth * years.length; + playbackWidth = timelineHeight; + tallEnough = timelineHeight - vars.ui.padding * 2 >= yearHeight; + availableWidth = vars.width.value - vars.ui.padding * 2; + if (tallEnough && vars.timeline.play.value) { + availableWidth -= playbackWidth + vars.ui.padding; + } + if (!tallEnough || visible.length < years.length || availableWidth < labelWidth * visible.length) { + oldWidth = labelWidth; + labelWidth = (availableWidth - labelWidth) / years.length; + timelineWidth = labelWidth * years.length; + timelineOffset = 1; + tickStep = ~~(oldWidth / (timelineWidth / visible.length)) + 1; + while (tickStep < visible.length - 1) { + if ((visible.length - 1) % tickStep === 0) { + break; + } + tickStep++; + } + visible = visible.filter(function(t, i) { + return i % tickStep === 0; + }); + } else { + timelineOffset = 0; + min = new Date(years[0]); + step = vars.data.time.stepType; + min["set" + step](min["get" + step]() + years.length); + year_ticks.push(min); + } + start = new Date(init[0]); + start = closest(year_ticks, start); + end = new Date(init[1]); + if (!timelineOffset) { + end["set" + vars.data.time.stepType](end["get" + vars.data.time.stepType]() + 1); + } + end = closest(year_ticks, end); + yearMS = year_ticks.map(Number); + min_index = yearMS.indexOf(+start); + max_index = yearMS.indexOf(+end); + brushExtent = [start, end]; + if (vars.timeline.align === "start") { + start_x = vars.ui.padding; + } else if (vars.timeline.align === "end") { + start_x = vars.width.value - vars.ui.padding - timelineWidth; + } else { + start_x = vars.width.value / 2 - timelineWidth / 2; + } + if (tallEnough && vars.timeline.play.value) { + start_x += (playbackWidth + vars.ui.padding) / 2; + } + stopPlayback = function() { + clearInterval(playInterval); + playInterval = false; + return playIcon.call(playIconChar, "icon"); + }; + brushed = function() { + var extent, max_val, min_val; + if (d3.event.sourceEvent !== null) { + if (playInterval) { + stopPlayback(); + } + brushExtent = brush.extent(); + min_val = closest(year_ticks, brushExtent[0]); + max_val = closest(year_ticks, brushExtent[1]); + if (min_val === max_val) { + min_index = yearMS.indexOf(+min_val); + if (min_val < brushExtent[0] || min_index === 0) { + max_val = year_ticks[min_index + 1]; + } else { + min_val = year_ticks[min_index - 1]; + } + } + min_index = yearMS.indexOf(+min_val); + max_index = yearMS.indexOf(+max_val); + if (max_index - min_index >= 1) { + extent = [min_val, max_val]; + } else if (min_index + 1 <= years.length) { + extent = [min_val, year_ticks[min_index + 1]]; + } else { + extent = [min_val]; + i = 1; + while (i <= 1) { + if (min_index + i <= years.length) { + extent.push(year_ticks[min_index + i]); + } else { + extent.unshift(year_ticks[min_index - ((min_index + i) - years.length)]); + } + i++; + } + extent = [extent[0], extent[extent.length - 1]]; + } + brushExtent = extent; + text.attr("fill", textFill); + return d3.select(this).call(brush.extent(extent)); + } + }; + setYears = function() { + var newYears; + if (max_index - min_index === years.length - timelineOffset) { + newYears = []; + } else { + newYears = yearMS.filter(function(t, i) { + return i >= min_index && i < (max_index + timelineOffset); + }); + newYears = newYears.map(function(t) { + return new Date(t); + }); + } + playUpdate(); + return vars.self.time({ + "solo": newYears + }).draw(); + }; + brushend = function() { + var change, old_max, old_min, solo; + if (d3.event.sourceEvent !== null) { + if (vars.time.solo.value.length) { + solo = d3.extent(vars.time.solo.value); + old_min = yearMS.indexOf(+closest(year_ticks, solo[0])); + old_max = yearMS.indexOf(+closest(year_ticks, solo[1])); + change = old_min !== min_index || old_max !== max_index; + } else { + change = max_index - min_index !== years.length - timelineOffset; + } + if (change) { + return setYears(); + } + } + }; + playButton = vars.g.timeline.selectAll("rect.d3plus_timeline_play").data(tallEnough && vars.timeline.play.value ? [0] : []); + playStyle = function(btn) { + return btn.attr("width", playbackWidth + 1).attr("height", timelineHeight + 1).attr("fill", vars.ui.color.primary.value).attr("stroke", vars.ui.color.primary.value).attr("stroke-width", 1).attr("x", start_x - playbackWidth - 1 - vars.ui.padding).attr("y", vars.ui.padding); + }; + playButton.enter().append("rect").attr("class", "d3plus_timeline_play").attr("shape-rendering", "crispEdges").attr("opacity", 0).call(playStyle); + playButton.transition().duration(vars.draw.timing).call(playStyle); + playButton.exit().transition().duration(vars.draw.timing).attr("opacity", 0).remove(); + playIcon = vars.g.timeline.selectAll("text.d3plus_timeline_playIcon").data(tallEnough && vars.timeline.play.value ? [0] : []); + playIconChar = function(text, char) { + var font; + char = vars.timeline.play[char]; + if (css("font-awesome")) { + char = char.awesome; + font = "FontAwesome"; + } else { + char = char.fallback; + font = "inherit"; + } + return text.style("font-family", font).text(char); + }; + playIconStyle = function(text) { + var y; + y = timelineHeight / 2 + vars.ui.padding + 1; + return text.attr("fill", textColor(vars.ui.color.primary.value)).attr("stroke", "none").attr(textStyle).attr("x", start_x - (playbackWidth - 1) / 2 - vars.ui.padding).attr("y", y).attr("dy", "0.5ex").call(playIconChar, playInterval ? "pause" : "icon"); + }; + playIcon.enter().append("text").attr("class", "d3plus_timeline_playIcon").call(playIconStyle).style("pointer-events", "none").attr("opacity", 0); + playIcon.call(playIconStyle).transition().duration(vars.draw.timing).attr("opacity", 1); + playIcon.exit().transition().duration(vars.draw.timing).attr("opacity", 0).remove(); + playUpdate = function() { + if (max_index - min_index === years.length - timelineOffset) { + playButton.on(events.hover, null).on(events.click, null).transition().duration(vars.draw.timing).attr("opacity", 0.3); + return playIcon.transition().duration(vars.draw.timing).attr("opacity", 0.3); + } else { + playButton.on(events.over, function() { + return d3.select(this).style("cursor", "pointer"); + }).on(events.out, function() { + return d3.select(this).style("cursor", "auto"); + }).on(events.click, function() { + if (playInterval) { + return stopPlayback(); + } else { + playIcon.call(playIconChar, "pause"); + if (max_index === years.length) { + max_index = max_index - min_index; + min_index = 0; + } else { + min_index++; + max_index++; + } + setYears(); + return playInterval = setInterval(function() { + if (max_index === years.length - timelineOffset) { + return stopPlayback(); + } else { + min_index++; + max_index++; + return setYears(); + } + }, vars.timeline.play.timing.value); + } + }).transition().duration(vars.draw.timing).attr("opacity", 1); + return playIcon.transition().duration(vars.draw.timing).attr("opacity", 1); + } + }; + playUpdate(); + textFill = function(d) { + var color, less, opacity; + less = timelineOffset ? d <= brushExtent[1] : d < brushExtent[1]; + if (d >= brushExtent[0] && less) { + opacity = 1; + color = textColor(vars.ui.color.secondary.value); + } else { + opacity = 0.5; + color = textColor(vars.ui.color.primary.value); + } + if (timelineOffset && vars.background.value && vars.background.value !== "none") { + color = d3.rgb(textColor(vars.background.value)); + } + color = d3.rgb(color); + return "rgba(" + color.r + "," + color.g + "," + color.b + "," + opacity + ")"; + }; + background = vars.g.timeline.selectAll("rect.d3plus_timeline_background").data(["background"]); + background.enter().append("rect").attr("class", "d3plus_timeline_background").attr("shape-rendering", "crispEdges").attr("width", timelineWidth + 2).attr("height", timelineHeight + 2).attr("fill", vars.ui.color.primary.value).attr("x", start_x - 1).attr("y", vars.ui.padding); + background.transition().duration(vars.draw.timing).attr("width", timelineWidth + 2).attr("height", timelineHeight + 2).attr("fill", vars.ui.color.primary.value).attr("x", start_x - 1).attr("y", vars.ui.padding); + ticks = vars.g.timeline.selectAll("g#ticks").data(["ticks"]); + ticks.enter().append("g").attr("id", "ticks").attr("transform", "translate(" + vars.width.value / 2 + "," + vars.ui.padding + ")"); + brush_group = vars.g.timeline.selectAll("g#brush").data(["brush"]); + brush_group.enter().append("g").attr("id", "brush"); + labels = vars.g.timeline.selectAll("g#labels").data(["labels"]); + labels.enter().append("g").attr("id", "labels"); + text = labels.selectAll("text").data(years, function(d, i) { + return i; + }); + text.enter().append("text").attr("stroke", "none").attr("y", 0).attr("dy", "0.5ex").attr("x", 0); + x = d3.time.scale().domain(d3.extent(year_ticks)).rangeRound([0, timelineWidth]); + text.order().attr(textStyle).text(function(d, i) { + if (visible.indexOf(+d) >= 0) { + return timeFormat(d); + } else { + return ""; + } + }).attr("opacity", function(d, i) { + if (vars.data.time.dataSteps.indexOf(i) >= 0) { + return 1; + } else { + return 0.4; + } + }).attr("fill", textFill).attr("transform", function(d, i) { + var dx, dy; + dx = start_x + x(d); + if (!timelineOffset) { + dx += labelWidth / 2; + } + dy = timelineHeight / 2 + vars.ui.padding + 1; + if (timelineOffset) { + dy += timelineHeight / 2 + yearHeight; + } + return "translate(" + Math.round(dx) + "," + Math.round(dy) + ")"; + }); + text.exit().transition().duration(vars.draw.timing).attr("opacity", 0).remove(); + brush = d3.svg.brush().x(x).extent(brushExtent).on("brush", brushed).on("brushend", brushend); + if (vars.axes.discrete && vars[vars.axes.discrete].value === vars.time.value) { + tickColor = vars[vars.axes.discrete].ticks.color; + } else { + tickColor = vars.x.ticks.color; + } + ticks.attr("transform", "translate(" + start_x + "," + (vars.ui.padding + 1) + ")").transition().duration(vars.draw.timing).call(d3.svg.axis().scale(x).orient("top").ticks(function() { + return year_ticks; + }).tickFormat("").tickSize(-timelineHeight).tickPadding(0)).selectAll("line").attr("stroke-width", 1).attr("shape-rendering", "crispEdges").attr("stroke", function(d) { + if (visible.indexOf(+d) >= 0) { + return tickColor; + } else { + return mix(tickColor, vars.background.value, 0.4, 1); + } + }); + ticks.selectAll("path").attr("fill", "none"); + brush_group.attr("transform", "translate(" + start_x + "," + (vars.ui.padding + 1) + ")").attr("opacity", 1).call(brush); + text.attr("pointer-events", "none"); + brush_group.selectAll("rect.background").attr("fill", "none").style("visibility", "visible").attr("height", timelineHeight).attr("shape-rendering", "crispEdges").on(events.move, function() { + var c; + c = vars.timeline.hover.value; + if (["grab", "grabbing"].indexOf(c) >= 0) { + c = prefix() + c; + } + return d3.select(this).style("cursor", c); + }); + brush_group.selectAll("rect.extent").attr("opacity", 0.75).attr("height", timelineHeight).attr("fill", vars.ui.color.secondary.value).attr("shape-rendering", "crispEdges").on(events.move, function() { + var c; + c = vars.timeline.hover.value; + if (["grab", "grabbing"].indexOf(c) >= 0) { + c = prefix() + c; + } + return d3.select(this).style("cursor", c); + }); + if (vars.timeline.handles.value) { + handles = brush_group.selectAll("g.resize").selectAll("rect.d3plus_handle").data(["d3plus_handle"]); + handles.enter().insert("rect", "rect").attr("class", "d3plus_handle"); + handles.attr("fill", vars.timeline.handles.color).attr("transform", function(d) { + var mod; + if (this.parentNode.className.baseVal === "resize e") { + mod = -vars.timeline.handles.size; + } else { + mod = 0; + } + return "translate(" + mod + ",0)"; + }).attr("width", vars.timeline.handles.size).style("visibility", "visible").attr("shape-rendering", "crispEdges").attr("opacity", vars.timeline.handles.opacity); + brush_group.selectAll("g.resize").selectAll("rect").attr("height", timelineHeight); + } else { + brush_group.selectAll("g.resize").remove(); + } + timelineBox = vars.g.timeline.node().getBBox(); + if (vars.margin.bottom === 0) { + vars.margin.bottom += vars.ui.padding; + } + vars.margin.bottom += timelineBox.height + timelineBox.y; + vars.g.timeline.transition().duration(vars.draw.timing).attr("transform", "translate(0," + Math.round(vars.height.value - vars.margin.bottom - vars.ui.padding / 2) + ")"); + vars.margin.bottom += vars.ui.padding; + if (vars.dev.value) { + return print.time("drawing timeline"); + } + } else { + return vars.g.timeline.transition().duration(vars.draw.timing).attr("transform", "translate(0," + vars.height.value + ")"); + } +}; + + +},{"../../../client/css.coffee":38,"../../../client/pointer.coffee":40,"../../../client/prefix.coffee":41,"../../../color/mix.coffee":48,"../../../color/text.coffee":52,"../../../core/console/print.coffee":54,"../../../core/data/time.coffee":64,"../../../font/sizes.coffee":104,"../../../util/closest.coffee":209}],251:[function(require,module,exports){ +var events = require("../../../client/pointer.coffee"), + fetchValue = require("../../../core/fetch/value.coffee"), + print = require("../../../core/console/print.coffee"), + rtl = require("../../../client/rtl.coffee"), + textWrap = require("../../../textwrap/textwrap.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws appropriate titles +//------------------------------------------------------------------------------ +module.exports = function(vars) { + + var total_key = vars.size.value ? vars.size.value + : vars.color.type === "number" ? vars.color.value : false + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If there is no data or the title bar is not needed, + // set the total value to 'null' + //---------------------------------------------------------------------------- + if (!vars.data.viz || !vars.title.total.value || vars.small) { + var total = false + } + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Otherwise, let's calculate it! + //---------------------------------------------------------------------------- + else if (total_key) { + + if ( vars.dev.value ) { + print.time("calculating total value") + } + + var total_data = vars.data.pool; + if (vars.focus.value.length) { + total_data = vars.data.viz.filter(function(d){ + return d[vars.id.value] == vars.focus.value[0]; + }); + } + + var agg = vars.aggs.value[total_key] || "sum"; + var total; + if (agg.constructor === Function) { + total = agg(total_data); + } + else { + + total_data = total_data.reduce(function(arr, d){ + var vals = fetchValue(vars, d, total_key); + if (vals instanceof Array) arr = arr.concat(vals); + else arr.push(vals); + return arr; + }, []); + + total = d3[agg](total_data); + } + + if (total === 0 || total === null || total === undefined) { + total = false + } + + if (typeof total === "number") { + + var pct = "" + + if (vars.data.mute.length || vars.data.solo.length || vars.focus.value.length) { + + var overall_total = d3.sum(vars.data.value, function(d){ + if (vars.time.solo.value.length > 0) { + var match = vars.time.solo.value.indexOf(fetchValue(vars,d,vars.time.value)) >= 0 + } + else if (vars.time.mute.value.length > 0) { + var match = vars.time.solo.value.indexOf(fetchValue(vars,d,vars.time.value)) < 0 + } + else { + var match = true + } + if (match) { + return fetchValue(vars,d,total_key) + } + }) + + if (overall_total > total) { + + var pct = (total/overall_total)*100, + ot = vars.format.value(overall_total, {"key": vars.size.value, "vars": vars}); + + pct = " ("+vars.format.value(pct,{"key": "share", "vars": vars})+" of "+ot+")"; + + } + } + + total = vars.format.value(total, {"key": vars.size.value, "vars": vars}) + var obj = vars.title.total.value + , prefix = obj.prefix || vars.format.value(vars.format.locale.value.ui.total)+": " + total = prefix + total + obj.suffix ? total = total + obj.suffix : null + total += pct + + } + + if ( vars.dev.value ) { + print.timeEnd("calculating total value") + } + + } + else { + var total = false + } + + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialize titles and detect footer + //---------------------------------------------------------------------------- + var title_data = [] + + if (vars.footer.value) { + title_data.push({ + "link": vars.footer.link, + "style": vars.footer, + "type": "footer", + "value": vars.footer.value + }) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If not in "small" mode, detect titles available + //---------------------------------------------------------------------------- + if (!vars.small) { + + if (vars.title.value) { + var title = vars.title.value; + if (typeof title === "function") title = title(vars.self); + title_data.push({ + "link": vars.title.link, + "style": vars.title, + "type": "title", + "value": title + }) + } + if (vars.title.sub.value) { + var title = vars.title.sub.value; + if (typeof title === "function") title = title(vars.self); + title_data.push({ + "link": vars.title.sub.link, + "style": vars.title.sub, + "type": "sub", + "value": title + }) + } + if (vars.title.total.value && total) { + title_data.push({ + "link": vars.title.total.link, + "style": vars.title.total, + "type": "total", + "value": total + }) + } + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Enter Titles + //---------------------------------------------------------------------------- + function style(title) { + + title + .attr("font-size",function(t){ + return t.style.font.size + }) + .attr("fill",function(t){ + return t.link ? vars.links.font.color : t.style.font.color + }) + .attr("font-family",function(t){ + return t.link ? vars.links.font.family.value : t.style.font.family.value + }) + .attr("font-weight",function(t){ + return t.link ? vars.links.font.weight : t.style.font.weight + }) + .style("text-decoration",function(t){ + return t.link ? vars.links.font.decoration.value : t.style.font.decoration.value + }) + .style("text-transform",function(t){ + return t.link ? vars.links.font.transform.value : t.style.font.transform.value + }) + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Enter Titles + //---------------------------------------------------------------------------- + if ( vars.dev.value ) print.time("drawing titles") + var titles = vars.svg.selectAll("g.d3plus_title") + .data(title_data,function(t){ + return t.type + }) + + var titleWidth = vars.title.width || vars.width.value-vars.margin.left-vars.margin.right; + + titles.enter().append("g") + .attr("class", function(t){ + return "d3plus_title " + t.type; + }) + .attr("opacity",0) + .append("text") + .attr("stroke", "none") + .call(style) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Wrap text and calculate positions, then transition style and opacity + //---------------------------------------------------------------------------- + function getAlign(d) { + var align = d.style.font.align; + if (align == "center") { + return "middle"; + } + else if ((align == "left" && !rtl) || (align == "right" && rtl)) { + return "start"; + } + else if ((align == "left" && rtl) || (align == "right" && !rtl)) { + return "end"; + } + return align; + } + titles + .each(function(d){ + + var container = d3.select(this).select("text").call(style); + + var align = getAlign(d); + + textWrap() + .align(align) + .container(container) + .height(vars.height.value / 2) + .size(false) + .text(d.value) + .width(titleWidth) + .draw() + + d.y = vars.margin[d.style.position] + vars.margin[d.style.position] += this.getBBox().height + d.style.padding*2 + + }) + .on(events.over,function(t){ + if (t.link) { + d3.select(this) + .transition().duration(vars.timing.mouseevents) + .style("cursor","pointer") + .select("text") + .attr("fill",vars.links.hover.color) + .attr("font-family",vars.links.hover.family.value) + .attr("font-weight",vars.links.hover.weight) + .style("text-decoration",vars.links.hover.decoration.value) + .style("text-transform",vars.links.hover.transform.value) + } + }) + .on(events.out,function(t){ + if (t.link) { + d3.select(this) + .transition().duration(vars.timing.mouseevents) + .style("cursor","auto") + .select("text") + .call(style) + } + }) + .on(events.click,function(t){ + if (t.link) { + var target = t.link.charAt(0) != "/" ? "_blank" : "_self" + window.open(t.link,target) + } + }) + .attr("opacity",1) + .attr("transform",function(t){ + var pos = t.style.position, + y = pos == "top" ? 0+t.y : vars.height.value-t.y + if (pos == "bottom") { + y -= this.getBBox().height+t.style.padding + } + else { + y += t.style.padding + } + var align = getAlign(t); + if (align === "start") { + var x = vars.margin.left + vars.title.padding; + } + else { + var w = d3.select(this).select("text").node().getBBox().width; + if (align === "middle") { + x = vars.width.value/2 - titleWidth/2; + } + else { + x = vars.width.value - titleWidth - vars.margin.right - vars.title.padding; + } + } + return "translate("+x+","+y+")"; + }) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Exit unused titles + //---------------------------------------------------------------------------- + titles.exit().transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove() + + if ( vars.margin.top > 0 ) { + vars.margin.top += vars.title.padding + } + + if ( vars.margin.bottom > 0 ) { + vars.margin.bottom += vars.title.padding + } + + var min = vars.title.height + if (min && vars.margin[vars.title.position] < min) { + vars.margin[vars.title.position] = min + } + + if ( vars.dev.value ) print.timeEnd("drawing titles") + +} + +},{"../../../client/pointer.coffee":40,"../../../client/rtl.coffee":42,"../../../core/console/print.coffee":54,"../../../core/fetch/value.coffee":69,"../../../textwrap/textwrap.coffee":203}],252:[function(require,module,exports){ +var labels, transform; + +labels = require("./labels.coffee"); + +transform = require("./transform.coffee"); + +module.exports = function(vars, b, timing) { + var aspect, extent, fit, max_scale, min, padding, scale, translate, type; + if (!b) { + b = vars.zoom.bounds; + } + if (typeof timing !== "number") { + timing = vars.timing.transitions; + } + vars.zoom.size = { + height: b[1][1] - b[0][1], + width: b[1][0] - b[0][0] + }; + type = vars.types[vars.type.value]; + fit = vars.coords.fit.value; + if (fit === "auto" || type.requirements.indexOf("coords") < 0) { + aspect = d3.max([vars.zoom.size.width / vars.width.viz, vars.zoom.size.height / vars.height.viz]); + } else { + aspect = vars.zoom.size[fit] / vars["app_" + fit]; + } + min = d3.min([vars.width.viz, vars.height.viz]); + padding = type.zoom ? vars.coords.padding * 2 : 0; + scale = ((min - padding) / min) / aspect; + extent = vars.zoom.behavior.scaleExtent(); + if (extent[0] === extent[1] || b === vars.zoom.bounds) { + vars.zoom.behavior.scaleExtent([scale, scale * 16]); + } + max_scale = vars.zoom.behavior.scaleExtent()[1]; + if (scale > max_scale) { + scale = max_scale; + } + vars.zoom.scale = scale; + translate = [vars.width.viz / 2 - (vars.zoom.size.width * scale) / 2 - (b[0][0] * scale), vars.height.viz / 2 - (vars.zoom.size.height * scale) / 2 - (b[0][1] * scale)]; + vars.zoom.translate = translate; + vars.zoom.behavior.translate(translate).scale(scale); + vars.zoom.size = { + height: vars.zoom.bounds[1][1] - vars.zoom.bounds[0][1], + width: vars.zoom.bounds[1][0] - vars.zoom.bounds[0][0] + }; + vars.zoom.reset = false; + if (vars.labels.value || vars.labels.changed) { + labels(vars); + } + return transform(vars, timing); +}; + + +},{"./labels.coffee":254,"./transform.coffee":257}],253:[function(require,module,exports){ +module.exports = function(data, vars) { + var depth, max_depth, nextDepth; + max_depth = vars.id.nesting.length - 1; + depth = vars.depth.value; + nextDepth = vars.id.nesting[depth + 1]; + if (vars.types[vars.type.value].nesting === false) { + return 0; + } else if ((data.d3plus.merged || (nextDepth in data && depth < max_depth)) && (!data || nextDepth in data)) { + return 1; + } else if (((depth === max_depth && depth > 0) || (data && nextDepth && (!(nextDepth in data)))) && (vars.small || !vars.tooltip.html.value)) { + return -1; + } else { + return 0; + } +}; + + +},{}],254:[function(require,module,exports){ +var print; + +print = require("../../../core/console/print.coffee"); + +module.exports = function(vars) { + var opacity, scale; + if (vars.dev.value) { + print.time("determining label visibility"); + } + scale = vars.zoom.behavior.scaleExtent(); + opacity = function(text) { + return text.attr("opacity", function(d) { + var size; + if (!d) { + d = {}; + } + size = parseFloat(d3.select(this).attr("font-size"), 10); + d.visible = size * (vars.zoom.scale / scale[1]) >= 2; + if (d.visible) { + return 1; + } else { + return 0; + } + }); + }; + if (vars.draw.timing) { + vars.g.viz.selectAll("text.d3plus_label").transition().duration(vars.draw.timing).call(opacity); + } else { + vars.g.viz.selectAll("text.d3plus_label").call(opacity); + } + if (vars.dev.value) { + return print.timeEnd("determining label visibility"); + } +}; + + +},{"../../../core/console/print.coffee":54}],255:[function(require,module,exports){ +var labels, removeTooltip, transform; + +labels = require("./labels.coffee"); + +removeTooltip = require("../../../tooltip/remove.coffee"); + +transform = require("./transform.coffee"); + +module.exports = function(vars) { + var delay, eventType, limits, scale, translate, xmax, xmin, xoffset, ymax, ymin, yoffset; + eventType = d3.event.sourceEvent ? d3.event.sourceEvent.type : null; + translate = d3.event.translate; + scale = d3.event.scale; + limits = vars.zoom.bounds; + xoffset = (vars.width.viz - (vars.zoom.size.width * scale)) / 2; + xmin = (xoffset > 0 ? xoffset : 0); + xmax = (xoffset > 0 ? vars.width.viz - xoffset : vars.width.viz); + yoffset = (vars.height.viz - (vars.zoom.size.height * scale)) / 2; + ymin = (yoffset > 0 ? yoffset : 0); + ymax = (yoffset > 0 ? vars.height.viz - yoffset : vars.height.viz); + if (translate[0] + limits[0][0] * scale > xmin) { + translate[0] = -limits[0][0] * scale + xmin; + } else if (translate[0] + limits[1][0] * scale < xmax) { + translate[0] = xmax - (limits[1][0] * scale); + } + if (translate[1] + limits[0][1] * scale > ymin) { + translate[1] = -limits[0][1] * scale + ymin; + } else if (translate[1] + limits[1][1] * scale < ymax) { + translate[1] = ymax - (limits[1][1] * scale); + } + vars.zoom.behavior.translate(translate).scale(scale); + vars.zoom.translate = translate; + vars.zoom.scale = scale; + if (eventType === "wheel") { + removeTooltip(vars.type.value); + } + if (vars.labels.value || vars.labels.changed) { + if (eventType === "wheel") { + delay = (vars.draw.timing ? 100 : 250); + clearTimeout(vars.zoom.wheel); + vars.zoom.wheel = setTimeout(function() { + return labels(vars); + }, delay); + } else { + labels(vars); + } + } + if (eventType === "dblclick") { + return transform(vars, vars.timing.transitions); + } else { + return transform(vars, 0); + } +}; + + +},{"../../../tooltip/remove.coffee":206,"./labels.coffee":254,"./transform.coffee":257}],256:[function(require,module,exports){ +module.exports = function(vars, event) { + var enabled, zoom, zoomable, zoomed; + zoom = vars.zoom; + if (!event) { + event = d3.event; + } + zoomed = zoom.scale > zoom.behavior.scaleExtent()[0]; + enabled = vars.types[vars.type.value].zoom && zoom.value && zoom.scroll.value; + zoomable = event.touches && event.touches.length > 1 && enabled; + if (!zoomable && !zoomed) { + event.stopPropagation(); + } +}; + + +},{}],257:[function(require,module,exports){ +module.exports = function(vars, timing) { + var translate; + if (typeof timing !== "number") { + timing = vars.timing.transitions; + } + translate = "translate(" + vars.zoom.translate + ")"; + translate += "scale(" + vars.zoom.scale + ")"; + if (timing) { + return vars.g.viz.transition().duration(timing).attr("transform", translate); + } else { + return vars.g.viz.attr("transform", translate); + } +}; + + +},{}],258:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [false, Function, Object, String], + deprecates: "active_var", + mute: filter(true), + solo: filter(true), + spotlight: { + accepted: [Boolean], + deprecates: "spotlight", + value: false + }, + value: false +}; + + +},{"../../core/methods/filter.coffee":83}],259:[function(require,module,exports){ +module.exports = { + accepted: [Object], + deprecated: "nesting_aggs", + objectAccess: false, + value: {} +}; + + +},{}],260:[function(require,module,exports){ +var process; + +process = require("../../core/methods/process/data.coffee"); + +module.exports = { + accepted: [false, Array, Object, String], + delimiter: { + accepted: String, + value: "|" + }, + filetype: { + accepted: [false, "json", "xml", "html", "csv", "dsv", "tsv", "txt"], + value: false + }, + keys: {}, + process: process, + value: false +}; + + +},{"../../core/methods/process/data.coffee":89}],261:[function(require,module,exports){ +var process, rendering; + +process = require("../../core/methods/process/margin.coffee"); + +rendering = require("../../core/methods/rendering.coffee"); + +module.exports = { + background: { + color: "#fafafa", + rendering: rendering(), + stroke: { + color: "#ccc", + width: 1 + } + }, + margin: { + accepted: [Number, Object, String], + process: function(value) { + var userValue; + if (value === void 0) { + value = this.value; + } + userValue = value; + process(value, this); + return userValue; + }, + value: 10 + }, + mirror: { + accepted: [Boolean], + deprecates: ["mirror_axis", "mirror_axes"], + value: false + }, + ticks: { + accepted: [Boolean], + value: true + } +}; + + +},{"../../core/methods/process/margin.coffee":92,"../../core/methods/rendering.coffee":94}],262:[function(require,module,exports){ +module.exports = { + accepted: [String], + value: "#ffffff" +}; + + +},{}],263:[function(require,module,exports){ +module.exports = { + accepted: [Function, String], + value: false +}; + + +},{}],264:[function(require,module,exports){ +var filter, scale; + +filter = require("../../core/methods/filter.coffee"); + +scale = require("../../color/scale.coffee"); + +module.exports = { + accepted: [false, Array, Function, Object, String], + deprecates: "color_var", + domain: { + accepted: [false, Array], + value: false + }, + focus: "#444444", + heatmap: ["#282F6B", "#419391", "#AFD5E8", "#EACE3F", "#B35C1E", "#B22200"], + missing: "#eeeeee", + mute: filter(true), + primary: "#d74b03", + range: ["#B22200", "#FFEE8D", "#759143"], + scale: { + accepted: [Array, Function, "d3plus", "category10", "category20", "category20b", "category20c"], + process: function(value) { + if (value instanceof Array) { + return d3.scale.ordinal().range(value); + } else if (value === "d3plus") { + return scale; + } else if (typeof value === "string") { + return d3.scale[value](); + } else { + return value; + } + }, + value: "d3plus" + }, + solo: filter(true), + secondary: "#e5b3bb", + value: false +}; + + +},{"../../color/scale.coffee":50,"../../core/methods/filter.coffee":83}],265:[function(require,module,exports){ +module.exports = { + "accepted": [Array, Function, String], + "index": { + "accepted": [Boolean], + "value": true + }, + "process": function(value, vars) { + if (typeof value === "string") value = [value] + return value + }, + "value": false +} + +},{}],266:[function(require,module,exports){ +arguments[4][110][0].apply(exports,arguments) +},{"dup":110}],267:[function(require,module,exports){ +var d3selection; + +d3selection = require("../../util/d3selection.coffee"); + +module.exports = { + accepted: [false, Array, Object, String], + id: "default", + process: function(value, vars) { + if (value === false) { + return false; + } + if (vars.container.id === "default") { + vars.self.container({ + id: "d3plus_" + +new Date() + }); + } + if (d3selection(value)) { + return value.append("div"); + } else if (value instanceof Array) { + return d3.select(value[0][0]).append("div"); + } else { + this.selector = value; + return d3.select(value).append("div"); + } + }, + value: false +}; + + +},{"../../util/d3selection.coffee":211}],268:[function(require,module,exports){ +var filter, process; + +filter = require("../../core/methods/filter.coffee"); + +process = require("../../core/methods/process/data.coffee"); + +module.exports = { + accepted: [false, Array, Function, Object, String], + center: [0, 0], + filetype: { + accepted: ["json"], + value: "json" + }, + fit: { + accepted: ["auto", "height", "width"], + value: "auto" + }, + key: false, + mute: filter(false), + padding: 20, + process: process, + projection: { + accepted: ["albers", "albersUsa", "azimuthalEqualArea", "azimuthalEquidistant", "conicConformal", "conicEqualArea", "conicEquidistant", "equirectangular", "gnomonic", "mercator", "orthographic", "stereographic", "transverseMercator", Function], + value: "mercator" + }, + simplify: { + accepted: [Boolean], + value: true + }, + solo: filter(false), + threshold: { + accepted: [Number], + value: 0.9 + }, + value: false +}; + + +},{"../../core/methods/filter.coffee":83,"../../core/methods/process/data.coffee":89}],269:[function(require,module,exports){ +var fetchValue, ie, stringStrip; + +fetchValue = require("../../core/fetch/value.coffee"); + +ie = require("../../client/ie.js"); + +stringStrip = require("../../string/strip.js"); + +module.exports = { + accepted: [void 0, true, Array, String], + chainable: false, + data: [], + process: function(value, vars) { + var blob, c, col, columns, csv_data, csv_to_return, d, dataString, encodedUri, i, j, k, l, len, len1, len2, len3, len4, len5, len6, len7, link, m, max_filename_len, n, node, o, p, q, ref, ref1, ref2, row, title, titles, val; + if (vars.returned === void 0) { + return []; + } + value = value || vars.cols.value; + if (value instanceof Array) { + columns = value; + } else if (typeof value === "string") { + columns = [value]; + } + csv_to_return = []; + titles = []; + if (vars.title.value) { + title = vars.title.value; + if (typeof title === "function") { + title = title(vars.self); + } + title = stringStrip(title); + max_filename_len = 250; + title = title.substr(0, max_filename_len); + } else { + title = "D3plus Visualization Data"; + } + if (value === true) { + columns = d3.keys(vars.data.keys); + csv_to_return.push(columns); + ref = vars.data.value; + for (j = 0, len = ref.length; j < len; j++) { + d = ref[j]; + row = []; + for (k = 0, len1 = columns.length; k < len1; k++) { + c = columns[k]; + val = d[c]; + if (vars.data.keys[c] === "string") { + val = '"' + val + '"'; + } + row.push(val); + } + csv_to_return.push(row); + } + } else { + if (!columns) { + columns = [vars.id.value]; + if (vars.time.value) { + columns.push(vars.time.value); + } + if (vars.size.value) { + columns.push(vars.size.value); + } + if (vars.text.value) { + columns.push(vars.text.value); + } + } + for (l = 0, len2 = columns.length; l < len2; l++) { + c = columns[l]; + titles.push(vars.format.value(c)); + } + csv_to_return.push(titles); + ref1 = vars.returned.nodes; + for (m = 0, len3 = ref1.length; m < len3; m++) { + node = ref1[m]; + if ((node.values != null) && node.values instanceof Array) { + ref2 = node.values; + for (n = 0, len4 = ref2.length; n < len4; n++) { + val = ref2[n]; + row = []; + for (o = 0, len5 = columns.length; o < len5; o++) { + col = columns[o]; + val = fetchValue(vars, val, col); + if (typeof val === "string") { + val = '"' + val + '"'; + } + row.push(val); + } + csv_to_return.push(row); + } + } else { + row = []; + for (p = 0, len6 = columns.length; p < len6; p++) { + col = columns[p]; + row.push(fetchValue(vars, node, col)); + } + csv_to_return.push(row); + } + } + } + csv_data = "data:text/csv;charset=utf-8,"; + for (i = q = 0, len7 = csv_to_return.length; q < len7; i = ++q) { + c = csv_to_return[i]; + dataString = c.join(","); + csv_data += (i < csv_to_return.length ? dataString + "\n" : dataString); + } + if (ie) { + blob = new Blob([csv_data], { + type: "text/csv;charset=utf-8;" + }); + navigator.msSaveBlob(blob, title + ".csv"); + } else { + encodedUri = encodeURI(csv_data); + link = document.createElement("a"); + link.setAttribute("href", encodedUri); + link.setAttribute("download", title + ".csv"); + link.click(); + } + this.data = csv_to_return; + return columns; + }, + value: void 0 +}; + + +},{"../../client/ie.js":39,"../../core/fetch/value.coffee":69,"../../string/strip.js":178}],270:[function(require,module,exports){ +var process; + +process = require("../../core/methods/process/data.coffee"); + +module.exports = { + accepted: [false, Array, Function, String], + cache: {}, + delimiter: { + accepted: [String], + value: "|" + }, + donut: { + size: 0.35 + }, + filetype: { + accepted: [false, "json", "xml", "html", "csv", "dsv", "tsv", "txt"], + value: false + }, + filters: [], + keys: {}, + mute: [], + large: 400, + opacity: 0.9, + padding: { + accepted: [Number], + value: 1 + }, + process: function(value, vars) { + return process(value, vars, this); + }, + solo: [], + stroke: { + width: 1 + }, + value: false +}; + + +},{"../../core/methods/process/data.coffee":89}],271:[function(require,module,exports){ +module.exports = { + accepted: [Function, Number], + value: 0 +}; + + +},{}],272:[function(require,module,exports){ +module.exports = { + accepted: [false, Function, Object], + value: false +}; + + +},{}],273:[function(require,module,exports){ +arguments[4][114][0].apply(exports,arguments) +},{"dup":114}],274:[function(require,module,exports){ +var print = require("../../core/console/print.coffee"), + stringFormat = require("../../string/format.js") + +module.exports = { + "accepted" : [ undefined , Function ], + "first" : true, + "frozen" : false, + "process" : function (value, vars) { + + if ( this.initialized === false ) { + this.initialized = true + return value + } + + if ( value === undefined && typeof this.value === "function" ) { + value = this.value + } + + if ( vars.container.value === false ) { + + var str = vars.format.locale.value.dev.setContainer + print.warning( str , "container" ) + + } + else if ( vars.container.value.empty() ) { + + var str = vars.format.locale.value.dev.noContainer + var selector = vars.container.selector || ""; + print.warning( stringFormat(str, "\"" + selector + "\"") , "container" ) + + } + else { + + if ( vars.dev.value ) print.time("total draw time"); + + vars.container.value.call(vars.self); + + } + + if ( typeof value === "function" && vars.history.chain.length ) { + + var changesObject = {} + vars.history.chain.forEach(function(c){ + var method = c.method + delete c.method + changesObject[method] = c + }) + + value(changesObject) + + vars.history.chain = [] + + } + + return value + + }, + "update" : true, + "value" : undefined +} + +},{"../../core/console/print.coffee":54,"../../string/format.js":176}],275:[function(require,module,exports){ +var process = require("../../core/methods/process/data.coffee"); + +module.exports = { + "accepted": [false, Array, Function, String], + "arrows": { + "accepted": [ Boolean , Number ], + "direction": { + "accepted": [ "source" , "target" ], + "value": "target" + }, + "value": false + }, + "color": "#d0d0d0", + "connections": function(focus,id,objects) { + + var self = this + + if (!self.value) { + return [] + } + + if (!id) var id = "id" + + var edges = self.restricted || self.value, + targets = [] + + if (!focus) { + return edges + } + + var connections = edges.filter(function(edge){ + + var match = false + + if (edge[self.source][id] == focus) { + match = true + if (objects) { + targets.push(edge[self.target]) + } + } + else if (edge[self.target][id] == focus) { + match = true + if (objects) { + targets.push(edge[self.source]) + } + } + + return match + + }) + + return objects ? targets : connections + + }, + "delimiter": { + "accepted": [ String ], + "value": "|" + }, + "filetype": { + "accepted": [false, "json", "xml","html", "csv", "dsv", "tsv", "txt"], + "value": false + }, + "interpolate": { + "accepted": ["basis", "cardinal", "linear", "monotone", "step"], + "value": "basis" + }, + "label": false, + "large": 100, + "limit": { + "accepted": [false, Function, Number], + "value": false + }, + "opacity": { + "accepted": [Function, Number, String], + "min": { + "accepted": [Number], + "value": 0.25 + }, + "scale": { + "accepted": [Function], + "value": d3.scale.linear() + }, + "value": 1 + }, + "process": process, + "size": { + "accepted": [false, Number, String], + "min": 1, + "scale": 0.5, + "value": false + }, + "source": "source", + "strength": { + "accepted": [false, Function, Number, String], + "value": false + }, + "target": "target", + "value": false +}; + +},{"../../core/methods/process/data.coffee":89}],276:[function(require,module,exports){ +module.exports = { + accepted: [Boolean, String], + value: false +}; + + +},{}],277:[function(require,module,exports){ +module.exports = { + accepted: [false, Array, Function, Number, String], + deprecates: "highlight", + process: function(value) { + if (value === false) { + return []; + } else if (value instanceof Array) { + return value; + } else { + return [value]; + } + }, + tooltip: { + accepted: [Boolean], + value: true + }, + value: [] +}; + + +},{}],278:[function(require,module,exports){ +var align, decoration, family, transform; + +align = require("../../core/methods/font/align.coffee"); + +decoration = require("../../core/methods/font/decoration.coffee"); + +family = require("../../core/methods/font/family.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +module.exports = { + align: align(), + color: "#444444", + decoration: decoration(), + family: family(), + secondary: { + align: align(), + color: "#444444", + decoration: decoration(), + family: family(), + size: 12, + spacing: 0, + transform: transform(), + weight: 200 + }, + size: 12, + spacing: 0, + transform: transform(), + weight: 200 +}; + + +},{"../../core/methods/font/align.coffee":84,"../../core/methods/font/decoration.coffee":85,"../../core/methods/font/family.coffee":86,"../../core/methods/font/transform.coffee":88}],279:[function(require,module,exports){ +var decoration, family, transform; + +family = require("../../core/methods/font/family.coffee"); + +decoration = require("../../core/methods/font/decoration.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +module.exports = { + accepted: [false, Number, String], + font: { + align: "center", + color: "#444", + decoration: decoration(), + family: family(), + size: 11, + transform: transform(), + weight: 200 + }, + link: false, + padding: 0, + position: "bottom", + value: false +}; + + +},{"../../core/methods/font/decoration.coffee":85,"../../core/methods/font/family.coffee":86,"../../core/methods/font/transform.coffee":88}],280:[function(require,module,exports){ +var formatNumber, locale, mergeObject, titleCase; + +formatNumber = require("../../number/format.coffee"); + +locale = require("../../core/locale/locale.coffee"); + +mergeObject = require("../../object/merge.coffee"); + +titleCase = require("../../string/title.coffee"); + +module.exports = { + accepted: [Function, String], + affixes: { + accepted: [Object], + objectAccess: false, + value: {} + }, + deprecates: ["number_format", "text_format"], + locale: { + accepted: function() { + return d3.keys(locale); + }, + process: function(value) { + var defaultLocale, returnObject; + defaultLocale = "en_US"; + returnObject = locale[defaultLocale]; + if (value !== defaultLocale) { + returnObject = mergeObject(returnObject, locale[value]); + } + this.language = value; + return returnObject; + }, + value: "en_US" + }, + number: { + accepted: [false, Function], + value: false + }, + process: function(value, vars) { + if (typeof value === "string") { + vars.self.format({ + locale: value + }); + } else { + if (typeof value === "function") { + return value; + } + } + return this.value; + }, + text: { + accepted: [false, Function], + value: false + }, + value: function(value, opts) { + var f, v, vars; + if (!opts) { + opts = {}; + } + if (!opts.locale) { + opts.locale = this.locale.value; + } + vars = opts.vars || {}; + if (vars.time && vars.time.value && opts.key === vars.time.value) { + v = value.constructor === Date ? value : new Date(value); + return vars.data.time.format(v); + } else if (typeof value === "number") { + f = this.number.value || formatNumber; + return f(value, opts); + } else if (typeof value === "string") { + f = this.text.value || titleCase; + return f(value, opts); + } else { + return JSON.stringify(value); + } + } +}; + + +},{"../../core/locale/locale.coffee":81,"../../number/format.coffee":173,"../../object/merge.coffee":174,"../../string/title.coffee":179}],281:[function(require,module,exports){ +module.exports = { + accepted: [false, Number], + max: 600, + secondary: false, + small: 200, + value: false +}; + + +},{}],282:[function(require,module,exports){ +var align, decoration, family, filter, orientMap, position, rendering, transform; + +align = require("../../../core/methods/font/align.coffee"); + +decoration = require("../../../core/methods/font/decoration.coffee"); + +family = require("../../../core/methods/font/family.coffee"); + +filter = require("../../../core/methods/filter.coffee"); + +position = require("../../../core/methods/font/position.coffee"); + +rendering = require("../../../core/methods/rendering.coffee"); + +transform = require("../../../core/methods/font/transform.coffee"); + +orientMap = { + x: "bottom", + x2: "top", + y: "left", + y2: "right" +}; + +module.exports = function(axis) { + return { + accepted: [Array, Boolean, Function, Object, String], + affixes: { + accepted: [Boolean], + separator: { + accepted: [Boolean, Array], + value: true + }, + value: false + }, + axis: { + accepted: [Boolean], + color: "#444", + font: { + color: false, + decoration: decoration(false), + family: family(""), + size: false, + spacing: 0, + transform: transform(false), + weight: false + }, + rendering: rendering(), + value: true + }, + dataFilter: true, + deprecates: [axis + "axis", axis + "axis_val", axis + "axis_var"], + domain: { + accepted: [false, Array], + value: false + }, + grid: { + accepted: [Boolean], + color: "#ccc", + rendering: rendering(), + value: true + }, + label: { + accepted: [Boolean, String], + fetch: function(vars) { + if (this.value === true) { + return vars.format.value(vars[axis].value, { + key: axis, + vars: vars + }); + } + return this.value; + }, + font: { + color: "#444", + decoration: decoration(), + family: family(), + size: 12, + spacing: 0, + transform: transform(), + weight: 200 + }, + padding: 3, + value: true + }, + lines: { + accept: [false, Array, Number, Object], + dasharray: { + accepted: [Array, String], + process: function(value) { + if (value instanceof Array) { + value = value.filter(function(d) { + return !isNaN(d); + }); + value = value.length ? value.join(", ") : "none"; + } + return value; + }, + value: "10, 10" + }, + color: "#888", + font: { + align: align("right"), + color: "#444", + background: { + accepted: [Boolean], + value: true + }, + decoration: decoration(), + family: family(), + padding: { + accepted: [Number], + value: 10 + }, + position: position("middle"), + size: 12, + transform: transform(), + weight: 200 + }, + process: Array, + rendering: rendering(), + width: 1, + value: [] + }, + mouse: { + accept: [Boolean], + dasharray: { + accepted: [Array, String], + process: function(value) { + if (value instanceof Array) { + value = value.filter(function(d) { + return !isNaN(d); + }); + value = value.length ? value.join(", ") : "none"; + } + return value; + }, + value: "none" + }, + rendering: rendering(), + width: 2, + value: true + }, + mute: filter(true), + orient: { + accepted: ["top", "right", "bottom", "left"], + value: orientMap[axis] + }, + padding: { + accepted: [Number], + value: 0.1 + }, + persist: { + position: { + accepted: [Boolean], + value: false + }, + size: { + accepted: [Boolean], + value: true + } + }, + range: { + accepted: [false, Array], + value: false + }, + scale: { + accepted: ["linear", "log", "discrete", "share"], + deprecates: ["layout", "unique_axis", axis + "axis_scale"], + process: function(value, vars) { + var i, len, ref, scale; + ref = ["log", "discrete", "share"]; + for (i = 0, len = ref.length; i < len; i++) { + scale = ref[i]; + if (scale === value) { + vars.axes[scale] = axis; + } else { + if (vars.axes[scale] === axis) { + vars.axes[scale] = false; + } + } + } + if (value === "discrete") { + vars.axes.opposite = (axis.indexOf("x") === 0 ? "y" : "x"); + } + return value; + }, + value: "linear" + }, + solo: filter(true), + stacked: { + accepted: [Boolean], + process: function(value, vars) { + if (!value && vars.axes.stacked === axis) { + vars.axes.stacked = false; + } else { + if (value) { + vars.axes.stacked = axis; + } + } + return value; + }, + value: false + }, + ticks: { + accepted: [false, Array], + color: "#ccc", + font: { + color: "#666", + decoration: decoration(), + family: family(), + size: 10, + spacing: 0, + transform: transform(), + weight: 200 + }, + labels: { + accepted: [Boolean, Array], + value: true + }, + rendering: rendering(), + size: 10, + width: 1, + value: false + }, + value: false, + zerofill: { + accepted: [Boolean], + value: false + } + }; +}; + + +},{"../../../core/methods/filter.coffee":83,"../../../core/methods/font/align.coffee":84,"../../../core/methods/font/decoration.coffee":85,"../../../core/methods/font/family.coffee":86,"../../../core/methods/font/position.coffee":87,"../../../core/methods/font/transform.coffee":88,"../../../core/methods/rendering.coffee":94}],283:[function(require,module,exports){ +module.exports = { + accepted: [Boolean], + back: function() { + if (this.states.length) { + return this.states.pop()(); + } + }, + chain: [], + reset: function() { + var results; + results = []; + while (this.states.length) { + results.push(this.states.pop()()); + } + return results; + }, + states: [], + value: true +}; + + +},{}],284:[function(require,module,exports){ +var process; + +process = require("../../core/methods/process/icon.coffee"); + +module.exports = { + accepted: [false, Array, Function, Object, String], + back: { + accepted: [false, String], + fallback: "❮", + opacity: 1, + process: process, + rotate: 0, + value: "fa-angle-left" + }, + deprecates: "icon_var", + style: { + accepted: [Object, String], + deprecates: "icon_style", + value: "default" + }, + value: false +}; + + +},{"../../core/methods/process/icon.coffee":91}],285:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [Array, String], + dataFilter: true, + deprecates: ["id_var", "nesting"], + grouping: { + accepted: [Boolean], + value: true + }, + mute: filter(true), + nesting: ["id"], + solo: filter(true), + value: "id" +}; + + +},{"../../core/methods/filter.coffee":83}],286:[function(require,module,exports){ +var decoration, family, transform; + +decoration = require("../../core/methods/font/decoration.coffee"); + +family = require("../../core/methods/font/family.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +module.exports = { + accepted: [Boolean], + align: { + accepted: ["start", "middle", "end", "left", "center", "right"], + process: function(value) { + var css; + css = ["left", "center", "right"].indexOf(value); + if (css >= 0) { + value = this.accepted[css]; + } + return value; + }, + value: "middle" + }, + color: { + accepted: [false, String], + value: false + }, + font: { + decoration: decoration(), + family: family(), + size: 11, + transform: transform(), + weight: 200 + }, + padding: 7, + resize: { + accepted: [Boolean], + value: true + }, + text: { + accepted: [false, Function, String], + value: false + }, + segments: 2, + valign: { + accepted: [false, "top", "middle", "bottom"], + value: "middle" + }, + value: true +}; + + +},{"../../core/methods/font/decoration.coffee":85,"../../core/methods/font/family.coffee":86,"../../core/methods/font/transform.coffee":88}],287:[function(require,module,exports){ +var family; + +family = require("../../core/methods/font/family.coffee"); + +module.exports = { + accepted: [Boolean], + align: "middle", + data: { + accepted: [Boolean], + value: true + }, + filters: { + accepted: [Boolean], + value: false + }, + font: { + align: "middle", + color: "#444444", + family: family(), + size: [8, 14], + weight: 200 + }, + gradient: { + height: 10 + }, + icons: { + accepted: [Boolean], + value: true + }, + labels: { + accepted: [Boolean], + value: true + }, + order: { + accepted: ["color", "id", "size", "text", Function], + sort: { + accepted: ["asc", "desc"], + value: "asc" + }, + value: "color" + }, + size: [8, 30], + tooltip: { + accepted: [Boolean], + value: true + }, + text: { + accepted: [false, Function, String], + value: false + }, + title: { + accepted: [false, Function, String], + value: false + }, + value: true +}; + + +},{"../../core/methods/font/family.coffee":86}],288:[function(require,module,exports){ +var decoration, family, transform; + +decoration = require("../../core/methods/font/decoration.coffee"); + +family = require("../../core/methods/font/family.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +module.exports = { + font: { + color: "#444444", + decoration: decoration(), + family: family(), + transform: transform(), + weight: 200 + }, + hover: { + color: "#444444", + decoration: decoration(), + family: family(), + transform: transform(), + weight: 200 + } +}; + + +},{"../../core/methods/font/decoration.coffee":85,"../../core/methods/font/family.coffee":86,"../../core/methods/font/transform.coffee":88}],289:[function(require,module,exports){ +arguments[4][125][0].apply(exports,arguments) +},{"../../core/methods/process/margin.coffee":92,"dup":125}],290:[function(require,module,exports){ +var decoration, family, transform; + +decoration = require("../../core/methods/font/decoration.coffee"); + +family = require("../../core/methods/font/family.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +module.exports = { + accepted: [Boolean, String], + background: { + accepted: [false, String], + value: false + }, + branding: { + accepted: [Boolean], + image: { + dark: "http://d3plus.org/assets/img/icon-transparent-invert.png", + light: "http://d3plus.org/assets/img/icon-transparent.png" + }, + value: false + }, + font: { + color: "#444", + decoration: decoration(), + family: family(), + size: 16, + transform: transform(), + weight: 200 + }, + padding: 5, + style: { + accepted: [false, "small", "large"], + value: false + }, + value: true +}; + + +},{"../../core/methods/font/decoration.coffee":85,"../../core/methods/font/family.coffee":86,"../../core/methods/font/transform.coffee":88}],291:[function(require,module,exports){ +module.exports = { + accepted: [Boolean], + click: { + accepted: [Boolean, Function], + value: true + }, + move: { + accepted: [Boolean, Function], + value: true + }, + out: { + accepted: [Boolean, Function], + value: true + }, + over: { + accepted: [Boolean, Function], + value: true + }, + value: true +}; + + +},{}],292:[function(require,module,exports){ +var process; + +process = require("../../core/methods/process/data.coffee"); + +module.exports = { + accepted: [false, Array, Function, String], + delimiter: { + accepted: [String], + value: "|" + }, + filetype: { + accepted: [false, "json", "xml", "html", "csv", "dsv", "tsv", "txt"], + value: false + }, + overlap: 0.6, + process: process, + value: false +}; + + +},{"../../core/methods/process/data.coffee":89}],293:[function(require,module,exports){ +module.exports = { + accepted: [Boolean, Function, String], + agg: { + accepted: [false, Function, "sum", "min", "max", "mean", "median"], + value: false + }, + deprecates: ["sort"], + sort: { + accepted: ["asc", "desc"], + value: "desc" + }, + value: false +}; + + +},{}],294:[function(require,module,exports){ +module.exports = { + accepted: [Boolean], + value: false, + timeout: 400, + process: function(value, vars) { + var resize, resizeEnd; + if (!value) { + return false; + } + resize = null; + resizeEnd = function() { + var height, mainNode, width; + mainNode = vars.container.value.node().parentNode.getBoundingClientRect(); + width = mainNode.width; + height = mainNode.height; + vars.self.width(width); + vars.self.height(height); + if (vars.width.changed || vars.height.changed) { + return vars.self.draw(); + } + }; + d3.select(window).on("resize." + vars.container.id, (function(_this) { + return function(e) { + clearTimeout(resize); + return resize = setTimeout(resizeEnd, _this.timeout); + }; + })(this)); + return value; + } +}; + + +},{}],295:[function(require,module,exports){ +var rendering; + +rendering = require("../../core/methods/rendering.coffee"); + +module.exports = { + accepted: function(vars) { + var list; + list = vars.types[vars.type.value].shapes; + if (list && !(list instanceof Array)) { + list = [list]; + } + if (list.length) { + return list; + } else { + return ["square"]; + } + }, + interpolate: { + accepted: ["basis", "basis-open", "cardinal", "cardinal-open", "linear", "monotone", "step", "step-before", "step-after"], + deprecates: "stack_type", + value: "linear" + }, + rendering: rendering(), + value: false +}; + + +},{"../../core/methods/rendering.coffee":94}],296:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [false, Function, Number, Object, String], + dataFilter: true, + deprecates: ["value", "value_var"], + mute: filter(true), + scale: { + accepted: [Function], + deprecates: "size_scale", + domain: { + min: { + accepted: [false, Number], + value: false + }, + max: { + accepted: [false, Number], + value: false + } + }, + range: { + max: { + accepted: [Function, Number], + value: function(vars) { + return Math.floor(d3.max([d3.min([vars.width.viz, vars.height.viz]) / 15, 6])); + } + }, + min: { + accepted: [Function, Number], + value: 3 + } + }, + value: d3.scale.sqrt() + }, + solo: filter(true), + threshold: { + accepted: [Boolean, Function, Number], + value: false + }, + value: false +}; + + +},{"../../core/methods/filter.coffee":83}],297:[function(require,module,exports){ +module.exports = { + value: false +}; + + +},{}],298:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [false, Function, Object, String], + deprecates: ["else_var", "else"], + mute: filter(true), + solo: filter(true), + value: false +}; + + +},{"../../core/methods/filter.coffee":83}],299:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [Array, Boolean, Function, Object, String], + deprecates: ["name_array", "text_var"], + nesting: true, + mute: filter(true), + solo: filter(true), + value: false +}; + + +},{"../../core/methods/filter.coffee":83}],300:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [Array, Boolean, Function, Object, String], + dataFilter: true, + deprecates: ["year", "year_var"], + fixed: { + accepted: [Boolean], + deprecates: ["static_axis", "static_axes"], + value: true + }, + format: { + accepted: [false, Array, Function, String], + value: false + }, + mute: filter(false), + solo: filter(false), + value: false +}; + + +},{"../../core/methods/filter.coffee":83}],301:[function(require,module,exports){ +module.exports = { + accepted: [Boolean], + align: "middle", + hover: { + accepted: ["all-scroll", "col-resize", "crosshair", "default", "grab", "grabbing", "move", "pointer"], + value: "pointer" + }, + handles: { + accepted: [Boolean], + color: "#666", + opacity: 1, + size: 3, + stroke: "#666", + value: true + }, + height: { + accepted: [false, Number], + value: false + }, + play: { + accepted: [Boolean], + icon: { + accepted: [false, String], + awesome: "", + fallback: "►" + }, + pause: { + accepted: [false, String], + awesome: "", + fallback: "❚❚" + }, + timing: { + accepted: [Number], + value: 1500 + }, + value: true + }, + value: true +}; + + +},{}],302:[function(require,module,exports){ +module.exports = { + mouseevents: 60, + transitions: 600, + ui: 200 +}; + + +},{}],303:[function(require,module,exports){ +var decoration, family, stringStrip, transform; + +decoration = require("../../core/methods/font/decoration.coffee"); + +family = require("../../core/methods/font/family.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +stringStrip = require("../../string/strip.js"); + +module.exports = { + accepted: [false, Function, String], + font: { + align: "center", + color: "#444444", + decoration: decoration(), + family: family(), + size: 16, + transform: transform(), + weight: 400 + }, + height: false, + link: false, + padding: 2, + position: "top", + process: function(value, vars) { + var id; + if (vars.container.id.indexOf("default") === 0 && value) { + id = stringStrip(value).toLowerCase(); + vars.self.container({ + id: id + }); + } + return value; + }, + sub: { + accepted: [false, Function, String], + deprecates: "sub_title", + font: { + align: "center", + color: "#444444", + decoration: decoration(), + family: family(), + size: 12, + transform: transform(), + weight: 200 + }, + link: false, + padding: 1, + position: "top", + value: false + }, + total: { + accepted: [Boolean, Object], + deprecates: "total_bar", + font: { + align: "center", + color: "#444444", + decoration: decoration(), + family: family(), + size: 12, + transform: transform(), + weight: 200, + value: false + }, + link: false, + padding: 1, + position: "top", + value: false + }, + width: false, + value: false +}; + + +},{"../../core/methods/font/decoration.coffee":85,"../../core/methods/font/family.coffee":86,"../../core/methods/font/transform.coffee":88,"../../string/strip.js":178}],304:[function(require,module,exports){ +var family, transform; + +family = require("../../core/methods/font/family.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +module.exports = { + accepted: [Boolean, Array, Function, Object, String], + anchor: "top center", + background: "#ffffff", + children: { + accepted: [Boolean, Number], + value: true + }, + connections: { + accepted: [Boolean], + value: true + }, + curtain: { + color: "#ffffff", + opacity: 0.8 + }, + deprecates: "tooltip_info", + extent: { + accepted: [Boolean], + value: true + }, + font: { + color: "#444", + family: family(), + size: 12, + transform: transform(), + weight: 200 + }, + fullscreen: { + accepted: [Boolean], + value: false + }, + html: { + accepted: [false, Function, Object, String], + deprecates: "click_function", + value: false + }, + iqr: { + accepted: [Boolean], + value: true + }, + large: 250, + share: { + accepted: [Boolean], + value: true + }, + size: { + accepted: [Boolean], + value: true + }, + small: 225, + stacked: { + accepted: [Boolean], + value: false + }, + sub: { + accepted: [false, Function, String], + value: false + }, + value: true +}; + + +},{"../../core/methods/font/family.coffee":86,"../../core/methods/font/transform.coffee":88}],305:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [false, Function, Object, String], + deprecates: ["total_var"], + mute: filter(true), + solo: filter(true), + value: false +}; + + +},{"../../core/methods/filter.coffee":83}],306:[function(require,module,exports){ +module.exports = { + accepted: function(vars) { + return d3.keys(vars.types); + }, + mode: { + accepted: function(vars) { + return vars.types[vars.type.value].modes || [false]; + }, + value: false + }, + value: "tree_map" +}; + + +},{}],307:[function(require,module,exports){ +var align, decoration, family, transform; + +family = require("../../core/methods/font/family.coffee"); + +align = require("../../core/methods/font/align.coffee"); + +decoration = require("../../core/methods/font/decoration.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +module.exports = { + accepted: [Array, Boolean], + align: align("center"), + border: 1, + color: { + primary: { + process: function(value, vars) { + var primary; + primary = this.value; + if (!vars.ui.color.secondary.value) { + vars.ui.color.secondary.value = d3.rgb(primary).darker(0.75).toString(); + } + return value; + }, + value: "#ffffff" + }, + secondary: { + value: false + } + }, + display: { + acceped: ["block", "inline-block"], + value: "inline-block" + }, + font: { + align: "center", + color: "#444", + decoration: decoration(), + family: family(), + size: 11, + transform: transform(), + weight: 200 + }, + margin: 5, + padding: 5, + position: { + accepted: ["top", "right", "bottom", "left"], + value: "bottom" + }, + value: false +}; + + +},{"../../core/methods/font/align.coffee":84,"../../core/methods/font/decoration.coffee":85,"../../core/methods/font/family.coffee":86,"../../core/methods/font/transform.coffee":88}],308:[function(require,module,exports){ +module.exports = { + accepted: [false, Number], + secondary: false, + small: 200, + value: false +}; + + +},{}],309:[function(require,module,exports){ +module.exports = { + "accepted" : [ Boolean ], + "behavior" : d3.behavior.zoom().scaleExtent([ 1 , 1 ]).duration(0), + "click" : { + "accepted" : [ Boolean ], + "value" : true + }, + "pan" : { + "accepted" : [ Boolean ], + "value" : true + }, + "scroll" : { + "accepted" : [ Boolean ], + "deprecates" : "scroll_zoom", + "value" : true + }, + "value" : true +} + +},{}],310:[function(require,module,exports){ +var area, closest, fetchValue, graph, nest, sort, stack, threshold; + +closest = require("../../util/closest.coffee"); + +fetchValue = require("../../core/fetch/value.coffee"); + +graph = require("./helpers/graph/draw.coffee"); + +nest = require("./helpers/graph/nest.coffee"); + +sort = require("../../array/sort.coffee"); + +stack = require("./helpers/graph/stack.coffee"); + +threshold = require("../../core/data/threshold.js"); + +area = function(vars) { + var d, data, discrete, domains, i, j, len, len1, opposite, point, ref; + graph(vars, { + buffer: vars.axes.opposite, + zero: true + }); + domains = vars.x.domain.viz.concat(vars.y.domain.viz); + if (domains.indexOf(void 0) >= 0) { + return []; + } + data = sort(vars.data.viz, null, null, null, vars); + discrete = vars[vars.axes.discrete]; + opposite = vars[vars.axes.opposite]; + for (i = 0, len = data.length; i < len; i++) { + point = data[i]; + if (!point.d3plus) { + point.d3plus = {}; + } + ref = point.values; + for (j = 0, len1 = ref.length; j < len1; j++) { + d = ref[j]; + if (!d.d3plus) { + d.d3plus = {}; + } + d.d3plus.x = discrete.scale.viz(fetchValue(vars, d, discrete.value)); + d.d3plus.x += vars.axes.margin.viz.left; + d.d3plus.y = opposite.scale.viz(fetchValue(vars, d, opposite.value)); + d.d3plus.y += vars.axes.margin.viz.top; + if (d.d3plus.merged instanceof Array) { + if (!point.d3plus.merged) { + point.d3plus.merged = []; + } + point.d3plus.merged = point.d3plus.merged.concat(d.d3plus.merged); + } + if (d.d3plus.text && !point.d3plus.text) { + point.d3plus.text = d.d3plus.text; + } + } + } + return stack(vars, data); +}; + +area.filter = function(vars, data) { + return nest(vars, threshold(vars, data, vars[vars.axes.discrete].value)); +}; + +area.requirements = ["data", "x", "y"]; + +area.setup = function(vars) { + var axis, size, y; + if (!vars.axes.discrete) { + axis = vars.time.value === vars.y.value ? "y" : "x"; + vars.self[axis]({ + scale: "discrete" + }); + } + if (!vars[vars.axes.discrete].zerofill.value) { + vars.self[vars.axes.discrete]({ + zerofill: true + }); + } + if (!vars[vars.axes.opposite].stacked.value && vars.type.value === "stacked") { + vars.self[vars.axes.opposite]({ + stacked: true + }); + } + y = vars[vars.axes.opposite]; + size = vars.size; + if ((!y.value && size.value) || (size.changed && size.previous === y.value)) { + return vars.self[vars.axes.opposite](size.value); + } else if ((!size.value && y.value) || (y.changed && y.previous === size.value)) { + return vars.self.size(y.value); + } +}; + +area.shapes = ["area"]; + +area.threshold = function(vars) { + return 20 / vars.height.viz; +}; + +area.tooltip = "static"; + +module.exports = area; + + +},{"../../array/sort.coffee":36,"../../core/data/threshold.js":63,"../../core/fetch/value.coffee":69,"../../util/closest.coffee":209,"./helpers/graph/draw.coffee":317,"./helpers/graph/nest.coffee":323,"./helpers/graph/stack.coffee":324}],311:[function(require,module,exports){ +var bar, buckets, fetchValue, graph, nest, stack, uniques, + indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; + +buckets = require("../../util/buckets.coffee"); + +fetchValue = require("../../core/fetch/value.coffee"); + +graph = require("./helpers/graph/draw.coffee"); + +nest = require("./helpers/graph/nest.coffee"); + +stack = require("./helpers/graph/stack.coffee"); + +uniques = require("../../util/uniques.coffee"); + +bar = function(vars) { + var bars, base, cMargin, d, data, discrete, discreteVal, divisions, domains, h, i, ids, j, k, l, len, len1, len2, length, maxBars, maxSize, mod, nested, newSize, oMargin, offset, oppDomain, oppMethod, oppVal, opposite, p, padding, point, ref, ref1, space, value, w, x, zero; + discrete = vars.axes.discrete; + h = discrete === "x" ? "height" : "width"; + w = discrete === "x" ? "width" : "height"; + opposite = vars.axes.opposite; + cMargin = discrete === "x" ? "left" : "top"; + oMargin = discrete === "x" ? "top" : "left"; + graph(vars, { + buffer: true, + zero: opposite + }); + domains = vars.x.domain.viz.concat(vars.y.domain.viz); + if (domains.indexOf(void 0) >= 0) { + return []; + } + nested = vars.data.viz; + if (vars.axes.stacked) { + for (j = 0, len = nested.length; j < len; j++) { + point = nested[j]; + stack(vars, point.values); + } + } + space = vars.axes[w] / vars[vars.axes.discrete].ticks.values.length; + padding = vars[vars.axes.discrete].padding.value; + if (padding < 1) { + padding *= space; + } + if (padding * 2 > space) { + padding = space * 0.1; + } + maxSize = space - padding * 2; + if (!vars.axes.stacked) { + if (vars[discrete].persist.position.value) { + if (ref = vars[discrete].value, indexOf.call(vars.id.nesting, ref) >= 0) { + divisions = d3.max(nested, function(b) { + return b.values.length; + }); + } else { + divisions = uniques(nested, vars.id.value, fetchValue, vars).length; + } + maxSize /= divisions; + offset = space / 2 - maxSize / 2 - padding; + x = d3.scale.ordinal(); + if (divisions === 1) { + x.domain([0]).range([0]); + } else { + x.domain([0, divisions - 1]).range([-offset, offset]); + } + } else { + x = d3.scale.linear(); + } + } + data = []; + oppMethod = vars[opposite]; + oppDomain = oppMethod.scale.viz.domain().slice(); + if (opposite.indexOf("y") === 0) { + oppDomain = oppDomain.reverse(); + } + if (oppDomain[0] <= 0 && oppDomain[1] >= 0) { + zero = 0; + } else if (oppDomain[0] < 0) { + zero(d3.max(oppDomain)); + } else { + zero = d3.min(oppDomain); + } + if (vars[discrete].persist.position.value && !vars.axes.stacked) { + ids = uniques(d3.merge(nested.map(function(d) { + return d.values; + })), vars.id.value, fetchValue, vars, vars.id.value, false); + x.domain(ids); + if (ids.length === 1) { + x.range([0]); + } else { + x.range(buckets(x.range(), ids.length)); + } + } + maxBars = d3.max(nested, function(b) { + return b.values.length; + }); + for (k = 0, len1 = nested.length; k < len1; k++) { + p = nested[k]; + if (vars.axes.stacked) { + bars = 1; + newSize = maxSize; + } else if (vars[discrete].persist.position.value) { + bars = divisions; + newSize = maxSize; + } else { + bars = p.values.length; + if (vars[discrete].persist.size.value) { + newSize = maxSize / maxBars; + offset = space / 2 - ((maxBars - bars) * (newSize / 2)) - newSize / 2 - padding; + } else { + newSize = maxSize / bars; + offset = space / 2 - newSize / 2 - padding; + } + x.domain([0, bars - 1]); + x.range([-offset, offset]); + } + ref1 = p.values; + for (i = l = 0, len2 = ref1.length; l < len2; i = ++l) { + d = ref1[i]; + if (vars.axes.stacked) { + mod = 0; + } else if (vars[discrete].persist.position.value) { + mod = x(fetchValue(vars, d, vars.id.value)); + } else { + mod = x(i % bars); + } + if (vars.axes.stacked) { + value = d.d3plus[opposite]; + base = d.d3plus[opposite + "0"]; + } else { + oppVal = fetchValue(vars, d, oppMethod.value); + if (oppVal === null) { + oppMethod = vars[opposite + "2"]; + oppVal = fetchValue(vars, d, oppMethod.value); + } + if (oppVal === 0) { + continue; + } + if (oppMethod.scale.value === "log") { + zero = oppVal < 0 ? -1 : 1; + } + value = oppMethod.scale.viz(oppVal); + base = oppMethod.scale.viz(zero); + } + discreteVal = fetchValue(vars, d, vars[discrete].value); + d.d3plus[discrete] = vars[discrete].scale.viz(discreteVal); + d.d3plus[discrete] += vars.axes.margin.viz[cMargin] + mod; + length = base - value; + d.d3plus[opposite] = base - length / 2; + if (!vars.axes.stacked) { + d.d3plus[opposite] += vars.axes.margin.viz[oMargin]; + } + delete d.d3plus.r; + d.d3plus[w] = newSize; + d.d3plus[h] = Math.abs(length); + d.d3plus.init = {}; + d.d3plus.init[opposite] = oppMethod.scale.viz(zero); + d.d3plus.init[opposite] -= d.d3plus[opposite]; + d.d3plus.init[opposite] += vars.axes.margin.viz[oMargin]; + d.d3plus.init[w] = d.d3plus[w]; + if (vars.text.value) { + delete d.d3plus.label; + } else { + d.d3plus.label = false; + } + data.push(d); + } + } + return data; +}; + +bar.filter = function(vars, data) { + return nest(vars, data, vars[vars.axes.discrete].value); +}; + +bar.requirements = ["data", "x", "y"]; + +bar.setup = function(vars) { + var axis, size, y; + if (!vars.axes.discrete) { + axis = vars.time.value === vars.y.value ? "y" : "x"; + vars.self[axis]({ + scale: "discrete" + }); + } + y = vars[vars.axes.opposite]; + size = vars.size; + if ((!y.value && size.value) || (size.changed && size.previous === y.value)) { + return vars.self[vars.axes.opposite](size.value); + } else if ((!size.value && y.value) || (y.changed && y.previous === size.value)) { + return vars.self.size(y.value); + } +}; + +bar.shapes = ["square"]; + +module.exports = bar; + + +},{"../../core/fetch/value.coffee":69,"../../util/buckets.coffee":207,"../../util/uniques.coffee":213,"./helpers/graph/draw.coffee":317,"./helpers/graph/nest.coffee":323,"./helpers/graph/stack.coffee":324}],312:[function(require,module,exports){ +var box, fetchValue, graph, stringFormat, strip, uniques; + +fetchValue = require("../../core/fetch/value.coffee"); + +graph = require("./helpers/graph/draw.coffee"); + +stringFormat = require("../../string/format.js"); + +strip = require("../../string/strip.js"); + +uniques = require("../../util/uniques.coffee"); + +box = function(vars) { + var botstr, disMargin, discrete, domains, h, iqrstr, maxstr, medians, medstr, mergeData, minstr, mode, noData, oppMargin, opposite, pctstr, qt1str, qt3str, returnData, size, space, topstr, w; + graph(vars, { + buffer: true + }); + domains = vars.x.domain.viz.concat(vars.y.domain.viz); + if (domains.indexOf(void 0) >= 0) { + return []; + } + discrete = vars.axes.discrete; + opposite = vars.axes.opposite; + disMargin = discrete === "x" ? vars.axes.margin.viz.left : vars.axes.margin.viz.top; + oppMargin = opposite === "x" ? vars.axes.margin.viz.left : vars.axes.margin.viz.top; + h = discrete === "x" ? "height" : "width"; + w = discrete === "x" ? "width" : "height"; + space = vars.axes[w] / vars[discrete].ticks.values.length; + size = vars.size.value; + size = typeof size === "number" ? size : 100; + space = d3.min([space - vars.labels.padding * 2, size]); + mode = vars.type.mode.value; + if (!(mode instanceof Array)) { + mode = [mode, mode]; + } + mergeData = function(arr) { + var key, obj, vals; + obj = {}; + for (key in vars.data.keys) { + vals = uniques(arr, key, fetchValue, vars); + obj[key] = vals.length === 1 ? vals[0] : vals; + } + return obj; + }; + noData = false; + medians = []; + iqrstr = vars.format.value(vars.format.locale.value.ui.iqr); + maxstr = vars.format.value(vars.format.locale.value.ui.max); + minstr = vars.format.value(vars.format.locale.value.ui.min); + pctstr = vars.format.value(vars.format.locale.value.ui.percentile); + botstr = vars.format.value(vars.format.locale.value.ui.tukey_bottom); + topstr = vars.format.value(vars.format.locale.value.ui.tukey_top); + qt1str = vars.format.value(vars.format.locale.value.ui.quartile_first); + qt3str = vars.format.value(vars.format.locale.value.ui.quartile_third); + medstr = vars.format.value(vars.format.locale.value.ui.median); + returnData = []; + d3.nest().key(function(d) { + return fetchValue(vars, d, vars[discrete].value); + }).rollup(function(leaves) { + var bottom, bottomLabel, bottomWhisker, boxData, d, diff1, diff2, first, i, iqr, j, key, label, len, len1, median, medianBuffer, medianData, medianHeight, medianText, outliers, scale, second, tooltipData, top, topLabel, topWhisker, uniqs, val, values, x, y; + scale = vars[opposite].scale.viz; + values = leaves.map(function(d) { + return fetchValue(vars, d, vars[opposite].value); + }); + values.sort(function(a, b) { + return a - b; + }); + uniqs = uniques(values); + first = d3.quantile(values, 0.25); + median = d3.quantile(values, 0.50); + second = d3.quantile(values, 0.75); + tooltipData = {}; + if (mode[1] === "tukey") { + iqr = first - second; + top = second - iqr * 1.5; + topLabel = topstr; + } else if (mode[1] === "extent") { + top = d3.max(values); + topLabel = maxstr; + } else if (typeof mode[1] === "number") { + top = d3.quantile(values, (100 - mode[1]) / 100); + topLabel = stringFormat(pctstr, mode[1]); + } + top = d3.min([d3.max(values), top]); + if (vars.tooltip.extent.value) { + tooltipData[topLabel] = { + key: vars[opposite].value, + value: top + }; + } + if (vars.tooltip.iqr.value) { + tooltipData[qt3str] = { + key: vars[opposite].value, + value: second + }; + tooltipData[medstr] = { + key: vars[opposite].value, + value: median + }; + tooltipData[qt1str] = { + key: vars[opposite].value, + value: first + }; + } + if (mode[0] === "tukey") { + iqr = first - second; + bottom = first + iqr * 1.5; + bottomLabel = botstr; + } else if (mode[0] === "extent") { + bottom = d3.min(values); + bottomLabel = minstr; + } else if (typeof mode[0] === "number") { + bottom = d3.quantile(values, mode[0] / 100); + topLabel = stringFormat(pctstr, mode[0]); + } + bottom = d3.max([d3.min(values), bottom]); + if (vars.tooltip.extent.value) { + tooltipData[bottomLabel] = { + key: vars[opposite].value, + value: bottom + }; + } + boxData = []; + bottomWhisker = []; + topWhisker = []; + outliers = []; + for (i = 0, len = leaves.length; i < len; i++) { + d = leaves[i]; + val = fetchValue(vars, d, vars[opposite].value); + if (val >= first && val <= second) { + boxData.push(d); + } else if (val >= bottom && val < first) { + bottomWhisker.push(d); + } else if (val <= top && val > second) { + topWhisker.push(d); + } else { + outliers.push(d); + } + } + key = fetchValue(vars, leaves[0], vars[discrete].value); + x = vars[discrete].scale.viz(key); + x += disMargin; + label = vars.format.value(key, { + key: vars[discrete].value, + vars: vars + }); + if (key.constructor === Date) { + key = key.getTime(); + } + key = strip(key); + boxData = mergeData(boxData); + boxData.d3plus = { + color: "white", + id: "box_" + key, + init: {}, + label: false, + shape: "square", + stroke: "#444", + text: stringFormat(iqrstr, label) + }; + boxData.d3plus[w] = space; + boxData.d3plus.init[w] = space; + boxData.d3plus[h] = Math.abs(scale(first) - scale(second)); + boxData.d3plus[discrete] = x; + y = d3.min([scale(first), scale(second)]) + boxData.d3plus[h] / 2; + y += oppMargin; + boxData.d3plus[opposite] = y; + boxData.d3plus.tooltip = tooltipData; + returnData.push(boxData); + medianData = { + d3plus: { + id: "median_line_" + key, + position: h === "height" ? "top" : "right", + shape: "whisker", + "static": true + } + }; + medianText = vars.format.value(median, { + key: vars[opposite].value, + vars: vars + }); + label = { + background: "#fff", + names: [medianText], + padding: 0, + resize: false, + x: 0, + y: 0 + }; + diff1 = Math.abs(scale(median) - scale(first)); + diff2 = Math.abs(scale(median) - scale(second)); + medianHeight = d3.min([diff1, diff2]) * 2; + medianBuffer = vars.data.stroke.width * 2 + vars.labels.padding * 2; + label[w === "width" ? "w" : "h"] = space - medianBuffer; + label[h === "width" ? "w" : "h"] = medianHeight - medianBuffer; + medianData.d3plus.label = label; + medianData.d3plus[w] = space; + medianData.d3plus[discrete] = x; + medianData.d3plus[opposite] = scale(median) + oppMargin; + returnData.push(medianData); + bottomWhisker = mergeData(bottomWhisker); + bottomWhisker.d3plus = { + id: "bottom_whisker_line_" + key, + offset: boxData.d3plus[h] / 2, + position: h === "height" ? "bottom" : "left", + shape: "whisker", + "static": true + }; + if (opposite === "x") { + bottomWhisker.d3plus.offset *= -1; + } + bottomWhisker.d3plus[h] = Math.abs(scale(bottom) - scale(first)); + bottomWhisker.d3plus[w] = space; + bottomWhisker.d3plus[discrete] = x; + bottomWhisker.d3plus[opposite] = y; + returnData.push(bottomWhisker); + topWhisker = mergeData(topWhisker); + topWhisker.d3plus = { + id: "top_whisker_line_" + key, + offset: boxData.d3plus[h] / 2, + position: h === "height" ? "top" : "right", + shape: "whisker", + "static": true + }; + if (opposite === "y") { + topWhisker.d3plus.offset *= -1; + } + topWhisker.d3plus[h] = Math.abs(scale(top) - scale(second)); + topWhisker.d3plus[w] = space; + topWhisker.d3plus[discrete] = x; + topWhisker.d3plus[opposite] = y; + returnData.push(topWhisker); + for (j = 0, len1 = outliers.length; j < len1; j++) { + d = outliers[j]; + d.d3plus[discrete] = x; + d.d3plus[opposite] = scale(fetchValue(vars, d, vars.y.value)); + d.d3plus[opposite] += oppMargin; + d.d3plus.r = 4; + d.d3plus.shape = vars.shape.value; + } + noData = !outliers.length && top - bottom === 0; + medians.push(median); + returnData = returnData.concat(outliers); + return leaves; + }).entries(vars.data.viz); + if (noData && uniques(medians).length === 1) { + return []; + } else { + return returnData; + } +}; + +box.modes = ["tukey", "extent", Array, Number]; + +box.requirements = ["data", "x", "y"]; + +box.shapes = ["circle", "check", "cross", "diamond", "square", "triangle", "triangle_up", "triangle_down"]; + +box.setup = function(vars) { + var axis; + if (!vars.axes.discrete) { + axis = vars.time.value === vars.y.value ? "y" : "x"; + return vars.self[axis]({ + scale: "discrete" + }); + } +}; + +module.exports = box; + + +},{"../../core/fetch/value.coffee":69,"../../string/format.js":176,"../../string/strip.js":178,"../../util/uniques.coffee":213,"./helpers/graph/draw.coffee":317}],313:[function(require,module,exports){ +var arraySort, bubbles, fetchColor, fetchText, fetchValue, groupData, legible; + +arraySort = require("../../array/sort.coffee"); + +fetchValue = require("../../core/fetch/value.coffee"); + +fetchColor = require("../../core/fetch/color.coffee"); + +fetchText = require("../../core/fetch/text.js"); + +legible = require("../../color/legible.coffee"); + +groupData = require("../../core/data/group.coffee"); + +bubbles = function(vars) { + var column_height, column_width, columns, d, data, dataLength, domain, domainMax, domainMin, downscale, groupedData, i, j, k, l, labelHeight, len, len1, len2, obj, pack, padding, row, rows, screenRatio, size, size_max, size_min, t, temp, userDomainMax, userDomainMin, xPadding, xoffset, yMod, yPadding, yoffset; + groupedData = groupData(vars, vars.data.viz); + groupedData = arraySort(groupedData, null, null, null, vars); + dataLength = groupedData.length; + if (dataLength < 4) { + columns = dataLength; + rows = 1; + } else { + screenRatio = vars.width.viz / vars.height.viz; + columns = Math.ceil(Math.sqrt(dataLength * screenRatio)); + rows = Math.ceil(Math.sqrt(dataLength / screenRatio)); + } + if (dataLength > 0) { + while ((rows - 1) * columns >= dataLength) { + rows--; + } + } + column_width = vars.width.viz / columns; + column_height = vars.height.viz / rows; + if (vars.size.value) { + userDomainMin = vars.size.scale.domain.min.value; + userDomainMax = vars.size.scale.domain.max.value; + if (typeof userDomainMin === 'number') { + domainMin = userDomainMin; + } else { + domainMin = d3.min(vars.data.viz, function(d) { + return fetchValue(vars, d, vars.size.value, vars.id.value, "min"); + }); + } + if (typeof userDomainMax === 'number') { + domainMax = userDomainMax; + } else { + domainMax = d3.max(vars.data.viz, function(d) { + return fetchValue(vars, d, vars.size.value, vars.id.value); + }); + } + domain = [domainMin, domainMax]; + } else { + domain = [0, 0]; + } + padding = 5; + size_max = (d3.min([column_width, column_height]) / 2) - (padding * 2); + labelHeight = vars.labels.value && !vars.small && size_max >= 40 ? d3.max([20, d3.min([size_max * 0.25, 50])]) : 0; + size_max -= labelHeight; + size_min = d3.min([size_max, vars.size.scale.range.min.value]); + size = vars.size.scale.value.domain(domain).rangeRound([size_min, size_max]); + pack = d3.layout.pack().children(function(d) { + return d.values; + }).padding(padding).radius(function(d) { + return size(d); + }).size([column_width - padding * 2, column_height - padding * 2 - labelHeight]).value(function(d) { + return d.value; + }); + data = []; + row = 0; + for (i = j = 0, len = groupedData.length; j < len; i = ++j) { + d = groupedData[i]; + temp = pack.nodes(d); + xoffset = (column_width * i) % vars.width.viz; + yoffset = column_height * row; + for (k = 0, len1 = temp.length; k < len1; k++) { + t = temp[k]; + if (t.children) { + obj = { + d3plus: {} + }; + obj[vars.id.value] = t.key; + } else { + obj = t.d3plus; + } + obj.d3plus.depth = vars.id.grouping.value ? t.depth : vars.depth.value; + obj.d3plus.x = t.x; + obj.d3plus.xOffset = xoffset; + obj.d3plus.y = t.y; + obj.d3plus.yOffset = yoffset + labelHeight; + obj.d3plus.r = t.r; + data.push(obj); + } + if ((i + 1) % columns === 0) { + row++; + } + } + downscale = size_max / d3.max(data, function(d) { + return d.d3plus.r; + }); + xPadding = pack.size()[0] / 2; + yPadding = pack.size()[1] / 2; + for (l = 0, len2 = data.length; l < len2; l++) { + d = data[l]; + d.d3plus.x = ((d.d3plus.x - xPadding) * downscale) + xPadding + d.d3plus.xOffset; + d.d3plus.y = ((d.d3plus.y - yPadding) * downscale) + yPadding + d.d3plus.yOffset; + d.d3plus.r = d.d3plus.r * downscale; + delete d.d3plus.xOffset; + delete d.d3plus.yOffset; + d.d3plus["static"] = d.d3plus.depth < vars.depth.value && vars.id.grouping.value; + if (labelHeight && (d.d3plus.depth === 0 || vars.id.grouping.value === false)) { + d.d3plus.text = fetchText(vars, d[vars.id.value], d.d3plus.depth); + yMod = labelHeight > vars.labels.padding * 3 ? vars.labels.padding : 0; + d.d3plus.label = { + x: 0, + y: -(size_max + yMod + labelHeight / 2), + w: size_max * 2, + h: labelHeight - yMod, + padding: 0, + resize: true, + color: legible(fetchColor(vars, d, d.d3plus.depth)), + force: true + }; + } else { + delete d.d3plus.label; + } + } + return data.sort(function(a, b) { + return a.d3plus.depth - b.d3plus.depth; + }); +}; + +bubbles.fill = true; + +bubbles.requirements = ["data"]; + +bubbles.scale = 1.05; + +bubbles.shapes = ["circle", "donut"]; + +module.exports = bubbles; + + +},{"../../array/sort.coffee":36,"../../color/legible.coffee":46,"../../core/data/group.coffee":59,"../../core/fetch/color.coffee":65,"../../core/fetch/text.js":68,"../../core/fetch/value.coffee":69}],314:[function(require,module,exports){ +var chart, print; + +print = require("../../../core/console/print.coffee"); + +chart = function(vars) { + var type, types; + types = { + circle: "scatter", + donut: "scatter", + line: "line", + square: "scatter", + area: "stacked" + }; + type = types[vars.shape.value]; + print.warning("The \"chart\" visualization type has been deprecated and will be removed in version 2.0. Please use the \"" + type + "\" visualization type."); + vars.self.type(type).draw(); +}; + +chart.shapes = ["circle", "donut", "line", "square", "area"]; + +module.exports = chart; + + +},{"../../../core/console/print.coffee":54}],315:[function(require,module,exports){ +var geo_map; + +geo_map = function(vars) { + var coords, features, key, mute, solo, topo; + coords = vars.coords.value; + key = vars.coords.key || d3.keys(coords.objects)[0]; + topo = topojson.feature(coords, coords.objects[key]); + features = topo.features; + solo = vars.coords.solo.value; + mute = vars.coords.mute.value; + features = features.filter(function(f) { + f[vars.id.value] = f.id; + if (solo.length) { + return solo.indexOf(f.id) >= 0; + } else if (mute.length) { + return mute.indexOf(f.id) < 0; + } else { + return true; + } + }); + return features; +}; + +geo_map.libs = ["topojson"]; + +geo_map.nesting = false; + +geo_map.requirements = ["coords"]; + +geo_map.scale = 1; + +geo_map.shapes = ["coordinates"]; + +geo_map.zoom = true; + +module.exports = geo_map; + + +},{}],316:[function(require,module,exports){ +var color, legible, print; + +color = require("../../../../core/fetch/color.coffee"); + +legible = require("../../../../color/legible.coffee"); + +print = require("../../../../core/console/print.coffee"); + +module.exports = function(vars) { + var axes, axis, axisData, data, i, len, margin, ref, style, tick, ticks, timing; + axes = vars.axes; + margin = vars.axes.margin.viz; + data = axes.stacked || !axes.ticks.value ? [] : vars.data.viz; + timing = data.length * 2 > vars.data.large ? 0 : vars.draw.timing; + style = function(line, axis) { + if (axis.indexOf("y") === 0) { + line.attr("x1", -2).attr("x2", -8).attr("y1", function(d) { + return d.d3plus.y - margin.top; + }).attr("y2", function(d) { + return d.d3plus.y - margin.top; + }); + } else { + line.attr("x1", function(d) { + return d.d3plus.x - margin.left; + }).attr("x2", function(d) { + return d.d3plus.x - margin.left; + }).attr("y1", axes.height + 2).attr("y2", axes.height + 8); + } + return line.style("stroke", function(d) { + return legible(color(vars, d)); + }).style("stroke-width", vars.data.stroke.width).attr("shape-rendering", vars.shape.rendering.value); + }; + if (vars.dev.value) { + print.time("creating axis tick groups"); + } + ticks = vars.group.select("g#d3plus_graph_plane").selectAll("g.d3plus_data_tick").data(data, function(d) { + var mod; + mod = axes.discrete ? "_" + d.d3plus[axes.discrete] : ""; + return "tick_" + d[vars.id.value] + "_" + d.d3plus.depth + mod; + }); + ticks.enter().append("g").attr("class", "d3plus_data_tick").attr("opacity", 0); + if (vars.dev.value) { + print.timeEnd("creating axis tick groups"); + } + ref = ["x", "y"]; + for (i = 0, len = ref.length; i < len; i++) { + axis = ref[i]; + if (vars.dev.value && timing) { + print.time("creating " + axis + " ticks"); + } + axisData = timing && axis !== axes.discrete ? data : []; + tick = ticks.selectAll("line.d3plus_data_" + axis).data(axisData, function(d) { + return "tick_" + d[vars.id.value] + "_" + d.d3plus.depth; + }); + if (vars.dev.value && timing) { + print.timeEnd("creating " + axis + " ticks"); + } + if (vars.dev.value && timing) { + print.time("styling " + axis + " ticks"); + } + if (timing > 0) { + tick.transition().duration(timing).call(style, axis); + } else { + tick.call(style, axis); + } + tick.enter().append("line").attr("class", "d3plus_data_" + axis).call(style, axis); + if (vars.dev.value && timing) { + print.timeEnd("styling " + axis + " ticks"); + } + } + if (timing > 0) { + ticks.transition().duration(timing).attr("opacity", 1); + ticks.exit().transition().duration(timing).attr("opacity", 0).remove(); + } else { + ticks.attr("opacity", 1); + ticks.exit().remove(); + } +}; + + +},{"../../../../color/legible.coffee":46,"../../../../core/console/print.coffee":54,"../../../../core/fetch/color.coffee":65}],317:[function(require,module,exports){ +var axes, draw, mouse, plot; + +axes = require("./includes/axes.coffee"); + +draw = require("./includes/svg.coffee"); + +mouse = require("./includes/mouse.coffee"); + +plot = require("./includes/plot.coffee"); + +module.exports = function(vars, opts) { + if (opts === void 0) { + opts = {}; + } + axes(vars, opts); + plot(vars, opts); + draw(vars, opts); + vars.mouse.viz = opts.mouse === true ? mouse : false; +}; + + +},{"./includes/axes.coffee":318,"./includes/mouse.coffee":320,"./includes/plot.coffee":321,"./includes/svg.coffee":322}],318:[function(require,module,exports){ +var arraySort, axisRange, buckets, buffer, dataChange, fetchData, fetchValue, getData, getScale, print, sizeScale, uniques; + +arraySort = require("../../../../../array/sort.coffee"); + +buffer = require("./buffer.coffee"); + +buckets = require("../../../../../util/buckets.coffee"); + +fetchData = require("../../../../../core/fetch/data.js"); + +fetchValue = require("../../../../../core/fetch/value.coffee"); + +print = require("../../../../../core/console/print.coffee"); + +uniques = require("../../../../../util/uniques.coffee"); + +module.exports = function(vars, opts) { + var axes, axis, changed, domains, i, j, len, len1, oppAxis, range, reorder, zero; + changed = dataChange(vars); + if (changed || !vars.axes.dataset) { + vars.axes.dataset = getData(vars); + } + vars.axes.scale = opts.buffer && opts.buffer !== true ? sizeScale(vars, opts.buffer) : false; + axes = vars.width.viz > vars.height.viz ? ["y", "y2", "x", "x2"] : ["x", "x2", "y", "y2"]; + for (i = 0, len = axes.length; i < len; i++) { + axis = axes[i]; + oppAxis = axis.indexOf("x") === 0 ? "y" : "x"; + reorder = vars.order.changed || vars.order.sort.changed || (vars.order.value === true && vars[oppAxis].changed); + if (vars[axis].value && (!vars[axis].ticks.values || changed || reorder || (vars[axis].value === vars.time.value && vars.time.fixed.value))) { + if (vars.dev.value) { + print.time("calculating " + axis + " axis"); + } + vars[axis].reset = true; + vars[axis].ticks.values = false; + if (axis === vars.axes.discrete && vars[axis].value !== vars.time.value) { + vars[axis].ticks.values = uniques(vars.axes.dataset, vars[axis].value, fetchValue, vars); + } + zero = opts.zero === true || axis.indexOf(opts.zero) === 0 ? true : false; + range = axisRange(vars, axis, zero); + if (axis.indexOf("y") === 0) { + range = range.reverse(); + } + vars[axis].scale.viz = getScale(vars, axis, range); + vars[axis].domain.viz = range; + if (vars.dev.value) { + print.timeEnd("calculating " + axis + " axis"); + } + } + } + if (vars.axes.mirror.value) { + domains = d3.extent(vars.y.domain.viz.concat(vars.x.domain.viz)); + vars.x.domain.viz = domains; + vars.x.scale.viz.domain(domains); + domains = domains.slice().reverse(); + vars.y.domain.viz = domains; + vars.y.scale.viz.domain(domains); + } + if (opts.buffer) { + for (j = 0, len1 = axes.length; j < len1; j++) { + axis = axes[j]; + if (axis !== vars.axes.discrete) { + buffer(vars, axis, opts.buffer); + } + } + } +}; + +dataChange = function(vars) { + var axis, changed, check, i, j, k, l, len, len1, len2, ref, sub, subs; + changed = !vars.time.fixed.value && (vars.time.solo.changed || vars.time.mute.changed); + if (!changed) { + changed = vars.id.solo.changed || vars.id.mute.changed; + } + if (changed) { + return changed; + } + check = ["data", "time", "id", "depth", "type", "width", "height", "x", "y", "x2", "y2"]; + for (i = 0, len = check.length; i < len; i++) { + k = check[i]; + if (vars[k].changed) { + changed = true; + break; + } + } + if (changed) { + return changed; + } + subs = ["mute", "range", "scale", "solo", "stacked", "zerofill"]; + ref = ["x", "y", "x2", "y2"]; + for (j = 0, len1 = ref.length; j < len1; j++) { + axis = ref[j]; + for (l = 0, len2 = subs.length; l < len2; l++) { + sub = subs[l]; + if (vars[axis][sub].changed) { + changed = true; + break; + } + } + } + return changed; +}; + +getData = function(vars) { + var d, depths; + if (!vars.time.fixed.value) { + return vars.data.viz; + } else { + depths = d3.range(0, vars.id.nesting.length); + return d3.merge(d3.merge([ + (function() { + var i, len, results; + results = []; + for (i = 0, len = depths.length; i < len; i++) { + d = depths[i]; + results.push(fetchData(vars, "all", d)); + } + return results; + })() + ])); + } +}; + +axisRange = function(vars, axis, zero, buffer) { + var agg, aggType, allNegative, allPositive, axisSums, counts, d, group, i, j, k, l, len, len1, len2, len3, m, min, oppAxis, ref, ref1, ref2, ref3, sort, sortKey, splitData, v, val, values; + oppAxis = axis.indexOf("x") === 0 ? "y" : "x"; + if (vars[axis].range.value && vars[axis].range.value.length === 2) { + return vars[axis].range.value.slice(); + } else if (vars[axis].scale.value === "share") { + vars[axis].ticks.values = d3.range(0, 1.1, 0.1); + return [0, 1]; + } else if (vars[axis].stacked.value) { + splitData = []; + ref = vars.axes.dataset; + for (i = 0, len = ref.length; i < len; i++) { + d = ref[i]; + if (d.values) { + splitData = splitData.concat(d.values); + } else { + splitData.push(d); + } + } + axisSums = d3.nest().key(function(d) { + return fetchValue(vars, d, vars[oppAxis].value); + }).rollup(function(leaves) { + var negatives, positives; + positives = d3.sum(leaves, function(d) { + var val; + val = fetchValue(vars, d, vars[axis].value); + if (val > 0) { + return val; + } else { + return 0; + } + }); + negatives = d3.sum(leaves, function(d) { + var val; + val = fetchValue(vars, d, vars[axis].value); + if (val < 0) { + return val; + } else { + return 0; + } + }); + return [negatives, positives]; + }).entries(splitData); + values = d3.merge(axisSums.map(function(d) { + return d.values; + })); + return d3.extent(values); + } else if (vars[axis].value === vars.time.value) { + if (vars.time.solo.value.length) { + return d3.extent(vars.time.solo.value).map(function(v) { + if (v.constructor !== Date) { + v = v + ""; + if (v.length === 4 && parseInt(v) + "" === v) { + v += "/01/01"; + } + return new Date(v); + } else { + return v; + } + }); + } else { + return d3.extent(vars.data.time.ticks); + } + } else { + values = []; + ref1 = vars.axes.dataset; + for (j = 0, len1 = ref1.length; j < len1; j++) { + d = ref1[j]; + val = fetchValue(vars, d, vars[axis].value); + if (val instanceof Array) { + values = values.concat(val); + } else { + values.push(val); + } + } + values = values.filter(function(d) { + return d !== null; + }); + if (axis === vars.axes.discrete) { + if (vars.order.value === true) { + sortKey = vars[oppAxis].value; + } else { + sortKey = vars.order.value; + } + if (sortKey) { + sort = vars.order.sort.value; + agg = vars.order.agg.value || vars.aggs.value[sortKey] || "max"; + aggType = typeof agg; + counts = values.reduce(function(obj, val) { + obj[val] = []; + return obj; + }, {}); + ref2 = vars.axes.dataset; + for (l = 0, len2 = ref2.length; l < len2; l++) { + d = ref2[l]; + if (d.values) { + ref3 = d.values; + for (m = 0, len3 = ref3.length; m < len3; m++) { + v = ref3[m]; + group = fetchValue(vars, v, vars[axis].value); + counts[group].push(fetchValue(vars, v, sortKey)); + } + } else { + group = fetchValue(vars, d, vars[axis].value); + counts[group].push(fetchValue(vars, d, sortKey)); + } + } + for (k in counts) { + v = counts[k]; + if (aggType === "string") { + counts[k] = d3[agg](v); + } else if (aggType === "function") { + counts[k] = agg(v, sortKey); + } + } + counts = arraySort(d3.entries(counts), "value", sort); + counts = counts.reduce(function(arr, v) { + arr.push(v.key); + return arr; + }, []); + return counts; + } else if (values[0].constructor === String) { + return uniques(values).sort(function(a, b) { + return "" + a.localeCompare("" + b); + }); + } else { + return uniques(values).sort(function(a, b) { + return a - b; + }); + } + } else { + values.sort(function(a, b) { + return a - b; + }); + if (vars[axis].scale.value === "log") { + if (values[0] === 0) { + values[0] = 1; + } + if (values[values.length - 1] === 0) { + values[values.length - 1] = -1; + } + } + if (zero) { + allPositive = values.every(function(v) { + return v > 0; + }); + allNegative = values.every(function(v) { + return v < 0; + }); + if (allPositive || allNegative) { + min = allPositive ? 1 : -1; + values.push(vars[axis].scale.value === "log" ? min : 0); + } + } + return d3.extent(values); + } + } +}; + +getScale = function(vars, axis, range) { + var rangeArray, rangeMax, retScale, scaleType, t; + rangeMax = axis.indexOf("x") === 0 ? vars.width.viz : vars.height.viz; + scaleType = vars[axis].scale.value; + if (["discrete", "share"].indexOf(scaleType) >= 0) { + scaleType = "linear"; + } + t = 10; + if (typeof range[0] === "string") { + scaleType = "ordinal"; + rangeArray = buckets([0, rangeMax], range.length); + } else { + rangeArray = [0, rangeMax]; + if (vars[axis].scale.value === "linear") { + t = Math.floor(rangeMax / (vars[axis].ticks.font.size * 4)); + } + } + vars[axis].scale.ticks = t; + retScale = d3.scale[scaleType]().domain(range).range(rangeArray); + if ("clamp" in retScale) { + retScale.clamp(true); + } + return retScale; +}; + +sizeScale = function(vars, value) { + var domain, max, min; + if (value === true) { + value = "size"; + } + if (value in vars) { + value = vars[value].value; + } + min = vars.size.scale.range.min.value; + if (typeof min === "function") { + min = min(vars); + } + max = vars.size.scale.range.max.value; + if (typeof max === "function") { + max = max(vars); + } + if (value === false) { + return vars.size.scale.value.domain([0, 1]).rangeRound([max, max]); + } else if (typeof value === "number") { + return vars.size.scale.value.domain([0, 1]).rangeRound([value, value]); + } else if (value) { + if (vars.dev.value) { + print.time("calculating buffer scale"); + } + domain = d3.extent(vars.axes.dataset, function(d) { + var val; + val = fetchValue(vars, d, value); + if (!val) { + return 0; + } else { + return val; + } + }); + if (domain[0] === domain[1]) { + min = max; + } + if (vars.dev.value) { + print.timeEnd("calculating buffer scale"); + } + return vars.size.scale.value.domain(domain).rangeRound([min, max]); + } +}; + + +},{"../../../../../array/sort.coffee":36,"../../../../../core/console/print.coffee":54,"../../../../../core/fetch/data.js":66,"../../../../../core/fetch/value.coffee":69,"../../../../../util/buckets.coffee":207,"../../../../../util/uniques.coffee":213,"./buffer.coffee":319}],319:[function(require,module,exports){ +var buckets, closest; + +buckets = require("../../../../../util/buckets.coffee"); + +closest = require("../../../../../util/closest.coffee"); + +module.exports = function(vars, axis, buffer) { + var add, additional, allNegative, allPositive, closestTime, copy, d, diff, difference, domain, domainCompare, domainHigh, domainLow, i, lowerDiff, lowerMod, lowerScale, lowerValue, maxSize, opp, orig_domain, range, rangeMax, second, strings, testScale, timeIndex, upperDiff, upperMod, upperScale, upperValue, zero; + if (vars[axis].scale.value !== "share" && !vars[axis].range.value && vars[axis].reset) { + testScale = vars[axis].scale.viz.copy(); + if ("clamp" in testScale) { + testScale.clamp(false); + } + if (axis === vars.axes.discrete) { + domain = testScale.domain(); + if (typeof domain[0] === "string") { + i = domain.length; + while (i >= 0) { + domain.splice(i, 0, "d3plus_buffer_" + i); + i--; + } + range = testScale.range(); + range = buckets(d3.extent(range), domain.length); + return vars[axis].scale.viz.domain(domain).range(range); + } else { + if (axis.indexOf("y") === 0) { + domain = domain.slice().reverse(); + } + if (vars[axis].ticks.values.length === 1) { + domain = [domain[0], domain[0]]; + if (vars[axis].value === vars.time.value && vars.data.time.ticks.length !== 1) { + closestTime = closest(vars.data.time.ticks, domain[0]); + timeIndex = vars.data.time.ticks.indexOf(closestTime); + if (timeIndex > 0) { + domain[0] = vars.data.time.ticks[timeIndex - 1]; + } else { + diff = vars.data.time.ticks[timeIndex + 1] - closestTime; + domain[0] = new Date(closestTime.getTime() - diff); + } + if (timeIndex < vars.data.time.ticks.length - 1) { + domain[1] = vars.data.time.ticks[timeIndex + 1]; + } else { + diff = closestTime - vars.data.time.ticks[timeIndex - 1]; + domain[1] = new Date(closestTime.getTime() + diff); + } + } else { + domain[0] -= 1; + domain[1] += 1; + } + } else if (vars.axes.scale) { + difference = Math.abs(domain[1] - domain[0]); + additional = difference / (vars[axis].ticks.values.length - 1); + additional = additional / 2; + rangeMax = testScale.range()[1]; + maxSize = vars.axes.scale.range()[1] * 1.5; + domainLow = testScale.invert(-maxSize); + domainHigh = testScale.invert(rangeMax + maxSize); + if (domain[0] - additional < domainLow) { + domain[0] = domain[0] - additional; + domain[domain.length - 1] = domain[domain.length - 1] + additional; + } else { + domain = [domainLow, domainHigh]; + if (axis.indexOf("y") === 0) { + domain = domain.reverse(); + } + domainCompare = testScale.domain(); + domainCompare = domainCompare[1] - domainCompare[0]; + if (!domainCompare) { + domain[0] -= 1; + domain[1] += 1; + } + } + } else if (vars[axis].value === vars.time.value) { + difference = Math.abs(domain[1] - domain[0]); + additional = difference / (vars[axis].ticks.values.length - 1); + additional = additional / 2; + domain[0] = domain[0] - additional; + domain[1] = domain[1] + additional; + } else { + difference = Math.abs(domain[1] - domain[0]); + add = difference / 2; + i = domain.length; + orig_domain = domain.slice(); + while (i >= 0) { + d = i ? orig_domain[i - 1] + add : orig_domain[i] - add; + domain.splice(i, 0, d); + i--; + } + range = testScale.range(); + range = buckets(d3.extent(range), domain.length); + vars[axis].scale.viz.domain(domain).range(range); + } + if (axis.indexOf("y") === 0) { + domain = domain.reverse(); + } + return vars[axis].scale.viz.domain(domain); + } + } else if ((buffer === "x" && axis.indexOf("x") === 0) || (buffer === "y" && axis.indexOf("y") === 0) || (buffer === true)) { + domain = testScale.domain(); + allPositive = domain[0] >= 0 && domain[1] >= 0; + allNegative = domain[0] <= 0 && domain[1] <= 0; + if (vars[axis].scale.value === "log") { + zero = allPositive ? 1 : -1; + if (allPositive && axis.indexOf("y") === 0) { + domain = domain.slice().reverse(); + } + lowerScale = Math.pow(10, parseInt(Math.abs(domain[0])).toString().length - 1) * zero; + lowerMod = domain[0] % lowerScale; + lowerDiff = lowerMod; + if (lowerMod && lowerDiff / lowerScale <= 0.1) { + lowerDiff += lowerScale * zero; + } + lowerValue = lowerMod === 0 ? lowerScale : lowerDiff; + domain[0] -= lowerValue; + if (domain[0] === 0) { + domain[0] = zero; + } + upperScale = Math.pow(10, parseInt(Math.abs(domain[1])).toString().length - 1) * zero; + upperMod = domain[1] % upperScale; + upperDiff = Math.abs(upperScale - upperMod); + if (upperMod && upperDiff / upperScale <= 0.1) { + upperDiff += upperScale * zero; + } + upperValue = upperMod === 0 ? upperScale : upperDiff; + domain[1] += upperValue; + if (domain[1] === 0) { + domain[1] = zero; + } + if (allPositive && axis.indexOf("y") === 0) { + domain = domain.reverse(); + } + } else { + zero = 0; + if (axis.indexOf("y") === 0) { + domain = domain.slice().reverse(); + } + strings = domain.filter(function(d) { + return d.constructor === String; + }); + additional = Math.abs(domain[1] - domain[0]) * 0.05 || 1; + if (!strings.length) { + domain[0] = domain[0] - additional; + domain[1] = domain[1] + additional; + if ((allPositive && domain[0] < zero) || (allNegative && domain[0] > zero)) { + domain[0] = zero; + } + if ((allPositive && domain[1] < zero) || (allNegative && domain[1] > zero)) { + domain[1] = zero; + } + } + if (axis.indexOf("y") === 0) { + domain = domain.reverse(); + } + } + return vars[axis].scale.viz.domain(domain); + } else if (vars.axes.scale) { + copy = false; + if (vars.axes.mirror.value) { + opp = axis.indexOf("y") === 0 ? "x" : "y"; + copy = vars[opp].scale.viz; + second = vars.width.viz > vars.height.viz ? "x" : "y"; + } + if (axis === second && copy) { + domain = copy.domain().slice().reverse(); + } else { + rangeMax = testScale.range()[1]; + maxSize = vars.axes.scale.range()[1]; + domainLow = testScale.invert(-maxSize * 1.5); + domainHigh = testScale.invert(rangeMax + maxSize * 1.5); + domain = [domainLow, domainHigh]; + if (axis.indexOf("y") === 0) { + domain = domain.reverse(); + } + domainCompare = testScale.domain(); + domainCompare = domainCompare[1] - domainCompare[0]; + if (!domainCompare) { + domain[0] -= 1; + domain[1] += 1; + } + if (axis.indexOf("y") === 0) { + domain = domain.reverse(); + } + } + return vars[axis].scale.viz.domain(domain); + } + } +}; + + +},{"../../../../../util/buckets.coffee":207,"../../../../../util/closest.coffee":209}],320:[function(require,module,exports){ +var copy, events, fetchColor, fetchValue, legible, textColor; + +copy = require("../../../../../util/copy.coffee"); + +events = require("../../../../../client/pointer.coffee"); + +fetchColor = require("../../../../../core/fetch/color.coffee"); + +fetchValue = require("../../../../../core/fetch/value.coffee"); + +legible = require("../../../../../color/legible.coffee"); + +textColor = require("../../../../../color/text.coffee"); + +module.exports = function(node, vars) { + var clickRemove, color, create, graph, lineData, lineInit, lineStyle, lineUpdate, lines, margin, r, rectStyle, rects, s, textStyle, texts, timing, x, y; + clickRemove = d3.event.type === events.click && (vars.tooltip.value.long || vars.tooltip.html.value); + create = [events.over, events.move].indexOf(d3.event.type) >= 0; + x = node.d3plus.x; + y = node.d3plus.y; + r = node.d3plus.r || 0; + s = vars.types[vars.type.value].scale || 1; + r = r * s; + graph = vars.axes; + margin = vars.axes.margin.viz; + timing = vars.draw.timing ? vars.timing.mouseevents : 0; + if (!clickRemove && create) { + color = legible(fetchColor(vars, node)); + lineData = ["x", "y", "x2", "y2"].filter(function(axis) { + var val; + val = fetchValue(vars, node, vars[axis].value); + return val && !(val instanceof Array) && axis !== vars.axes.stacked && vars[axis].mouse.value; + }); + } else { + lineData = []; + } + lineInit = function(line) { + return line.attr("x1", function(d) { + if (d.indexOf("x") === 0) { + return x; + } else { + return x - r; + } + }).attr("y1", function(d) { + if (d.indexOf("y") === 0) { + return y; + } else { + return y + r; + } + }).attr("x2", function(d) { + if (d.indexOf("x") === 0) { + return x; + } else { + return x - r; + } + }).attr("y2", function(d) { + if (d.indexOf("y") === 0) { + return y; + } else { + return y + r; + } + }).attr("opacity", 0); + }; + lineStyle = function(line) { + return line.style("stroke", function(d) { + if (vars.shape.value === "area") { + return "white"; + } else { + return color; + } + }).attr("stroke-dasharray", function(d) { + return vars[d].mouse.dasharray.value; + }).attr("shape-rendering", function(d) { + return vars[d].mouse.rendering.value; + }).style("stroke-width", function(d) { + return vars[d].mouse.width; + }); + }; + lineUpdate = function(line) { + return line.attr("x1", function(d) { + if (d.indexOf("x") === 0) { + return x; + } else { + return x - r; + } + }).attr("y1", function(d) { + if (d.indexOf("y") === 0) { + return y; + } else { + return y + r; + } + }).attr("x2", function(d) { + if (d.indexOf("x") === 0) { + return x; + } else if (node.d3plus.x0) { + return node.d3plus.x0; + } else if (d === "y") { + return margin.left - vars[d].ticks.size; + } else { + return margin.left + graph.width + vars[d].ticks.size; + } + }).attr("y2", function(d) { + if (d.indexOf("y") === 0) { + return y; + } else if (node.d3plus.y0) { + return node.d3plus.y0; + } else if (d === "x") { + return graph.height + margin.top + vars[d].ticks.size; + } else { + return margin.top - vars[d].ticks.size; + } + }).style("opacity", 1); + }; + lines = vars.g.labels.selectAll("line.d3plus_mouse_axis_label").data(lineData); + if (timing) { + lines.enter().append("line").attr("class", "d3plus_mouse_axis_label").attr("pointer-events", "none").call(lineInit).call(lineStyle); + lines.transition().duration(timing).call(lineUpdate).call(lineStyle); + lines.exit().transition().duration(timing).call(lineInit).remove(); + } else { + lines.call(lineUpdate).call(lineStyle); + lines.enter().append("line").attr("class", "d3plus_mouse_axis_label").attr("pointer-events", "none").call(lineInit).call(lineStyle); + lines.exit().remove(); + } + textStyle = function(text) { + return text.attr("font-size", function(d) { + return vars[d].ticks.font.size + "px"; + }).attr("font-family", function(d) { + return vars[d].ticks.font.family.value; + }).attr("font-weight", function(d) { + return vars[d].ticks.font.weight; + }).attr("x", function(d) { + if (d.indexOf("x") === 0) { + return x; + } else if (d === "y") { + return margin.left - 5 - vars[d].ticks.size; + } else { + return margin.left + graph.width + 5 + vars[d].ticks.size; + } + }).attr("y", function(d) { + if (d.indexOf("y") === 0) { + return y; + } else if (node.d3plus.y0) { + return node.d3plus.y + (node.d3plus.y0 - node.d3plus.y) / 2 + margin.top - 6; + } else if (d === "x") { + return graph.height + margin.top + 5 + vars[d].ticks.size; + } else { + return margin.top - 5 - vars[d].ticks.size - (vars[d].ticks.font.size * 1.35); + } + }).attr("fill", vars.shape.value === "area" ? "white" : textColor(color)); + }; + texts = vars.g.labels.selectAll("text.d3plus_mouse_axis_label").data(lineData); + texts.enter().append("text").attr("class", "d3plus_mouse_axis_label").attr("id", function(d) { + return d + "_d3plusmouseaxislabel"; + }).attr("dy", function(d) { + if (d.indexOf("y") === 0) { + return vars[d].ticks.font.size * 0.35; + } else { + return vars[d].ticks.font.size; + } + }).style("text-anchor", function(d) { + if (d === "y") { + return "end"; + } else if (d === "y2") { + return "start"; + } else { + return "middle"; + } + }).attr("opacity", 0).attr("pointer-events", "none").call(textStyle); + texts.text(function(d) { + var axis, val; + axis = vars.axes.stacked || d; + val = fetchValue(vars, node, vars[axis].value); + return vars.format.value(val, { + key: vars[axis].value, + vars: vars, + labels: vars[axis].affixes.value + }); + }); + if (timing) { + texts.transition().duration(timing).delay(timing).attr("opacity", 1).call(textStyle); + texts.exit().transition().duration(timing).attr("opacity", 0).remove(); + } else { + texts.attr("opacity", 1).call(textStyle); + texts.exit().remove(); + } + rectStyle = function(rect) { + var getText; + getText = function(axis) { + var l; + l = d3.select("text#" + axis + "_d3plusmouseaxislabel"); + if (l.size()) { + return l.node().getBBox(); + } else { + return { + "width": 0, + "height": 0 + }; + } + }; + return rect.attr("x", function(d) { + var width; + width = getText(d).width; + if (d.indexOf("x") === 0) { + return x - width / 2 - 5; + } else if (d === "y") { + return margin.left - vars[d].ticks.size - width - 10; + } else { + return margin.left + graph.width + vars[d].ticks.size; + } + }).attr("y", function(d) { + var height; + height = getText(d).height; + if (d.indexOf("y") === 0) { + return y - (height / 2 + 5); + } else if (node.d3plus.y0) { + return node.d3plus.y + (node.d3plus.y0 - node.d3plus.y) / 2 + margin.top - (height / 2 + 5); + } else if (d === "x") { + return graph.height + margin.top + vars[d].ticks.size; + } else { + return margin.top - vars[d].ticks.size - height - 10; + } + }).attr("width", function(d) { + return getText(d).width + 10; + }).attr("height", function(d) { + return getText(d).height + 10; + }).style("stroke", vars.shape.value === "area" ? "transparent" : color).attr("fill", color).attr("shape-rendering", function(d) { + return vars[d].mouse.rendering.value; + }).style("stroke-width", function(d) { + return vars[d].mouse.width; + }); + }; + rects = vars.g.labels.selectAll("rect.d3plus_mouse_axis_label").data(lineData); + if (timing) { + rects.enter().insert("rect", "text.d3plus_mouse_axis_label").attr("class", "d3plus_mouse_axis_label").attr("pointer-events", "none").attr("opacity", 0).call(rectStyle); + rects.transition().duration(timing).delay(timing).attr("opacity", 1).call(rectStyle); + return rects.exit().transition().duration(timing).attr("opacity", 0).remove(); + } else { + rects.attr("opacity", 1).call(rectStyle); + rects.enter().insert("rect", "text.d3plus_mouse_axis_label").attr("class", "d3plus_mouse_axis_label").attr("pointer-events", "none").call(rectStyle); + return rects.exit().remove(); + } +}; + + +},{"../../../../../client/pointer.coffee":40,"../../../../../color/legible.coffee":46,"../../../../../color/text.coffee":52,"../../../../../core/fetch/color.coffee":65,"../../../../../core/fetch/value.coffee":69,"../../../../../util/copy.coffee":210}],321:[function(require,module,exports){ +var buckets, buffer, createAxis, fetchValue, fontSizes, formatPower, labelPadding, superscript, textwrap, timeDetect, uniques; + +buckets = require("../../../../../util/buckets.coffee"); + +buffer = require("./buffer.coffee"); + +fetchValue = require("../../../../../core/fetch/value.coffee"); + +fontSizes = require("../../../../../font/sizes.coffee"); + +textwrap = require("../../../../../textwrap/textwrap.coffee"); + +timeDetect = require("../../../../../core/data/time.coffee"); + +uniques = require("../../../../../util/uniques.coffee"); + +module.exports = function(vars, opts) { + var axes, axis, axisStyle, extent, j, k, l, len, len1, len2, newtick, opp, otherScale, scale, step, tens, tick, ticks, timeReturn, values; + vars.axes.margin.viz = { + top: vars.axes.margin.top, + right: vars.axes.margin.right, + bottom: vars.axes.margin.bottom, + left: vars.axes.margin.left + }; + vars.axes.height = vars.height.viz; + vars.axes.width = vars.width.viz; + axes = vars.width.viz > vars.height.viz ? ["y", "y2", "x", "x2"] : ["x", "x2", "y", "y2"]; + for (j = 0, len = axes.length; j < len; j++) { + axis = axes[j]; + if (vars[axis].value) { + if (vars[axis].ticks.values === false) { + if (vars[axis].value === vars.time.value) { + ticks = vars.time.solo.value; + if (ticks.length) { + ticks = ticks.map(function(d) { + if (d.constructor !== Date) { + d = d + ""; + if (d.length === 4 && parseInt(d) + "" === d) { + d += "/01/01"; + } + d = new Date(d); + } + return d; + }); + } else { + ticks = vars.data.time.values; + } + extent = d3.extent(ticks); + step = vars.data.time.stepType; + ticks = [extent[0]]; + tick = extent[0]; + while (tick < extent[1]) { + newtick = new Date(tick); + tick = new Date(newtick["set" + step](newtick["get" + step]() + 1)); + ticks.push(tick); + } + vars[axis].ticks.values = ticks; + } else { + if (axis.indexOf("2") === 1) { + otherScale = vars[axis.slice(0, 1)].scale.viz; + scale = vars[axis].scale.viz; + ticks = vars[axis.slice(0, 1)].scale.ticks; + vars[axis].ticks.values = otherScale.ticks(ticks).map(function(t) { + return parseFloat(d3.format(".5f")(scale.invert(otherScale(t)))); + }); + } else { + vars[axis].ticks.values = vars[axis].scale.viz.ticks(vars[axis].scale.ticks); + } + } + } + if (!vars[axis].ticks.values.length) { + values = fetchValue(vars, vars.data.viz, vars[axis].value); + if (!(values instanceof Array)) { + values = [values]; + } + vars[axis].ticks.values = values; + } + opp = axis.indexOf("x") === 0 ? "y" : "x"; + if (vars[axis].ticks.values.length === 1 || (opts.buffer && opts.buffer !== opp && axis === vars.axes.discrete && vars[axis].reset === true)) { + buffer(vars, axis, opts.buffer); + } + vars[axis].reset = false; + if (vars[axis].value === vars.time.value) { + axisStyle = { + "font-family": vars[axis].ticks.font.family.value, + "font-weight": vars[axis].ticks.font.weight, + "font-size": vars[axis].ticks.font.size + "px", + "text-transform": vars[axis].ticks.font.transform.value, + "letter-spacing": vars[axis].ticks.font.spacing + "px" + }; + timeReturn = timeDetect(vars, { + values: vars[axis].ticks.values, + limit: vars.width.viz, + style: axisStyle + }); + if (vars[axis].ticks.value) { + vars[axis].ticks.visible = vars[axis].ticks.value.map(Number); + } else if (vars[axis].ticks.labels.value.constructor === Array) { + vars[axis].ticks.visible = vars[axis].ticks.labels.value.map(Number); + } else { + vars[axis].ticks.visible = timeReturn.values.map(Number); + } + vars[axis].ticks.format = timeReturn.format; + } else if (vars[axis].ticks.value) { + vars[axis].ticks.values = vars[axis].ticks.value; + if (vars[axis].ticks.labels.value.constructor === Array) { + vars[axis].ticks.visible = vars[axis].ticks.labels.value; + } else { + vars[axis].ticks.visible = vars[axis].ticks.value; + } + } else if (vars[axis].ticks.labels.value.constructor === Array) { + vars[axis].ticks.visible = vars[axis].ticks.labels.value; + } else if (vars[axis].scale.value === "log") { + ticks = vars[axis].ticks.values; + tens = ticks.filter(function(t) { + return Math.abs(t).toString().charAt(0) === "1"; + }); + if (tens.length < 3) { + vars[axis].ticks.visible = ticks; + } else { + vars[axis].ticks.visible = tens; + } + } else { + vars[axis].ticks.visible = vars[axis].ticks.values; + } + if (vars[axis].value === vars.time.value) { + vars[axis].ticks.visible = vars[axis].ticks.visible.map(function(d) { + if (d.constructor === Number && ("" + d).length > 4) { + return d; + } + d += ""; + if (d.length === 4 && parseInt(d) + "" === d) { + d += "/01/01"; + } + return new Date(d).getTime(); + }); + } + } + } + if (vars.small) { + vars.axes.width -= vars.axes.margin.viz.left + vars.axes.margin.viz.right; + vars.axes.height -= vars.axes.margin.viz.top + vars.axes.margin.viz.bottom; + for (k = 0, len1 = axes.length; k < len1; k++) { + axis = axes[k]; + vars[axis].label.height = 0; + } + } else { + if (!vars.small) { + labelPadding(vars); + } + } + for (l = 0, len2 = axes.length; l < len2; l++) { + axis = axes[l]; + vars[axis].axis.svg = createAxis(vars, axis); + } +}; + +labelPadding = function(vars) { + var axis, j, k, lastTick, len, len1, margin, ref, ref1, rightLabel, rightMod, x2Domain, xAttrs, xAxisHeight, xAxisWidth, xDomain, xLabel, xLabelAttrs, xMaxWidth, xSizes, xText, xValues, y2Domain, yAttrs, yAxisWidth, yDomain, yLabel, yLabelAttrs, yText, yValues; + xDomain = vars.x.scale.viz.domain(); + yDomain = vars.y.scale.viz.domain(); + if (vars.x2.value) { + x2Domain = vars.x2.scale.viz.domain(); + } + if (vars.y2.value) { + y2Domain = vars.y2.scale.viz.domain(); + } + ref = ["y", "y2"]; + for (j = 0, len = ref.length; j < len; j++) { + axis = ref[j]; + if (vars[axis].value) { + margin = axis === "y" ? "left" : "right"; + yAttrs = { + "font-size": vars[axis].ticks.font.size + "px", + "font-family": vars[axis].ticks.font.family.value, + "font-weight": vars[axis].ticks.font.weight, + "text-transform": vars[axis].ticks.font.transform.value, + "letter-spacing": vars[axis].ticks.font.spacing + "px" + }; + yValues = vars[axis].ticks.visible; + if (vars[axis].scale.value === "log") { + yText = yValues.map(function(d) { + return formatPower(d); + }); + } else if (vars[axis].scale.value === "share") { + yText = yValues.map(function(d) { + return vars.format.value(d * 100, { + key: "share", + vars: vars, + output: axis + }); + }); + } else if (vars[axis].value === vars.time.value) { + yText = yValues.map(function(d, i) { + return vars[axis].ticks.format(new Date(d)); + }); + } else { + if (typeof yValues[0] === "string") { + yValues = vars[axis].scale.viz.domain().filter(function(d) { + return d.indexOf("d3plus_buffer_") !== 0; + }); + } + yText = yValues.map(function(d) { + return vars.format.value(d, { + key: vars[axis].value, + vars: vars, + labels: vars[axis].affixes.value, + output: axis + }); + }); + } + if (vars[axis].ticks.labels.value) { + vars[axis].ticks.hidden = false; + yAxisWidth = d3.max(fontSizes(yText, yAttrs), function(d) { + return d.width; + }); + if (yAxisWidth) { + yAxisWidth = Math.ceil(yAxisWidth + vars.labels.padding); + vars.axes.margin.viz[margin] += yAxisWidth; + } + } else { + vars[axis].ticks.hidden = true; + } + yLabel = vars[axis].label.fetch(vars); + if (yLabel) { + yLabelAttrs = { + "font-family": vars[axis].label.font.family.value, + "font-weight": vars[axis].label.font.weight, + "font-size": vars[axis].label.font.size + "px", + "text-transform": vars[axis].label.font.transform.value, + "letter-spacing": vars[axis].label.font.spacing + "px" + }; + vars[axis].label.height = fontSizes([yLabel], yLabelAttrs)[0].height; + } else { + vars[axis].label.height = 0; + } + if (vars[axis].label.value) { + vars.axes.margin.viz[margin] += vars[axis].label.height; + vars.axes.margin.viz[margin] += vars[axis].label.padding * 2; + } + } + } + vars.axes.width -= vars.axes.margin.viz.left + vars.axes.margin.viz.right; + vars.x.scale.viz.range(buckets([0, vars.axes.width], xDomain.length)); + if (x2Domain) { + vars.x2.scale.viz.range(buckets([0, vars.axes.width], x2Domain.length)); + } + ref1 = ["x", "x2"]; + for (k = 0, len1 = ref1.length; k < len1; k++) { + axis = ref1[k]; + if (vars[axis].value) { + margin = axis === "x" ? "bottom" : "top"; + if (vars[axis].ticks.labels.value) { + vars[axis].ticks.hidden = false; + xAttrs = { + "font-size": vars[axis].ticks.font.size + "px", + "font-family": vars[axis].ticks.font.family.value, + "font-weight": vars[axis].ticks.font.weight, + "text-transform": vars[axis].ticks.font.transform.value, + "letter-spacing": vars[axis].ticks.font.spacing + "px" + }; + xValues = vars[axis].ticks.visible; + if (vars[axis].scale.value === "log") { + xText = xValues.map(function(d) { + return formatPower(d); + }); + } else if (vars[axis].scale.value === "share") { + xText = xValues.map(function(d) { + return vars.format.value(d * 100, { + key: "share", + vars: vars, + output: axis + }); + }); + } else if (vars[axis].value === vars.time.value) { + xText = xValues.map(function(d, i) { + return vars[axis].ticks.format(new Date(d)); + }); + } else { + if (typeof xValues[0] === "string") { + xValues = vars[axis].scale.viz.domain().filter(function(d) { + return d.indexOf("d3plus_buffer_") !== 0; + }); + } + xText = xValues.map(function(d) { + return vars.format.value(d, { + key: vars[axis].value, + vars: vars, + labels: vars[axis].affixes.value, + output: axis + }); + }); + } + xSizes = fontSizes(xText, xAttrs); + xAxisWidth = d3.max(xSizes, function(d) { + return d.width; + }); + xAxisHeight = d3.max(xSizes, function(d) { + return d.height; + }); + if (xValues.length === 1) { + xMaxWidth = vars.axes.width; + } else { + xMaxWidth = vars[axis].scale.viz(xValues[1]) - vars[axis].scale.viz(xValues[0]); + xMaxWidth = Math.abs(xMaxWidth); + } + if (xAxisWidth > xMaxWidth && xText.join("").indexOf(" ") > 0) { + vars[axis].ticks.wrap = true; + xSizes = fontSizes(xText, xAttrs, { + mod: function(elem) { + return textwrap().container(d3.select(elem)).height(vars.axes.height / 2).width(xMaxWidth).draw(); + } + }); + xAxisWidth = d3.max(xSizes, function(d) { + return d.width; + }); + xAxisHeight = d3.max(xSizes, function(d) { + return d.height; + }); + } else { + vars[axis].ticks.wrap = false; + } + vars[axis].ticks.baseline = "auto"; + if (xAxisWidth <= xMaxWidth) { + vars[axis].ticks.rotate = 0; + } else if (xAxisWidth < vars.axes.height / 2) { + xSizes = fontSizes(xText, xAttrs, { + mod: function(elem) { + return textwrap().container(d3.select(elem)).width(vars.axes.height / 2).height(xMaxWidth).draw(); + } + }); + xAxisHeight = d3.max(xSizes, function(d) { + return d.width; + }); + xAxisWidth = d3.max(xSizes, function(d) { + return d.height; + }); + vars[axis].ticks.rotate = -90; + } else { + xAxisWidth = 0; + xAxisHeight = 0; + } + if (!(xAxisWidth && xAxisHeight)) { + vars[axis].ticks.hidden = true; + vars[axis].ticks.rotate = 0; + } + xAxisWidth = Math.ceil(xAxisWidth); + xAxisHeight = Math.ceil(xAxisHeight); + vars[axis].ticks.maxHeight = xAxisHeight; + vars[axis].ticks.maxWidth = xAxisWidth; + if (xAxisHeight) { + vars.axes.margin.viz[margin] += xAxisHeight + vars.labels.padding; + } + lastTick = vars[axis].ticks.visible[vars[axis].ticks.visible.length - 1]; + rightLabel = vars[axis].scale.viz(lastTick); + rightLabel += xAxisWidth / 2 + vars.axes.margin.viz.left; + if (rightLabel > vars.width.value) { + rightMod = rightLabel - vars.width.value + vars.axes.margin.viz.right; + vars.axes.width -= rightMod; + vars.axes.margin.viz.right += rightMod; + } + } else { + vars[axis].ticks.hidden = true; + } + xLabel = vars[axis].label.fetch(vars); + if (xLabel) { + xLabelAttrs = { + "font-family": vars[axis].label.font.family.value, + "font-weight": vars[axis].label.font.weight, + "font-size": vars[axis].label.font.size + "px", + "text-transform": vars[axis].label.font.transform.value, + "letter-spacing": vars[axis].label.font.spacing + "px" + }; + vars[axis].label.height = fontSizes([xLabel], xLabelAttrs)[0].height; + } else { + vars[axis].label.height = 0; + } + if (vars[axis].label.value) { + vars.axes.margin.viz[margin] += vars[axis].label.height; + vars.axes.margin.viz[margin] += vars[axis].label.padding * 2; + } + } + } + vars.axes.height -= vars.axes.margin.viz.top + vars.axes.margin.viz.bottom; + vars.x.scale.viz.range(buckets([0, vars.axes.width], xDomain.length)); + if (x2Domain) { + vars.x2.scale.viz.range(buckets([0, vars.axes.width], x2Domain.length)); + } + vars.y.scale.viz.range(buckets([0, vars.axes.height], yDomain.length)); + if (y2Domain) { + return vars.y2.scale.viz.range(buckets([0, vars.axes.height], y2Domain.length)); + } +}; + +createAxis = function(vars, axis) { + return d3.svg.axis().tickSize(vars[axis].ticks.size).tickPadding(5).orient(vars[axis].orient.value).scale(vars[axis].scale.viz).tickValues(vars[axis].ticks.values).tickFormat(function(d, i) { + var c, scale; + if (vars[axis].ticks.hidden) { + return null; + } + scale = vars[axis].scale.value; + c = d.constructor === Date ? +d : d; + if (vars[axis].ticks.visible.indexOf(c) >= 0) { + if (scale === "share") { + return vars.format.value(d * 100, { + key: "share", + vars: vars, + labels: vars[axis].affixes.value, + output: axis + }); + } else if (d.constructor === Date) { + return vars[axis].ticks.format(d); + } else if (scale === "log") { + return formatPower(d); + } else { + return vars.format.value(d, { + key: vars[axis].value, + vars: vars, + labels: vars[axis].affixes.value, + output: axis + }); + } + } else { + return null; + } + }); +}; + +superscript = "⁰¹²³⁴⁵⁶⁷⁸⁹"; + +formatPower = function(d) { + var n, p, t; + p = Math.round(Math.log(Math.abs(d)) / Math.LN10); + t = Math.abs(d).toString().charAt(0); + n = 10 + " " + (p + "").split("").map(function(c) { + return superscript[c]; + }).join(""); + if (t !== "1") { + n = t + " x " + n; + } + if (d < 0) { + return "-" + n; + } else { + return n; + } +}; + + +},{"../../../../../core/data/time.coffee":64,"../../../../../core/fetch/value.coffee":69,"../../../../../font/sizes.coffee":104,"../../../../../textwrap/textwrap.coffee":203,"../../../../../util/buckets.coffee":207,"../../../../../util/uniques.coffee":213,"./buffer.coffee":319}],322:[function(require,module,exports){ +var mix, textwrap, validObject; + +mix = require("../../../../../color/mix.coffee"); + +textwrap = require("../../../../../textwrap/textwrap.coffee"); + +validObject = require("../../../../../object/validate.coffee"); + +module.exports = function(vars) { + var affixes, alignMap, axis, axisData, axisGroup, axisLabel, bg, bgStyle, d, domain, domains, getFontStyle, grid, gridData, groupEnter, j, k, l, label, labelData, labelStyle, len, len1, len2, len3, len4, line, lineData, lineFont, lineGroup, lineRects, lineStyle, lines, linetexts, m, mirror, n, opp, plane, planeTrans, position, realData, rectData, rectStyle, ref, ref1, ref2, ref3, rotated, sep, style, textData, textPad, textPos, tickFont, tickPosition, tickStyle, userLines, valid, xStyle, yStyle; + domains = vars.x.domain.viz.concat(vars.y.domain.viz); + if (domains.indexOf(void 0) >= 0) { + return null; + } + bgStyle = { + width: vars.axes.width, + height: vars.axes.height, + fill: vars.axes.background.color, + stroke: vars.axes.background.stroke.color, + "stroke-width": vars.axes.background.stroke.width, + "shape-rendering": vars.axes.background.rendering.value + }; + alignMap = { + left: "start", + center: "middle", + right: "end" + }; + axisData = vars.small ? [] : [0]; + tickPosition = function(tick, axis) { + return tick.attr("x1", function(d) { + if (axis.indexOf("x") === 0) { + return vars.x.scale.viz(d); + } else { + return 0; + } + }).attr("x2", function(d) { + if (axis.indexOf("x") === 0) { + return vars.x.scale.viz(d); + } else { + return vars.axes.width; + } + }).attr("y1", function(d) { + if (axis.indexOf("y") === 0) { + return vars.y.scale.viz(d); + } else { + return 0; + } + }).attr("y2", function(d) { + if (axis.indexOf("y") === 0) { + return vars.y.scale.viz(d); + } else { + return vars.axes.height; + } + }); + }; + tickStyle = function(tick, axis, grid) { + var color, log, visibles; + color = grid ? vars[axis].grid.color : vars[axis].ticks.color; + log = vars[axis].scale.value === "log"; + visibles = vars[axis].ticks.visible || []; + return tick.attr("stroke", function(d) { + var visible; + if (d === 0) { + return vars[axis].axis.color; + } + if (d.constructor === Date) { + d = +d; + } + visible = visibles.indexOf(d) >= 0; + if (visible && (!log || Math.abs(d).toString().charAt(0) === "1")) { + return color; + } else if (grid && vars.axes.background.color !== "transparent") { + return mix(color, vars.axes.background.color, 0.4, 1); + } else if (vars.background.value !== "transparent") { + return mix(color, vars.background.value, 0.4, 1); + } else { + return mix(color, "white", 0.4, 1); + } + }).attr("stroke-width", vars[axis].ticks.width).attr("shape-rendering", vars[axis].ticks.rendering.value); + }; + getFontStyle = function(axis, val, style) { + var type; + type = val === 0 ? "axis" : "ticks"; + val = vars[axis][type].font[style]; + if (val && (val.length || typeof val === "number")) { + return val; + } else { + return vars[axis].ticks.font[style]; + } + }; + tickFont = function(tick, axis) { + var log; + log = vars[axis].scale.value === "log"; + return tick.attr("font-size", function(d) { + return getFontStyle(axis, d, "size") + "px"; + }).attr("stroke", "none").attr("fill", function(d) { + var color; + color = getFontStyle(axis, d, "color"); + if (!log || Math.abs(d).toString().charAt(0) === "1") { + return color; + } else { + return mix(color, vars.background.value, 0.4, 1); + } + }).attr("font-family", function(d) { + return getFontStyle(axis, d, "family").value; + }).attr("font-weight", function(d) { + return getFontStyle(axis, d, "weight"); + }).style("text-transform", function(d) { + return getFontStyle(axis, d, "transform").value; + }).style("letter-spacing", function(d) { + return getFontStyle(axis, d, "spacing") + "px"; + }); + }; + lineStyle = function(line, axis) { + var max, opp; + max = axis.indexOf("x") === 0 ? "height" : "width"; + opp = axis.indexOf("x") === 0 ? "y" : "x"; + return line.attr(opp + "1", 0).attr(opp + "2", vars.axes[max]).attr(axis + "1", function(d) { + return d.coords.line; + }).attr(axis + "2", function(d) { + return d.coords.line; + }).attr("stroke", function(d) { + return d.color || vars[axis].lines.color; + }).attr("stroke-width", vars[axis].lines.width).attr("shape-rendering", vars[axis].lines.rendering.value).attr("stroke-dasharray", vars[axis].lines.dasharray.value); + }; + lineFont = function(text, axis) { + var opp; + opp = axis.indexOf("x") === 0 ? "y" : "x"; + return text.attr(opp, function(d) { + return d.coords.text[opp] + "px"; + }).attr(axis, function(d) { + return d.coords.text[axis] + "px"; + }).attr("dy", vars[axis].lines.font.position.value).attr("text-anchor", alignMap[vars[axis].lines.font.align.value]).attr("transform", function(d) { + return d.transform; + }).attr("font-size", vars[axis].lines.font.size + "px").attr("fill", function(d) { + return d.color || vars[axis].lines.color; + }).attr("font-family", vars[axis].lines.font.family.value).attr("font-weight", vars[axis].lines.font.weight); + }; + planeTrans = "translate(" + vars.axes.margin.viz.left + "," + vars.axes.margin.viz.top + ")"; + plane = vars.group.selectAll("g#d3plus_graph_plane").data([0]); + plane.transition().duration(vars.draw.timing).attr("transform", planeTrans); + plane.enter().append("g").attr("id", "d3plus_graph_plane").attr("transform", planeTrans); + bg = plane.selectAll("rect#d3plus_graph_background").data([0]); + bg.transition().duration(vars.draw.timing).attr(bgStyle); + bg.enter().append("rect").attr("id", "d3plus_graph_background").attr("x", 0).attr("y", 0).attr(bgStyle); + mirror = plane.selectAll("path#d3plus_graph_mirror").data([0]); + mirror.enter().append("path").attr("id", "d3plus_graph_mirror").attr("fill", "#000").attr("fill-opacity", 0.03).attr("stroke-width", 1).attr("stroke", "#ccc").attr("stroke-dasharray", "10,10").attr("opacity", 0); + mirror.transition().duration(vars.draw.timing).attr("opacity", function() { + if (vars.axes.mirror.value) { + return 1; + } else { + return 0; + } + }).attr("d", function() { + var h, w; + w = bgStyle.width; + h = bgStyle.height; + return "M " + w + " " + h + " L 0 " + h + " L " + w + " 0 Z"; + }); + rotated = vars.x.ticks.rotate !== 0; + xStyle = function(group, axis) { + var groups, offset; + offset = axis === "x" ? vars.axes.height : 0; + groups = group.attr("transform", "translate(0," + offset + ")").call(vars[axis].axis.svg.scale(vars[axis].scale.viz)).selectAll("g.tick"); + groups.selectAll("line").attr("y2", function(d) { + var y2; + if (d.constructor === Date) { + d = +d; + } + y2 = d3.select(this).attr("y2"); + if (vars[axis].ticks.visible.indexOf(d) >= 0) { + return y2; + } else { + return y2 / 2; + } + }); + return groups.select("text").style("text-anchor", rotated && axis === "x" ? "end" : rotated ? "start" : "middle").call(tickFont, axis).each(function(d) { + d3.select(this).attr("dy", "0px").attr("font-size", function(d) { + return getFontStyle(axis, d, "size") + "px"; + }); + if (d.constructor === Date) { + d = +d; + } + if (!vars[axis].ticks.hidden && vars[axis].ticks.visible.indexOf(d) >= 0) { + return textwrap().container(d3.select(this)).rotate(vars[axis].ticks.rotate).align(rotated ? "end" : "center").valign(rotated ? "middle" : axis === "x" ? "top" : "bottom").width(vars[axis].ticks.maxWidth + 2).height(vars[axis].ticks.maxHeight).padding(0).x(-vars[axis].ticks.maxWidth / 2).y(axis === "x2" ? -(vars[axis].ticks.maxHeight + vars.labels.padding * 2) : 0).draw(); + } + }); + }; + yStyle = function(group, axis) { + var groups, offset; + offset = axis === "y2" ? vars.axes.width : 0; + groups = group.attr("transform", "translate(" + offset + ", 0)").call(vars[axis].axis.svg.scale(vars[axis].scale.viz)).selectAll("g.tick"); + groups.selectAll("line").attr("y2", function(d) { + var y2; + if (d.constructor === Date) { + d = +d; + } + y2 = d3.select(this).attr("y2"); + if (vars.x.ticks.visible.indexOf(d) >= 0) { + return y2; + } else { + return y2 / 2; + } + }); + return groups.select("text").call(tickFont, axis); + }; + ref = ["x", "x2", "y", "y2"]; + for (j = 0, len = ref.length; j < len; j++) { + axis = ref[j]; + style = axis.indexOf("x") === 0 ? xStyle : yStyle; + realData = axisData.length && vars[axis].value ? [0] : []; + axisGroup = plane.selectAll("g#d3plus_graph_" + axis + "ticks").data(realData); + axisGroup.transition().duration(vars.draw.timing).call(style, axis); + axisGroup.selectAll("line").transition().duration(vars.draw.timing).call(tickStyle, axis); + groupEnter = axisGroup.enter().append("g").attr("id", "d3plus_graph_" + axis + "ticks").call(style, axis); + groupEnter.selectAll("path").attr("fill", "none").attr("stroke", "none"); + groupEnter.selectAll("line").call(tickStyle, axis); + axisGroup.exit().transition().duration(vars.data.timing).attr("opacity", 0).remove(); + } + labelStyle = function(label, axis) { + return label.attr("x", axis.indexOf("x") === 0 ? vars.width.viz / 2 : -(vars.axes.height / 2 + vars.axes.margin.viz.top)).attr("y", axis === "x" ? vars.height.viz - vars[axis].label.height / 2 - vars[axis].label.padding : axis === "y2" ? vars.width.viz - vars[axis].label.height / 2 - vars[axis].label.padding : vars[axis].label.height / 2 + vars[axis].label.padding).attr("transform", axis.indexOf("y") === 0 ? "rotate(-90)" : null).attr("font-family", vars[axis].label.font.family.value).attr("font-weight", vars[axis].label.font.weight).attr("font-size", vars[axis].label.font.size + "px").attr("fill", vars[axis].label.font.color).style("text-anchor", "middle").attr("dominant-baseline", "central").style("text-transform", vars[axis].label.font.transform.value).style("letter-spacing", vars[axis].label.font.spacing + "px"); + }; + ref1 = ["x", "y"]; + for (k = 0, len1 = ref1.length; k < len1; k++) { + axis = ref1[k]; + if (vars[axis].grid.value) { + if (vars[axis].ticks.value) { + gridData = vars[axis].ticks.value; + } else { + gridData = vars[axis].ticks.values; + } + } else { + gridData = []; + opp = axis === "x" ? "y" : "x"; + if (vars[axis].ticks.values.indexOf(0) >= 0 && vars[opp].axis.value) { + gridData = [0]; + } + } + if (vars[axis].value === vars.time.value) { + gridData = gridData.map(function(d) { + d += ""; + if (d.length === 4 && parseInt(d) + "" === d) { + d += "/01/01"; + } + return new Date(d).getTime(); + }); + } + grid = plane.selectAll("g#d3plus_graph_" + axis + "grid").data([0]); + grid.enter().append("g").attr("id", "d3plus_graph_" + axis + "grid"); + lines = grid.selectAll("line").data(gridData, function(d, i) { + if (d.constructor === Date) { + return d.getTime(); + } else { + return d; + } + }); + lines.transition().duration(vars.draw.timing).call(tickPosition, axis).call(tickStyle, axis, true); + lines.enter().append("line").style("opacity", 0).call(tickPosition, axis).call(tickStyle, axis, true).transition().duration(vars.draw.timing).delay(vars.draw.timing / 2).style("opacity", 1); + lines.exit().transition().duration(vars.draw.timing / 2).style("opacity", 0).remove(); + } + ref2 = ["x", "x2", "y", "y2"]; + for (l = 0, len2 = ref2.length; l < len2; l++) { + axis = ref2[l]; + if (vars[axis].value) { + axisLabel = vars[axis].label.fetch(vars); + labelData = axisData && axisLabel && !vars.small ? [0] : []; + affixes = vars.format.affixes.value[vars[axis].value]; + if (axisLabel && !vars[axis].affixes.value && affixes) { + sep = vars[axis].affixes.separator.value; + if (sep === true) { + sep = ["[", "]"]; + } else if (sep === false) { + sep = ["", ""]; + } + axisLabel += " " + sep[0] + affixes[0] + " " + affixes[1] + sep[1]; + } + } else { + axisLabel = ""; + labelData = []; + } + label = vars.group.selectAll("text#d3plus_graph_" + axis + "label").data(labelData); + label.text(axisLabel).transition().duration(vars.draw.timing).call(labelStyle, axis); + label.enter().append("text").attr("stroke", "none").attr("id", "d3plus_graph_" + axis + "label").text(axisLabel).call(labelStyle, axis); + label.exit().transition().duration(vars.data.timing).attr("opacity", 0).remove(); + } + ref3 = ["x", "y", "x2", "y2"]; + for (m = 0, len3 = ref3.length; m < len3; m++) { + axis = ref3[m]; + if (vars[axis].value) { + lineGroup = plane.selectAll("g#d3plus_graph_" + axis + "_userlines").data([0]); + lineGroup.enter().append("g").attr("id", "d3plus_graph_" + axis + "_userlines"); + domain = vars[axis].scale.viz.domain(); + if (axis.indexOf("y") === 0) { + domain = domain.slice().reverse(); + } + textData = []; + lineData = []; + userLines = vars[axis].lines.value || []; + for (n = 0, len4 = userLines.length; n < len4; n++) { + line = userLines[n]; + d = validObject(line) ? line.position : line; + if (axis === vars.axes.discrete) { + valid = domain.indexOf(d) >= 0; + } else { + valid = d >= domain[0] && d <= domain[1]; + } + if (valid) { + d = !validObject(line) ? { + "position": d + } : line; + d.coords = { + line: vars[axis].scale.viz(d.position) + }; + lineData.push(d); + if (d.text) { + d.axis = axis; + d.padding = vars[axis].lines.font.padding.value * 0.5; + d.align = vars[axis].lines.font.align.value; + position = vars[axis].lines.font.position.text; + textPad = position === "middle" ? 0 : d.padding * 2; + if (position === "top") { + textPad = -textPad; + } + if (axis.indexOf("x") === 0) { + textPos = d.align === "left" ? vars.axes.height : d.align === "center" ? vars.axes.height / 2 : 0; + if (d.align === "left") { + textPos -= d.padding * 2; + } + if (d.align === "right") { + textPos += d.padding * 2; + } + } else { + textPos = d.align === "left" ? 0 : d.align === "center" ? vars.axes.width / 2 : vars.axes.width; + if (d.align === "right") { + textPos -= d.padding * 2; + } + if (d.align === "left") { + textPos += d.padding * 2; + } + } + d.coords.text = {}; + d.coords.text[axis.indexOf("x") === 0 ? "y" : "x"] = textPos; + d.coords.text[axis] = vars[axis].scale.viz(d.position) + textPad; + d.transform = axis.indexOf("x") === 0 ? "rotate(-90," + d.coords.text.x + "," + d.coords.text.y + ")" : null; + textData.push(d); + } + } + } + lines = lineGroup.selectAll("line.d3plus_graph_" + axis + "line").data(lineData, function(d) { + return d.position; + }); + lines.enter().append("line").attr("class", "d3plus_graph_" + axis + "line").attr("opacity", 0).call(lineStyle, axis); + lines.transition().duration(vars.draw.timing).attr("opacity", 1).call(lineStyle, axis); + lines.exit().transition().duration(vars.draw.timing).attr("opacity", 0).remove(); + linetexts = lineGroup.selectAll("text.d3plus_graph_" + axis + "line_text").data(textData, function(d) { + return d.position; + }); + linetexts.enter().append("text").attr("class", "d3plus_graph_" + axis + "line_text").attr("id", function(d) { + var id; + id = d.position + ""; + id = id.replace("-", "neg"); + id = id.replace(".", "p"); + return "d3plus_graph_" + axis + "line_text_" + id; + }).attr("opacity", 0).call(lineFont, axis); + linetexts.text(function(d) { + return d.text; + }).transition().duration(vars.draw.timing).attr("opacity", 1).call(lineFont, axis); + linetexts.exit().transition().duration(vars.draw.timing).attr("opacity", 0).remove(); + rectStyle = function(rect) { + var getText; + getText = function(d) { + var id; + id = d.position + ""; + id = id.replace("-", "neg"); + id = id.replace(".", "p"); + return plane.select("text#d3plus_graph_" + d.axis + "line_text_" + id).node().getBBox(); + }; + return rect.attr("x", function(d) { + return getText(d).x - d.padding; + }).attr("y", function(d) { + return getText(d).y - d.padding; + }).attr("transform", function(d) { + return d.transform; + }).attr("width", function(d) { + return getText(d).width + (d.padding * 2); + }).attr("height", function(d) { + return getText(d).height + (d.padding * 2); + }).attr("fill", vars.axes.background.color !== "transparent" ? vars.axes.background.color : "white"); + }; + rectData = vars[axis].lines.font.background.value ? textData : []; + lineRects = lineGroup.selectAll("rect.d3plus_graph_" + axis + "line_rect").data(rectData, function(d) { + return d.position; + }); + lineRects.enter().insert("rect", "text.d3plus_graph_" + axis + "line_text").attr("class", "d3plus_graph_" + axis + "line_rect").attr("pointer-events", "none").attr("opacity", 0).call(rectStyle); + lineRects.transition().delay(vars.draw.timing).each("end", function(d) { + return d3.select(this).transition().duration(vars.draw.timing).attr("opacity", 1).call(rectStyle); + }); + lineRects.exit().transition().duration(vars.draw.timing).attr("opacity", 0).remove(); + } + } +}; + + +},{"../../../../../color/mix.coffee":48,"../../../../../object/validate.coffee":175,"../../../../../textwrap/textwrap.coffee":203}],323:[function(require,module,exports){ +var fetchValue, stringStrip, uniqueValues; + +fetchValue = require("../../../../core/fetch/value.coffee"); + +stringStrip = require("../../../../string/strip.js"); + +uniqueValues = require("../../../../util/uniques.coffee"); + +module.exports = function(vars, data, keys) { + var discrete, extras, key, opposite, serialized, ticks, timeAxis; + if (keys === void 0) { + keys = vars.id.nesting.slice(0, vars.depth.value + 1); + } else if (keys.constructor !== Array) { + keys = [keys]; + } + if (extras === void 0) { + extras = []; + } + if (!data) { + data = vars.data.viz; + } + discrete = vars[vars.axes.discrete]; + opposite = vars[vars.axes.opposite]; + timeAxis = discrete.value === vars.time.value; + if (timeAxis) { + ticks = vars.data.time.ticks; + key = vars.time.solo.value.length ? "solo" : "mute"; + if (vars.time[key].value.length) { + serialized = vars.time[key].value.slice().map(function(f) { + if (f.constructor !== Date) { + f = f + ""; + if (f.length === 4 && parseInt(f) + "" === f) { + f += "/01/01"; + } + f = new Date(f); + } + return +f; + }); + ticks = ticks.filter(function(f) { + if (key === "solo") { + return serialized.indexOf(+f) >= 0; + } else { + return serialized.indexOf(+f) < 0; + } + }); + } + } else if (discrete.ticks.values) { + ticks = discrete.ticks.values; + } else { + ticks = uniqueValues(data, discrete.value, fetchValue, vars); + } + return d3.nest().key(function(d) { + var id, j, len, return_id, val; + return_id = "nesting"; + for (j = 0, len = keys.length; j < len; j++) { + id = keys[j]; + val = fetchValue(vars, d, id); + if (val instanceof Array) { + val = val.join("_"); + } + return_id += "_" + stringStrip(val); + } + return return_id; + }).rollup(function(leaves) { + var availables, filler, i, j, k, len, len1, obj, ref, tester, tick, timeVar; + availables = uniqueValues(leaves, discrete.value, fetchValue, vars); + timeVar = availables.length && availables[0].constructor === Date; + if (timeVar) { + availables = availables.map(Number); + } + if (discrete.zerofill.value) { + if (discrete.scale.value === "log") { + if (opposite.scale.viz.domain().every(function(d) { + return d < 0; + })) { + filler = -1; + } else { + filler = 1; + } + } else { + filler = 0; + } + for (i = j = 0, len = ticks.length; j < len; i = ++j) { + tick = ticks[i]; + tester = timeAxis ? +tick : tick; + if (availables.indexOf(tester) < 0) { + obj = { + d3plus: {} + }; + ref = vars.id.nesting; + for (k = 0, len1 = ref.length; k < len1; k++) { + key = ref[k]; + if (key in leaves[0]) { + obj[key] = leaves[0][key]; + } + } + obj[discrete.value] = tick; + obj[opposite.value] = 0; + obj[opposite.value] = filler; + leaves.splice(i, 0, obj); + } + } + } + if (typeof leaves[0][discrete.value] === "string") { + return leaves; + } else { + return leaves.sort(function(a, b) { + var ad, ao, bd, bo, xsort; + ad = fetchValue(vars, a, discrete.value); + bd = fetchValue(vars, b, discrete.value); + xsort = ad - bd; + if (xsort) { + return xsort; + } + ao = fetchValue(vars, a, opposite.value); + bo = fetchValue(vars, b, opposite.value); + return ao - bo; + }); + } + }).entries(data); +}; + + +},{"../../../../core/fetch/value.coffee":69,"../../../../string/strip.js":178,"../../../../util/uniques.coffee":213}],324:[function(require,module,exports){ +var fetchValue; + +fetchValue = require("../../../../core/fetch/value.coffee"); + +module.exports = function(vars, data) { + var d, flip, i, j, len, len1, margin, neg, negativeData, offset, opposite, positiveData, scale, stack, stacked, v, val; + stacked = vars.axes.stacked || vars.axes.opposite; + flip = vars[stacked].scale.viz(0); + scale = vars[stacked].scale.value; + opposite = stacked === "x" ? "y" : "x"; + margin = stacked === "y" ? vars.axes.margin.viz.top : vars.axes.margin.viz.left; + offset = scale === "share" ? "expand" : "zero"; + stack = d3.layout.stack().values(function(d) { + return d.values || [d]; + }).offset(offset).x(function(d) { + return d.d3plus[opposite]; + }).y(function(d) { + return flip - vars[stacked].scale.viz(fetchValue(vars, d, vars[stacked].value)); + }).out(function(d, y0, y) { + var negative, value; + value = fetchValue(vars, d, vars[stacked].value); + negative = value < 0; + if (scale === "share") { + d.d3plus[stacked + "0"] = (1 - y0) * flip; + d.d3plus[stacked] = d.d3plus[stacked + "0"] - (y * flip); + } else { + d.d3plus[stacked + "0"] = flip; + if (vars.axes.stacked) { + d.d3plus[stacked + "0"] -= y0; + } + d.d3plus[stacked] = d.d3plus[stacked + "0"] - y; + } + d.d3plus[stacked] += margin; + return d.d3plus[stacked + "0"] += margin; + }); + positiveData = []; + negativeData = []; + for (i = 0, len = data.length; i < len; i++) { + d = data[i]; + val = fetchValue(vars, d, vars[stacked].value); + if (val instanceof Array) { + neg = true; + for (j = 0, len1 = val.length; j < len1; j++) { + v = val[j]; + if (v >= 0) { + neg = false; + break; + } + } + if (neg) { + negativeData.push(d); + } else { + positiveData.push(d); + } + } else { + if (val >= 0) { + positiveData.push(d); + } + if (val < 0) { + negativeData.push(d); + } + } + } + if (positiveData.length === 0 || negativeData.length === 0) { + return stack(data); + } else { + if (positiveData.length) { + positiveData = stack(positiveData); + } + if (negativeData.length) { + negativeData = stack(negativeData); + } + return positiveData.concat(negativeData); + } +}; + + +},{"../../../../core/fetch/value.coffee":69}],325:[function(require,module,exports){ +var fetchValue, graph, line, nest, sort, stack; + +fetchValue = require("../../core/fetch/value.coffee"); + +graph = require("./helpers/graph/draw.coffee"); + +nest = require("./helpers/graph/nest.coffee"); + +sort = require("../../array/sort.coffee"); + +stack = require("./helpers/graph/stack.coffee"); + +line = function(vars) { + var d, data, domains, i, j, len, len1, point, ref, xval, yval; + graph(vars, { + buffer: vars.axes.opposite, + mouse: true + }); + domains = vars.x.domain.viz.concat(vars.y.domain.viz); + if (domains.indexOf(void 0) >= 0) { + return []; + } + data = sort(vars.data.viz, null, null, null, vars); + for (i = 0, len = data.length; i < len; i++) { + point = data[i]; + ref = point.values; + for (j = 0, len1 = ref.length; j < len1; j++) { + d = ref[j]; + xval = fetchValue(vars, d, vars.x.value); + if (xval !== null) { + d.d3plus.x2 = false; + d.d3plus.x = vars.x.scale.viz(xval); + } else { + d.d3plus.x2 = true; + d.d3plus.x = vars.x2.scale.viz(fetchValue(vars, d, vars.x2.value)); + } + d.d3plus.x += vars.axes.margin.viz.left; + yval = fetchValue(vars, d, vars.y.value); + if (yval !== null) { + d.d3plus.y2 = false; + d.d3plus.y = vars.y.scale.viz(yval); + } else { + d.d3plus.y2 = true; + d.d3plus.y = vars.y2.scale.viz(fetchValue(vars, d, vars.y2.value)); + } + d.d3plus.y += vars.axes.margin.viz.top; + } + } + if (vars.axes.stacked) { + return stack(vars, data); + } else { + return data; + } +}; + +line.filter = function(vars, data) { + return nest(vars, data); +}; + +line.requirements = ["data", "x", "y"]; + +line.setup = function(vars) { + var axis; + if (!vars.axes.discrete) { + axis = vars.time.value === vars.y.value ? "y" : "x"; + vars.self[axis]({ + scale: "discrete" + }); + } +}; + +line.shapes = ["line"]; + +line.tooltip = "static"; + +module.exports = line; + + +},{"../../array/sort.coffee":36,"../../core/fetch/value.coffee":69,"./helpers/graph/draw.coffee":317,"./helpers/graph/nest.coffee":323,"./helpers/graph/stack.coffee":324}],326:[function(require,module,exports){ +var smallestGap = require("../../network/smallestGap.coffee"), + fetchValue = require("../../core/fetch/value.coffee"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Network +//------------------------------------------------------------------------------ +var network = function(vars) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Use filtered lists if they are available + //---------------------------------------------------------------------------- + var nodes = vars.nodes.restricted || vars.nodes.value, + edges = vars.edges.restricted || vars.edges.value; + + var x_range = d3.extent(nodes,function(n){return n.x}), + y_range = d3.extent(nodes,function(n){return n.y}) + + var val_range = [ 1 , 1 ] + if (typeof vars.size.value === "number"){ + val_range = [vars.size.value, vars.size.value] + } + else if (vars.size.value){ + val_range = d3.extent(nodes, function(d){ + var val = fetchValue( vars , d , vars.size.value ) + return val === 0 ? null : val + }) + } + if (typeof val_range[0] == "undefined") val_range = [1,1] + + if (typeof vars.size.value === "number"){ + var max_size = vars.size.value; + var min_size = vars.size.value; + } + else { + + var max_size = smallestGap(nodes, {"accessor": function(n){ + return [n.x, n.y]; + }}); + + var limit = max_size/2; + + var overlap = vars.size.value ? vars.nodes.overlap : 0.4 + max_size = max_size * overlap; + + if (vars.edges.arrows.value) { + max_size = max_size * 0.5; + } + + if (val_range[0] === val_range[1]) { + var min_size = limit; + max_size = limit; + } + else { + + var width = (x_range[1]+max_size*1.1)-(x_range[0]-max_size*1.1), + height = (y_range[1]+max_size*1.1)-(y_range[0]-max_size*1.1), + aspect = width/height, + app = vars.width.viz/vars.height.viz; + + if ( app > aspect ) { + var scale = vars.height.viz/height; + } + else { + var scale = vars.width.viz/width; + } + var min_size = max_size * 0.25; + if ( min_size * scale < 2 ) { + min_size = 2/scale; + } + + } + } + + // Create size scale + var radius = vars.size.scale.value + .domain(val_range) + .range([min_size, max_size]) + + vars.zoom.bounds = [ [ x_range[0]-max_size*1.1 , y_range[0]-max_size*1.1 ] + , [ x_range[1]+max_size*1.1 , y_range[1]+max_size*1.1 ] ] + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Match nodes to data + //---------------------------------------------------------------------------- + var data = [], lookup = {} + nodes.forEach(function(n){ + + var d = vars.data.viz.filter(function(a){ + return a[vars.id.value] == n[vars.id.value] + })[0] + + var obj = d || {} + + obj[vars.id.value] = n[vars.id.value] + + obj.d3plus = {} + obj.d3plus.x = n.x + obj.d3plus.y = n.y + var val = fetchValue(vars,obj,vars.size.value) + obj.d3plus.r = val ? radius(val) : radius.range()[0] + lookup[obj[vars.id.value]] = { + "x": obj.d3plus.x, + "y": obj.d3plus.y, + "r": obj.d3plus.r + } + + data.push(obj) + }) + + data.sort(function(a,b){ + return b.d3plus.r - a.d3plus.r + }) + + edges.forEach(function(l,i){ + + if (l.d3plus) { + delete l.d3plus.spline + } + + l[vars.edges.source].d3plus = {} + var source = lookup[l[vars.edges.source][vars.id.value]] + if (source !== undefined) { + l[vars.edges.source].d3plus.r = source.r + l[vars.edges.source].d3plus.x = source.x + l[vars.edges.source].d3plus.y = source.y + } else { + delete l[vars.edges.source].d3plus; + } + + l[vars.edges.target].d3plus = {} + var target = lookup[l[vars.edges.target][vars.id.value]] + if (target !== undefined) { + l[vars.edges.target].d3plus.r = target.r + l[vars.edges.target].d3plus.x = target.x + l[vars.edges.target].d3plus.y = target.y + } else { + delete l[vars.edges.target].d3plus; + } + + }) + + return {"nodes": data, "edges": edges} + +} + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Visualization Settings and Helper Functions +//------------------------------------------------------------------------------ +network.nesting = false +network.requirements = ["nodes","edges"] +network.scale = 1.05 +network.shapes = [ "circle" , "square" , "donut" ] +network.tooltip = "static" +network.zoom = true + +module.exports = network + +},{"../../core/fetch/value.coffee":69,"../../network/smallestGap.coffee":171}],327:[function(require,module,exports){ +var fetchValue, shortestPath, uniqueValues, viz, + indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; + +shortestPath = require("../../network/shortestPath.coffee"); + +fetchValue = require("../../core/fetch/value.coffee"); + +uniqueValues = require("../../util/uniques.coffee"); + +viz = function(vars) { + var base, base1, base2, base3, col, colIndex, columnWidth, columns, edge, edgeInt, edges, i, id, j, k, l, labelSpace, lastDir, lastHop, len, len1, len2, len3, len4, len5, len6, len7, m, maxRadius, minRadius, n, newPath, next, nextDir, nextHop, nextIndex, node, o, p, path, pathInt, pathLookup, paths, prev, prevIndex, q, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, rowHeight, rows, size, sizeDomain, val, x, xDiff, y, yDomain; + edges = []; + pathLookup = {}; + pathLookup[vars.focus.value[0]] = 0; + pathLookup[vars.focus.value[1]] = 0; + paths = { + all: [[vars.focus.value[0]], [vars.focus.value[1]]] + }; + ref = viz.paths; + for (pathInt = j = 0, len = ref.length; j < len; pathInt = ++j) { + path = ref[pathInt]; + edges = edges.concat(path.edges); + lastHop = vars.focus.value[0]; + paths[pathInt] = [lastHop]; + ref1 = path.edges; + for (edgeInt = k = 0, len1 = ref1.length; k < len1; edgeInt = ++k) { + edge = ref1[edgeInt]; + edge[vars.edges.source] = vars.data.viz.filter(function(d) { + return edge[vars.edges.source][vars.id.value] === d[vars.id.value]; + })[0]; + edge[vars.edges.target] = vars.data.viz.filter(function(d) { + return edge[vars.edges.target][vars.id.value] === d[vars.id.value]; + })[0]; + nextDir = edge[vars.edges.source][vars.id.value] === lastHop ? "target" : "source"; + nextHop = edge[vars.edges[nextDir]][vars.id.value]; + if (pathLookup[nextHop] === void 0) { + pathLookup[nextHop] = pathInt; + } + paths[pathInt].push(nextHop); + lastHop = nextHop; + } + } + rows = 0; + for (pathInt in paths) { + path = paths[pathInt]; + if (pathInt !== "all") { + newPath = 0; + for (i = l = 0, len2 = path.length; l < len2; i = ++l) { + id = path[i]; + if ((i !== 0 && i !== (path.length - 1)) && pathLookup[id] === parseFloat(pathInt)) { + newPath = 1; + prev = path[i - 1]; + next = path[i + 1]; + prevIndex = null; + nextIndex = null; + ref2 = paths.all; + for (colIndex = m = 0, len3 = ref2.length; m < len3; colIndex = ++m) { + col = ref2[colIndex]; + if (indexOf.call(col, prev) >= 0) { + prevIndex = colIndex; + } + if (indexOf.call(col, next) >= 0) { + nextIndex = colIndex; + } + } + if (prevIndex !== null && nextIndex === null) { + if (prevIndex + 1 === paths.all.length - 1) { + paths.all.splice(prevIndex + 1, 0, [id]); + } else { + paths.all[prevIndex + 1].push(id); + } + } else if (nextIndex - prevIndex === 1) { + paths.all.splice(nextIndex, 0, [id]); + } else if (nextIndex - prevIndex > 1) { + paths.all[nextIndex - 1].push(id); + } + } + } + rows += newPath; + } + } + rowHeight = Math.floor(vars.height.viz / rows); + yDomain = []; + i = 0; + while (i < rows) { + if (i % 2 === 0) { + yDomain.push(i); + } else { + yDomain.unshift(i); + } + i++; + } + labelSpace = vars.size.value && !vars.small ? 30 : 0; + y = d3.scale.ordinal().domain(yDomain).range(d3.range(rowHeight / 2 - labelSpace, vars.height.viz + rowHeight / 2 - labelSpace, (vars.height.viz - rowHeight) / (rows - 1))); + columns = paths["all"].length; + columnWidth = Math.floor(vars.width.viz / columns); + x = d3.scale.linear().domain([0, columns - 1]).rangeRound([columnWidth / 2, vars.width.viz - columnWidth / 2]); + minRadius = 5; + maxRadius = d3.min([columnWidth, rowHeight - labelSpace]) * 0.4; + sizeDomain = d3.extent(vars.data.viz, function(node) { + var val; + val = fetchValue(vars, node, vars.size.value); + return val || 0; + }); + size = vars.size.scale.value.domain(sizeDomain).rangeRound([minRadius, maxRadius]); + ref3 = vars.data.viz; + for (n = 0, len4 = ref3.length; n < len4; n++) { + node = ref3[n]; + if (node.d3plus == null) { + node.d3plus = {}; + } + ref4 = paths["all"]; + for (colIndex = o = 0, len5 = ref4.length; o < len5; colIndex = ++o) { + col = ref4[colIndex]; + if (ref5 = node[vars.id.value], indexOf.call(col, ref5) >= 0) { + node.d3plus.x = x(colIndex); + } + } + node.d3plus.y = y(pathLookup[node[vars.id.value]]); + if (vars.size.value) { + val = fetchValue(vars, node, vars.size.value); + node.d3plus.r = val ? size(val) : minRadius; + } else { + node.d3plus.r = maxRadius; + } + if (node.d3plus.r < columnWidth * 0.1 && !vars.small) { + node.d3plus.label = { + x: 0, + y: node.d3plus.r + vars.labels.padding * 2, + w: columnWidth * 0.6, + h: labelSpace + maxRadius - node.d3plus.r, + resize: false + }; + } else { + delete node.d3plus.label; + } + } + ref6 = viz.paths; + for (pathInt = p = 0, len6 = ref6.length; p < len6; pathInt = ++p) { + path = ref6[pathInt]; + lastHop = vars.focus.value[0]; + ref7 = path.edges; + for (edgeInt = q = 0, len7 = ref7.length; q < len7; edgeInt = ++q) { + edge = ref7[edgeInt]; + nextDir = edge[vars.edges.source][vars.id.value] === lastHop ? "target" : "source"; + lastDir = nextDir === "target" ? "source" : "target"; + nextHop = edge[vars.edges[nextDir]][vars.id.value]; + if (pathLookup[lastHop] !== pathLookup[nextHop]) { + edge.d3plus = { + spline: true + }; + if ((base = edge[vars.edges.source]).d3plus == null) { + base.d3plus = {}; + } + if ((base1 = edge[vars.edges.source].d3plus).edges == null) { + base1.edges = {}; + } + if ((base2 = edge[vars.edges.target]).d3plus == null) { + base2.d3plus = {}; + } + if ((base3 = edge[vars.edges.target].d3plus).edges == null) { + base3.edges = {}; + } + xDiff = edge[nextDir].d3plus.x - edge[lastDir].d3plus.x; + edge[lastDir].d3plus.edges[edge[nextDir][vars.id.value]] = { + angle: Math.PI, + radius: columnWidth / 2 + }; + edge[nextDir].d3plus.edges[edge[lastDir][vars.id.value]] = { + angle: 0, + radius: columnWidth / 2, + offset: xDiff - columnWidth + }; + } else { + delete edge.d3plus; + } + lastHop = nextHop; + } + } + return { + nodes: vars.data.viz, + edges: edges + }; +}; + +viz.filter = function(vars, data) { + var added, d, edge, edges, id, ids, j, k, l, len, len1, len2, obj, path, ref, ref1, returnData, source, target; + edges = vars.edges.filtered || vars.edges.value; + viz.paths = shortestPath(edges, vars.focus.value[0], { + target: vars.focus.value[1], + distance: vars.edges.size.value || void 0, + nodeid: vars.id.value, + startpoint: vars.edges.source, + endpoint: vars.edges.target, + K: vars.edges.limit.value || 5 + }); + viz.nodes = []; + added = []; + ref = viz.paths; + for (j = 0, len = ref.length; j < len; j++) { + path = ref[j]; + ref1 = path.edges; + for (k = 0, len1 = ref1.length; k < len1; k++) { + edge = ref1[k]; + source = edge[vars.edges.source]; + target = edge[vars.edges.target]; + if (added.indexOf(source[vars.id.value]) < 0) { + viz.nodes.push(source); + added.push(source[vars.id.value]); + } + if (added.indexOf(target[vars.id.value]) < 0) { + viz.nodes.push(target); + added.push(target[vars.id.value]); + } + } + } + ids = uniqueValues(viz.nodes, vars.id.value, fetchValue, vars); + returnData = []; + for (l = 0, len2 = ids.length; l < len2; l++) { + id = ids[l]; + d = data.filter(function(d) { + return d[vars.id.value] === id; + }); + if (!d[0]) { + obj = { + d3plus: {} + }; + obj[vars.id.value] = id; + returnData.push(obj); + } else { + returnData.push(d[0]); + } + } + return returnData; +}; + +viz.nesting = false; + +viz.requirements = [ + function(vars) { + return { + status: vars.focus.value.length === 2, + text: vars.format.locale.value.method.focus + " x 2" + }; + }, "edges" +]; + +viz.scale = 1; + +viz.shapes = ["circle", "square", "donut"]; + +viz.tooltip = "static"; + +module.exports = viz; + + +},{"../../core/fetch/value.coffee":69,"../../network/shortestPath.coffee":170,"../../util/uniques.coffee":213}],328:[function(require,module,exports){ +var comparator, dataThreshold, groupData, pie; + +comparator = require("../../array/comparator.coffee"); + +dataThreshold = require("../../core/data/threshold.js"); + +groupData = require("../../core/data/group.coffee"); + +pie = function(vars) { + var d, groupedData, i, item, len, pieData, pieLayout, radius, returnData; + pieLayout = d3.layout.pie().value(function(d) { + return d.value; + }).sort(function(a, b) { + if (vars.order.value) { + return comparator(a.d3plus, b.d3plus, [vars.order.value], vars.order.sort.value, [], vars); + } else if (vars.id.nesting.length > 1) { + return comparator(a.d3plus, b.d3plus, vars.id.nesting.concat([vars.size.value]), void 0, [], vars); + } else { + return comparator(a.d3plus, b.d3plus, [vars.size.value], "desc", [], vars); + } + }); + groupedData = groupData(vars, vars.data.viz, []); + pieData = pieLayout(groupedData); + returnData = []; + radius = d3.min([vars.width.viz, vars.height.viz]) / 2 - vars.labels.padding * 2; + for (i = 0, len = pieData.length; i < len; i++) { + d = pieData[i]; + item = d.data.d3plus; + item.d3plus.startAngle = d.startAngle; + item.d3plus.endAngle = d.endAngle; + item.d3plus.r = radius; + item.d3plus.x = vars.width.viz / 2; + item.d3plus.y = vars.height.viz / 2; + item.d3plus.share = (d.endAngle - d.startAngle) / (Math.PI * 2); + returnData.push(item); + } + return returnData; +}; + +pie.filter = dataThreshold; + +pie.requirements = ["data", "size"]; + +pie.shapes = ["arc"]; + +pie.threshold = function(vars) { + return (40 * 40) / (vars.width.viz * vars.height.viz); +}; + +module.exports = pie; + + +},{"../../array/comparator.coffee":34,"../../core/data/group.coffee":59,"../../core/data/threshold.js":63}],329:[function(require,module,exports){ +var buckets, comparator, dataThreshold, fetchText, fetchValue, fontSizes, offset, radar, sort, textwrap, uniques; + +comparator = require("../../array/comparator.coffee"); + +sort = require("../../array/sort.coffee"); + +dataThreshold = require("../../core/data/threshold.js"); + +fetchText = require("../../core/fetch/text.js"); + +fetchValue = require("../../core/fetch/value.coffee"); + +fontSizes = require("../../font/sizes.coffee"); + +offset = require("../../geom/offset.coffee"); + +textwrap = require("../../textwrap/textwrap.coffee"); + +buckets = require("../../util/buckets.coffee"); + +uniques = require("../../util/uniques.coffee"); + +radar = function(vars) { + var a, a2, anchor, angle, buffer, c, center, children, d, data, first, grid, gridStyle, i, idIndex, ids, intervals, j, k, l, labelData, labelGroup, labelHeight, labelIndex, labelStyle, labelWidth, labels, len, len1, len2, len3, m, maxData, maxRadius, n, nextDepth, nextLevel, o, ov, radius, ref, ref1, righty, ringData, ringStyle, rings, second, sizes, text, textStyle, top, total, x, y; + data = vars.data.viz; + nextDepth = vars.depth.value + 1; + nextLevel = vars.id.nesting[nextDepth]; + children = (function() { + var j, len, results; + results = []; + for (j = 0, len = data.length; j < len; j++) { + d = data[j]; + results.push(d[nextLevel]); + } + return results; + })(); + total = (function() { + var j, len, results; + results = []; + for (j = 0, len = data.length; j < len; j++) { + d = data[j]; + results.push(uniques(data, nextLevel, fetchValue, vars, nextDepth)); + } + return results; + })(); + total = uniques(d3.merge(total)).length; + angle = Math.PI * 2 / total; + maxRadius = d3.min([vars.width.viz, vars.height.viz]) / 2; + labelHeight = 0; + labelWidth = 0; + labels = (function() { + var j, len, results; + results = []; + for (j = 0, len = children.length; j < len; j++) { + c = children[j]; + results.push(fetchText(vars, c, nextDepth)[0]); + } + return results; + })(); + labels = uniques(d3.merge(labels)); + if (vars.labels.value) { + first = offset(Math.PI / 2, maxRadius); + second = offset(angle + Math.PI / 2, maxRadius); + labelHeight = (first.x - second.x) - vars.labels.padding * 2; + textStyle = { + "fill": vars.x.ticks.font.color, + "font-family": vars.x.ticks.font.family.value, + "font-weight": vars.x.ticks.font.weight, + "font-size": vars.x.ticks.font.size + "px" + }; + sizes = fontSizes(labels, textStyle, { + mod: function(elem) { + return textwrap().container(d3.select(elem)).width(vars.height.viz / 8).height(labelHeight).draw(); + } + }); + labelWidth = d3.max(sizes, function(d) { + return d.width; + }); + maxRadius -= labelWidth; + maxRadius -= vars.labels.padding * 2; + } + maxData = (function() { + var j, len, results; + results = []; + for (j = 0, len = children.length; j < len; j++) { + c = children[j]; + results.push((function() { + var k, len1, results1; + results1 = []; + for (k = 0, len1 = c.length; k < len1; k++) { + d = c[k]; + results1.push(fetchValue(vars, d, vars.size.value)); + } + return results1; + })()); + } + return results; + })(); + maxData = d3.max(d3.merge(maxData)); + radius = d3.scale.linear().domain([0, maxData]).range([0, maxRadius]); + ids = (function() { + var j, len, results; + results = []; + for (j = 0, len = children.length; j < len; j++) { + c = children[j]; + results.push(fetchValue(vars, c, nextLevel)); + } + return results; + })(); + ids = uniques(d3.merge(ids)); + idIndex = d3.scale.ordinal().domain(ids).range(d3.range(0, ids.length)); + for (j = 0, len = data.length; j < len; j++) { + d = data[j]; + d.d3plus.x = vars.width.viz / 2 + vars.margin.top; + d.d3plus.y = vars.height.viz / 2 + vars.margin.left; + ref = d[nextLevel]; + for (i = k = 0, len1 = ref.length; k < len1; i = ++k) { + a = ref[i]; + if (!a.d3plus) { + a.d3plus = {}; + } + a.d3plus.r = radius(fetchValue(vars, a, vars.size.value)); + a.d3plus.a = idIndex(fetchValue(vars, a, nextLevel)) * angle; + } + } + intervals = 1; + ref1 = [10, 5, 4, 2]; + for (m = 0, len2 = ref1.length; m < len2; m++) { + i = ref1[m]; + if (maxRadius / i >= 20) { + intervals = i; + break; + } + } + ringData = buckets([maxRadius / intervals, maxRadius], intervals - 1).reverse(); + if (ringData.length === intervals) { + ringData.shift(); + } + rings = vars.group.selectAll(".d3plus_radar_rings").data(ringData, function(d, i) { + return i; + }); + ringStyle = function(ring) { + return ring.attr("fill", function(d, i) { + if (i === 0) { + return vars.axes.background.color; + } else { + return "transparent"; + } + }).attr("cx", vars.width.viz / 2 + vars.margin.top).attr("cy", vars.height.viz / 2 + vars.margin.left).attr("stroke", vars.x.grid.value ? vars.x.grid.color : "transparent"); + }; + rings.enter().append("circle").attr("class", "d3plus_radar_rings").call(ringStyle).attr("r", 0); + rings.transition().duration(vars.draw.timing).call(ringStyle).attr("r", function(d) { + return d; + }); + rings.exit().transition().duration(vars.draw.timing).attr("opacity", 0).remove(); + labelIndex = d3.scale.ordinal().domain(labels).range(d3.range(0, labels.length)); + labelData = []; + for (n = 0, len3 = labels.length; n < len3; n++) { + l = labels[n]; + a2 = (angle * labelIndex(l)) - Math.PI / 2; + a = a2 * (180 / Math.PI); + if (a < -90 || a > 90) { + a = a - 180; + buffer = -(maxRadius + vars.labels.padding * 2 + labelWidth); + anchor = "end"; + } else { + buffer = maxRadius + vars.labels.padding * 2; + anchor = "start"; + } + top = a2 < 0 || a2 > Math.PI; + righty = a2 < Math.PI / 2; + ov = maxRadius; + if (vars.labels.value) { + ov += vars.labels.padding; + } + o = offset(a2, ov); + x = o.x; + y = o.y; + if (!righty) { + x -= labelWidth; + } + if (top) { + y -= labelHeight; + } + center = [0, Math.PI].indexOf(angle * labelIndex(l)) >= 0; + if (center) { + x -= labelWidth / 2; + } + labelData.push({ + "text": l, + "angle": a, + "x": buffer, + "anchor": anchor, + "offset": o + }); + } + labelGroup = vars.group.selectAll("g.d3plus_radar_label_group").data([0]); + labelGroup.enter().append("g").attr("class", "d3plus_radar_label_group").attr("transform", "translate(" + vars.width.viz / 2 + "," + vars.height.viz / 2 + ")"); + labelGroup.transition().duration(vars.draw.timing).attr("transform", "translate(" + vars.width.viz / 2 + "," + vars.height.viz / 2 + ")"); + text = labelGroup.selectAll(".d3plus_radar_labels").data((vars.labels.value ? labelData : []), function(d, i) { + return i; + }); + labelStyle = function(label) { + return label.attr(textStyle).each(function(l, i) { + return textwrap().container(d3.select(this)).height(labelHeight).width(labelWidth).align(l.anchor).text(l.text).padding(0).valign("middle").x(l.x).y(-labelHeight / 2).draw(); + }).attr("transform", function(t) { + var translate; + translate = d3.select(this).attr("transform") || ""; + if (translate.length) { + translate = translate.split(")").slice(-3).join(")"); + } + return "rotate(" + t.angle + ")" + translate; + }); + }; + text.call(labelStyle); + text.enter().append("text").attr("class", "d3plus_radar_labels").attr("opacity", 0).call(labelStyle).transition().duration(vars.draw.timing).attr("opacity", 1); + text.exit().transition().duration(vars.draw.timing).attr("opacity", 0).remove(); + grid = vars.group.selectAll(".d3plus_radar_lines").data(labelData, function(d, i) { + return i; + }); + gridStyle = function(grid) { + return grid.attr("stroke", vars.x.grid.color).attr("x1", vars.width.viz / 2 + vars.margin.left).attr("y1", vars.height.viz / 2 + vars.margin.top); + }; + grid.enter().append("line").attr("class", "d3plus_radar_lines").call(gridStyle).attr("x2", vars.width.viz / 2 + vars.margin.left).attr("y2", vars.height.viz / 2 + vars.margin.top); + grid.transition().duration(vars.draw.timing).call(gridStyle).attr("x2", function(d) { + return vars.width.viz / 2 + vars.margin.left + d.offset.x; + }).attr("y2", function(d) { + return vars.height.viz / 2 + vars.margin.top + d.offset.y; + }); + grid.exit().transition().duration(vars.draw.timing).attr("opacity", 0).remove(); + vars.mouse.viz = { + click: false + }; + return data; +}; + +radar.requirements = ["data", "size"]; + +radar.shapes = ["radial"]; + +module.exports = radar; + + +},{"../../array/comparator.coffee":34,"../../array/sort.coffee":36,"../../core/data/threshold.js":63,"../../core/fetch/text.js":68,"../../core/fetch/value.coffee":69,"../../font/sizes.coffee":104,"../../geom/offset.coffee":163,"../../textwrap/textwrap.coffee":203,"../../util/buckets.coffee":207,"../../util/uniques.coffee":213}],330:[function(require,module,exports){ +var arraySort = require("../../array/sort.coffee"), + events = require("../../client/pointer.coffee"), + fetchValue = require("../../core/fetch/value.coffee"), + fetchColor = require("../../core/fetch/color.coffee"), + legible = require("../../color/legible.coffee"), + removeTooltip = require("../../tooltip/remove.coffee"), + smallestGap = require("../../network/smallestGap.coffee"), + textColor = require("../../color/text.coffee"), + uniqueValues = require("../../util/uniques.coffee") + +var rings = function(vars) { + + var radius = d3.min([vars.height.viz,vars.width.viz])/2 + , ring_width = vars.small || !vars.labels.value + ? (radius-vars.labels.padding*2)/2 : radius/3 + , primaryRing = vars.small || !vars.labels.value + ? ring_width*1.4 : ring_width + , secondaryRing = ring_width*2 + , edges = [] + , nodes = [] + + var center = vars.data.viz.filter(function(d){ + return d[vars.id.value] === vars.focus.value[0] + })[0] + + if ( !center ) { + center = { "d3plus" : {} } + center[vars.id.value] = vars.focus.value[0] + } + + center.d3plus.x = vars.width.viz/2 + center.d3plus.y = vars.height.viz/2 + center.d3plus.r = primaryRing*.65 + + var primaries = [], claimed = [vars.focus.value[0]] + vars.edges.connections(vars.focus.value[0],vars.id.value).forEach(function(edge){ + + var c = edge[vars.edges.source][vars.id.value] == vars.focus.value[0] ? edge[vars.edges.target] : edge[vars.edges.source] + var n = vars.data.viz.filter(function(d){ + return d[vars.id.value] === c[vars.id.value] + })[0] + + if ( !n ) { + n = { "d3plus" : {} } + n[vars.id.value] = c[vars.id.value] + } + + n.d3plus.edges = vars.edges.connections(n[vars.id.value],vars.id.value).filter(function(c){ + return c[vars.edges.source][vars.id.value] != vars.focus.value[0] && c[vars.edges.target][vars.id.value] != vars.focus.value[0] + }) + n.d3plus.edge = edge + claimed.push(n[vars.id.value]) + primaries.push(n) + + }) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Sort primary nodes by children (smallest to largest) and then by sort + // order. + //-------------------------------------------------------------------------- + var sort = vars.order.value || vars.color.value + || vars.size.value || vars.id.value + + primaries.sort(function(a,b){ + + var lengthdiff = a.d3plus.edges.length - b.d3plus.edges.length + + if ( lengthdiff ) { + + return lengthdiff + + } + else { + + return arraySort( [a,b] , sort , vars.order.sort.value + , vars.color.value || [] , vars) + + } + + }) + + if (typeof vars.edges.limit.value == "number") { + primaries = primaries.slice(0,vars.edges.limit.value) + } + else if (typeof vars.edges.limit.value == "function") { + primaries = vars.edges.limit.value(primaries) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check for similar children and give preference to nodes with less + // overall children. + //---------------------------------------------------------------------------- + var secondaries = [], total = 0 + primaries.forEach(function(p){ + + var primaryId = p[vars.id.value] + + p.d3plus.edges = p.d3plus.edges.filter(function(c){ + + var source = c[vars.edges.source][vars.id.value] + , target = c[vars.edges.target][vars.id.value] + return (claimed.indexOf(source) < 0 && target == primaryId) + || (claimed.indexOf(target) < 0 && source == primaryId) + + }) + + total += p.d3plus.edges.length || 1 + + p.d3plus.edges.forEach(function(c){ + + var source = c[vars.edges.source] + , target = c[vars.edges.target] + var claim = target[vars.id.value] == primaryId ? source : target + claimed.push(claim[vars.id.value]) + + }) + }) + + arraySort( primaries , sort , vars.order.sort.value + , vars.color.value || [] , vars) + + var offset = 0, + radian = Math.PI*2, + start = 0 + + primaries.forEach(function(p,i){ + + var children = p.d3plus.edges.length || 1, + space = (radian/total)*children + + if (i == 0) { + start = angle + offset -= space/2 + } + + var angle = offset+(space/2) + angle -= radian/4 + + p.d3plus.radians = angle + p.d3plus.x = vars.width.viz/2 + (primaryRing * Math.cos(angle)) + p.d3plus.y = vars.height.viz/2 + (primaryRing * Math.sin(angle)) + + offset += space + p.d3plus.edges.sort(function(a,b){ + + var a = a[vars.edges.source][vars.id.value] == p[vars.id.value] + ? a[vars.edges.target] : a[vars.edges.source] + , b = b[vars.edges.source][vars.id.value] == p[vars.id.value] + ? b[vars.edges.target] : b[vars.edges.source] + + return arraySort( [a,b] , sort , vars.order.sort.value + , vars.color.value || [] , vars) + + }) + + p.d3plus.edges.forEach(function(edge,i){ + + var c = edge[vars.edges.source][vars.id.value] == p[vars.id.value] + ? edge[vars.edges.target] : edge[vars.edges.source] + , s = radian/total + + var d = vars.data.viz.filter(function(a){ + return a[vars.id.value] === c[vars.id.value] + })[0] + + if ( !d ) { + d = { "d3plus" : {} } + d[vars.id.value] = c[vars.id.value] + } + + a = (angle-(s*children/2)+(s/2))+((s)*i) + d.d3plus.radians = a + d.d3plus.x = vars.width.viz/2 + ((secondaryRing) * Math.cos(a)) + d.d3plus.y = vars.height.viz/2 + ((secondaryRing) * Math.sin(a)) + secondaries.push(d) + }) + + }) + + var primaryDistance = smallestGap(primaries,{"accessor": function(n){ + return [n.d3plus.x, n.d3plus.y] + }}) + , secondaryDistance = smallestGap(secondaries,{"accessor": function(n){ + return [n.d3plus.x, n.d3plus.y] + }}) + + if (!primaryDistance) { + primaryDistance = ring_width/2 + } + + if (!secondaryDistance) { + secondaryDistance = ring_width/4 + } + + if (primaryDistance/2 - 4 < 8) { + var primaryMax = d3.min([primaryDistance/2,8]) + } + else { + var primaryMax = primaryDistance/2 - 4 + } + + if (secondaryDistance/2 - 4 < 4) { + var secondaryMax = d3.min([secondaryDistance/2,4]) + } + else { + var secondaryMax = secondaryDistance/2 - 4 + } + + if (secondaryMax > ring_width/10) { + secondaryMax = ring_width/10 + } + + if (secondaryMax > primaryMax && secondaryMax > 10) { + secondaryMax = primaryMax*.75 + } + if (primaryMax > secondaryMax*1.5) { + primaryMax = secondaryMax*1.5 + } + + primaryMax = Math.floor(primaryMax) + secondaryMax = Math.floor(secondaryMax) + + var ids = uniqueValues(primaries, vars.id.value, fetchValue, vars) + ids = ids.concat(uniqueValues(secondaries, vars.id.value, fetchValue, vars)) + ids.push(vars.focus.value[0]) + + var data = vars.data.viz.filter(function(d){ + return ids.indexOf(d[vars.id.value]) >= 0 + }) + + if (vars.size.value) { + + var domain = d3.extent(data,function(d){ + return fetchValue(vars,d,vars.size.value) + }) + + if (domain[0] == domain[1]) { + domain[0] = 0 + } + + var radius = d3.scale.linear() + .domain(domain) + .rangeRound([3,d3.min([primaryMax,secondaryMax])]) + + var val = fetchValue(vars,center,vars.size.value) + center.d3plus.r = radius(val) + + } + else { + + var radius = d3.scale.linear() + .domain([1,2]) + .rangeRound([primaryMax,secondaryMax]) + + + if (vars.edges.label) { + center.d3plus.r = radius(1)*1.5 + } + + } + + secondaries.forEach(function(s){ + s.d3plus.ring = 2 + var val = vars.size.value ? fetchValue(vars,s,vars.size.value) : 2 + s.d3plus.r = radius(val) + }) + + primaries.forEach(function(p){ + p.d3plus.ring = 1 + var val = vars.size.value ? fetchValue(vars,p,vars.size.value) : 1 + p.d3plus.r = radius(val) + }) + + nodes = [center].concat(primaries).concat(secondaries) + + primaries.forEach(function(p,i){ + + var check = [vars.edges.source,vars.edges.target] + , edge = p.d3plus.edge + + check.forEach(function(node){ + + edge[node] = nodes.filter(function(n){ + return n[vars.id.value] == edge[node][vars.id.value] + })[0] + + }) + + delete edge.d3plus + edges.push(edge) + + vars.edges.connections(p[vars.id.value],vars.id.value).forEach(function(edge){ + + var c = edge[vars.edges.source][vars.id.value] == p[vars.id.value] + ? edge[vars.edges.target] : edge[vars.edges.source] + + if (c[vars.id.value] != center[vars.id.value]) { + + var target = secondaries.filter(function(s){ + return s[vars.id.value] == c[vars.id.value] + })[0] + + if (!target) { + var r = primaryRing + target = primaries.filter(function(s){ + return s[vars.id.value] == c[vars.id.value] + })[0] + } + else { + var r = secondaryRing + } + + if (target) { + + edge.d3plus = { + "spline": true, + "translate": { + "x": vars.width.viz/2, + "y": vars.height.viz/2 + } + } + + var check = [vars.edges.source,vars.edges.target] + + check.forEach(function(node,i){ + + edge[node] = nodes.filter(function(n){ + return n[vars.id.value] == edge[node][vars.id.value] + })[0] + + if (edge[node].d3plus.edges === undefined) edge[node].d3plus.edges = {} + + var oppID = i === 0 ? edge[vars.edges.target][vars.id.value] : edge[vars.edges.source][vars.id.value] + + if (edge[node][vars.id.value] == p[vars.id.value]) { + + edge[node].d3plus.edges[oppID] = { + "angle": p.d3plus.radians + Math.PI, + "radius": ring_width/2 + } + + } + else { + + edge[node].d3plus.edges[oppID] = { + "angle": target.d3plus.radians, + "radius": ring_width/2 + } + + } + }) + + edges.push(edge) + + } + + } + + }) + + }) + + var labelColor = false; + if (vars.background.value && + ["transparent", "none"].indexOf(vars.background.value) < 0 && + d3.hsl(vars.background.value).l < 0.5) { + labelColor = textColor(vars.background.value); + } + + nodes.forEach(function(n) { + + if (!vars.small && vars.labels.value) { + + if (n[vars.id.value] != vars.focus.value[0]) { + + n.d3plus.rotate = n.d3plus.radians*(180/Math.PI) + + var angle = n.d3plus.rotate, + width = ring_width-(vars.labels.padding*3)-n.d3plus.r + + if (angle < -90 || angle > 90) { + angle = angle-180 + var buffer = -(n.d3plus.r+width/2+vars.labels.padding), + anchor = "end" + } + else { + var buffer = n.d3plus.r+width/2+vars.labels.padding, + anchor = "start" + } + + var background = primaries.indexOf(n) >= 0 ? true : false + + var height = n.d3plus.ring == 1 ? primaryDistance : secondaryDistance + + n.d3plus.label = { + "x": buffer, + "y": 0, + "w": width, + "h": height, + "angle": angle, + "anchor": anchor, + "valign": "center", + "color": labelColor || legible(fetchColor(vars,n)), + "resize": [8, vars.labels.font.size], + "background": background, + "mouse": true + } + + } + else if (vars.size.value || vars.edges.label) { + + var height = primaryRing-n.d3plus.r*2-vars.labels.padding*2 + + n.d3plus.label = { + "x": 0, + "y": n.d3plus.r+height/2, + "w": primaryRing, + "h": height, + "color": labelColor || legible(fetchColor(vars,n)), + "resize": [10,40], + "background": true, + "mouse": true + } + + } + else { + delete n.d3plus.rotate + delete n.d3plus.label + } + + } + else { + delete n.d3plus.rotate + delete n.d3plus.label + } + + }) + + vars.mouse.viz = {}; + vars.mouse.viz[events.click] = function(d) { + if (d[vars.id.value] != vars.focus.value[0]) { + removeTooltip(vars.type.value); + var old_focus = vars.focus.value[0]; + vars.history.states.push(function(){ + vars.self.focus(old_focus).draw(); + }) + vars.self.focus(d[vars.id.value]).draw(); + } + } + + return {"edges": edges, "nodes": nodes, "data": data} + +}; + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Visualization Settings and Helper Functions +//------------------------------------------------------------------------------ +rings.filter = function( vars , data ) { + + var primaries = vars.edges.connections(vars.focus.value[0],vars.id.value,true) + , secondaries = [] + + primaries.forEach(function(p){ + secondaries = secondaries.concat(vars.edges.connections(p[vars.id.value],vars.id.value,true)) + }) + + var connections = primaries.concat(secondaries) + , ids = uniqueValues(connections, vars.id.value, fetchValue, vars) + , returnData = [] + + ids.forEach(function(id){ + + var d = data.filter(function(d){ + return d[vars.id.value] == id + })[0] + + if ( !d ) { + var obj = {"d3plus": {}} + obj[vars.id.value] = id + returnData.push(obj) + } + else { + returnData.push(d) + } + + }) + + return returnData + +} +rings.nesting = false +rings.scale = 1 +rings.shapes = [ "circle" , "square" , "donut" ] +rings.requirements = [ "edges" , "focus" ] +rings.tooltip = "static" + +module.exports = rings + +},{"../../array/sort.coffee":36,"../../client/pointer.coffee":40,"../../color/legible.coffee":46,"../../color/text.coffee":52,"../../core/fetch/color.coffee":65,"../../core/fetch/value.coffee":69,"../../network/smallestGap.coffee":171,"../../tooltip/remove.coffee":206,"../../util/uniques.coffee":213}],331:[function(require,module,exports){ +var d3sankey, events, removeTooltip, sankey, uniques; + +d3sankey = require("./sankey.js"); + +events = require("../../client/pointer.coffee"); + +removeTooltip = require("../../tooltip/remove.coffee"); + +uniques = require("../../util/uniques.coffee"); + +sankey = function(vars) { + var d, e, edges, focus, i, j, layout, len, len1, n, nodes, padding, placed, returnData, size; + focus = vars.focus.value[0]; + padding = vars.data.stroke.width * 2; + size = vars.size.value.constructor === Number ? vars.size.value : 20; + edges = vars.edges.connections(focus, vars.id.value).filter(function(e) { + return e[vars.edges.source][vars.id.value] !== focus || e[vars.edges.target][vars.id.value] !== focus; + }); + nodes = []; + placed = []; + edges = edges.map(function(e) { + var s, t; + if (e[vars.edges.target][vars.id.value] === focus) { + s = { + id: "left_" + e[vars.edges.source][vars.id.value], + dupe: "left", + data: e[vars.edges.source], + value: e[vars.edges.strength.value] + }; + t = e[vars.edges.target]; + } else { + s = e[vars.edges.source]; + t = { + id: "right_" + e[vars.edges.target][vars.id.value], + dupe: "right", + data: e[vars.edges.target], + value: e[vars.edges.strength.value] + }; + } + if (placed.indexOf(s.id) < 0) { + nodes.push(s); + } + if (placed.indexOf(t.id) < 0) { + nodes.push(t); + } + placed.push(s.id); + placed.push(t.id); + return { + source: s, + target: t, + value: e[vars.edges.strength.value] || 1 + }; + }); + layout = d3sankey().nodeWidth(size).nodePadding(vars.data.padding.value).size([vars.width.viz - padding * 2, vars.height.viz - padding * 2]).nodes(nodes).links(edges).layout(2); + returnData = []; + for (i = 0, len = nodes.length; i < len; i++) { + n = nodes[i]; + d = n.data || n; + d = { + id: d[vars.id.value] + }; + d.d3plus = { + x: n.x + n.dx / 2 + padding, + y: n.y + n.dy / 2 + padding, + width: n.dx, + height: n.dy, + suffix: n.dupe + }; + if (d.id !== focus) { + d[vars.edges.strength.value] = n.value; + } + returnData.push(d); + } + vars.edges.path = layout.link(); + for (j = 0, len1 = edges.length; j < len1; j++) { + e = edges[j]; + e.d3plus = { + x: padding, + y: padding + }; + } + vars.mouse.viz = {}; + vars.mouse.viz[events.click] = function(d) { + var old_focus; + if (d[vars.id.value] !== vars.focus.value[0]) { + removeTooltip(vars.type.value); + old_focus = vars.focus.value[0]; + vars.history.states.push(function() { + return vars.self.focus(old_focus).draw(); + }); + return vars.self.focus(d[vars.id.value]).draw(); + } + }; + return { + nodes: returnData, + edges: edges + }; +}; + +sankey.requirements = ["edges", "focus", "nodes"]; + +sankey.shapes = ["square"]; + +module.exports = sankey; + + +},{"../../client/pointer.coffee":40,"../../tooltip/remove.coffee":206,"../../util/uniques.coffee":213,"./sankey.js":332}],332:[function(require,module,exports){ +module.exports = function() { + var sankey = {}, + nodeWidth = 24, + nodePadding = 8, + size = [1, 1], + nodes = [], + links = []; + + sankey.nodeWidth = function(_) { + if (!arguments.length) return nodeWidth; + nodeWidth = +_; + return sankey; + }; + + sankey.nodePadding = function(_) { + if (!arguments.length) return nodePadding; + nodePadding = +_; + return sankey; + }; + + sankey.nodes = function(_) { + if (!arguments.length) return nodes; + nodes = _; + return sankey; + }; + + sankey.links = function(_) { + if (!arguments.length) return links; + links = _; + return sankey; + }; + + sankey.size = function(_) { + if (!arguments.length) return size; + size = _; + return sankey; + }; + + sankey.layout = function(iterations) { + computeNodeLinks(); + computeNodeValues(); + computeNodeBreadths(); + computeNodeDepths(iterations); + computeLinkDepths(); + return sankey; + }; + + sankey.relayout = function() { + computeLinkDepths(); + return sankey; + }; + + sankey.link = function() { + var curvature = .5; + + function link(d) { + var x0 = d.source.x + d.source.dx, + x1 = d.target.x, + xi = d3.interpolateNumber(x0, x1), + x2 = xi(curvature), + x3 = xi(1 - curvature), + y0 = d.source.y + d.sy + d.dy / 2, + y1 = d.target.y + d.ty + d.dy / 2; + return "M" + x0 + "," + y0 + + "C" + x2 + "," + y0 + + " " + x3 + "," + y1 + + " " + x1 + "," + y1; + } + + link.curvature = function(_) { + if (!arguments.length) return curvature; + curvature = +_; + return link; + }; + + return link; + }; + + // Populate the sourceLinks and targetLinks for each node. + // Also, if the source and target are not objects, assume they are indices. + function computeNodeLinks() { + nodes.forEach(function(node) { + node.sourceLinks = []; + node.targetLinks = []; + }); + links.forEach(function(link) { + var source = link.source, + target = link.target; + if (typeof source === "number") source = link.source = nodes[link.source]; + if (typeof target === "number") target = link.target = nodes[link.target]; + source.sourceLinks.push(link); + target.targetLinks.push(link); + }); + } + + // Compute the value (size) of each node by summing the associated links. + function computeNodeValues() { + nodes.forEach(function(node) { + node.value = Math.max( + d3.sum(node.sourceLinks, value), + d3.sum(node.targetLinks, value) + ); + }); + } + + // Iteratively assign the breadth (x-position) for each node. + // Nodes are assigned the maximum breadth of incoming neighbors plus one; + // nodes with no incoming links are assigned breadth zero, while + // nodes with no outgoing links are assigned the maximum breadth. + function computeNodeBreadths() { + var remainingNodes = nodes, + nextNodes, + x = 0; + + while (remainingNodes.length) { + nextNodes = []; + remainingNodes.forEach(function(node) { + node.x = x; + node.dx = nodeWidth; + node.sourceLinks.forEach(function(link) { + if (nextNodes.indexOf(link.target) < 0) { + nextNodes.push(link.target); + } + }); + }); + remainingNodes = nextNodes; + ++x; + } + + // + moveSinksRight(x); + scaleNodeBreadths((size[0] - nodeWidth) / (x - 1)); + } + + function moveSourcesRight() { + nodes.forEach(function(node) { + if (!node.targetLinks.length) { + node.x = d3.min(node.sourceLinks, function(d) { return d.target.x; }) - 1; + } + }); + } + + function moveSinksRight(x) { + nodes.forEach(function(node) { + if (!node.sourceLinks.length) { + node.x = x - 1; + } + }); + } + + function scaleNodeBreadths(kx) { + nodes.forEach(function(node) { + node.x *= kx; + }); + } + + function computeNodeDepths(iterations) { + var nodesByBreadth = d3.nest() + .key(function(d) { return d.x; }) + .sortKeys(d3.ascending) + .entries(nodes) + .map(function(d) { return d.values; }); + + // + initializeNodeDepth(); + resolveCollisions(); + for (var alpha = 1; iterations > 0; --iterations) { + relaxRightToLeft(alpha *= .99); + resolveCollisions(); + relaxLeftToRight(alpha); + resolveCollisions(); + } + + function initializeNodeDepth() { + var ky = d3.min(nodesByBreadth, function(nodes) { + return (size[1] - (nodes.length - 1) * nodePadding) / d3.sum(nodes, value); + }); + + nodesByBreadth.forEach(function(nodes) { + nodes.forEach(function(node, i) { + node.y = i; + node.dy = node.value * ky; + }); + }); + + links.forEach(function(link) { + link.dy = link.value * ky; + }); + } + + function relaxLeftToRight(alpha) { + nodesByBreadth.forEach(function(nodes, breadth) { + nodes.forEach(function(node) { + if (node.targetLinks.length) { + var y = d3.sum(node.targetLinks, weightedSource) / d3.sum(node.targetLinks, value); + node.y += (y - center(node)) * alpha; + } + }); + }); + + function weightedSource(link) { + return center(link.source) * link.value; + } + } + + function relaxRightToLeft(alpha) { + nodesByBreadth.slice().reverse().forEach(function(nodes) { + nodes.forEach(function(node) { + if (node.sourceLinks.length) { + var y = d3.sum(node.sourceLinks, weightedTarget) / d3.sum(node.sourceLinks, value); + node.y += (y - center(node)) * alpha; + } + }); + }); + + function weightedTarget(link) { + return center(link.target) * link.value; + } + } + + function resolveCollisions() { + nodesByBreadth.forEach(function(nodes) { + var node, + dy, + y0 = 0, + n = nodes.length, + i; + + // Push any overlapping nodes down. + nodes.sort(ascendingDepth); + for (i = 0; i < n; ++i) { + node = nodes[i]; + dy = y0 - node.y; + if (dy > 0) node.y += dy; + y0 = node.y + node.dy + nodePadding; + } + + // If the bottommost node goes outside the bounds, push it back up. + dy = y0 - nodePadding - size[1]; + if (dy > 0) { + y0 = node.y -= dy; + + // Push any overlapping nodes back up. + for (i = n - 2; i >= 0; --i) { + node = nodes[i]; + dy = node.y + node.dy + nodePadding - y0; + if (dy > 0) node.y -= dy; + y0 = node.y; + } + } + }); + } + + function ascendingDepth(a, b) { + return a.y - b.y; + } + } + + function computeLinkDepths() { + nodes.forEach(function(node) { + node.sourceLinks.sort(ascendingTargetDepth); + node.targetLinks.sort(ascendingSourceDepth); + }); + nodes.forEach(function(node) { + var sy = 0, ty = 0; + node.sourceLinks.forEach(function(link) { + link.sy = sy; + sy += link.dy; + }); + node.targetLinks.forEach(function(link) { + link.ty = ty; + ty += link.dy; + }); + }); + + function ascendingSourceDepth(a, b) { + return a.source.y - b.source.y; + } + + function ascendingTargetDepth(a, b) { + return a.target.y - b.target.y; + } + } + + function center(node) { + return node.y + node.dy / 2; + } + + function value(link) { + return link.value; + } + + return sankey; +}; + +},{}],333:[function(require,module,exports){ +var fetchValue, graph, print, scatter, sort, ticks; + +fetchValue = require("../../core/fetch/value.coffee"); + +graph = require("./helpers/graph/draw.coffee"); + +print = require("../../core/console/print.coffee"); + +sort = require("../../array/sort.coffee"); + +ticks = require("./helpers/graph/dataTicks.coffee"); + +scatter = function(vars) { + var d, domains, i, len, ref; + graph(vars, { + buffer: "size", + mouse: true + }); + domains = vars.x.domain.viz.concat(vars.y.domain.viz); + if (domains.indexOf(void 0) >= 0) { + return []; + } + ref = vars.data.viz; + for (i = 0, len = ref.length; i < len; i++) { + d = ref[i]; + d.d3plus.x = vars.x.scale.viz(fetchValue(vars, d, vars.x.value)); + d.d3plus.x += vars.axes.margin.viz.left; + d.d3plus.y = vars.y.scale.viz(fetchValue(vars, d, vars.y.value)); + d.d3plus.y += vars.axes.margin.viz.top; + if (typeof vars.size.value === "number" || !vars.size.value) { + d.d3plus.r = vars.axes.scale(0); + } else { + d.d3plus.r = vars.axes.scale(fetchValue(vars, d, vars.size.value)); + } + } + ticks(vars); + return sort(vars.data.viz, vars.order.value || vars.size.value || vars.id.value, vars.order.sort.value === "desc" ? "asc" : "desc", vars.color.value || [], vars); +}; + +scatter.fill = true; + +scatter.requirements = ["data", "x", "y"]; + +scatter.scale = 1.1; + +scatter.setup = function(vars) { + if (vars.time.value && !vars.axes.discrete) { + if (vars.time.value === vars.x.value) { + vars.self.x({ + scale: "discrete" + }); + } + if (vars.time.value === vars.y.value) { + return vars.self.y({ + scale: "discrete" + }); + } + } +}; + +scatter.shapes = ["circle", "square", "donut"]; + +scatter.tooltip = "static"; + +module.exports = scatter; + + +},{"../../array/sort.coffee":36,"../../core/console/print.coffee":54,"../../core/fetch/value.coffee":69,"./helpers/graph/dataTicks.coffee":316,"./helpers/graph/draw.coffee":317}],334:[function(require,module,exports){ +var fetchValue = require("../../core/fetch/value.coffee"); +var uniques = require("../../util/uniques.coffee"); +var copy = require("../../util/copy.coffee"); +var rand_col = require("../../color/random.coffee"); + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Table +//------------------------------------------------------------------------------ + +var table = function(vars) { + + // get unique IDs and columns + var ids = uniques(vars.data.viz, vars.id.value, fetchValue, vars); + var cols = uniques(vars.cols.value); + + // if user wants to show the row labels (default behavior) add this as a col + if (cols.indexOf("label") < 0 && vars.cols.index.value){ + cols.unshift("label"); + } + + // width/height are a function of number of IDs and columns + var item_height = vars.height.viz / (ids.length+1); // add 1 for header offset + var item_width = vars.width.viz / cols.length; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Setup background + //---------------------------------------------------------------------------- + vars.group.selectAll("rect").data([0]).enter() + .append("rect") + .attr("class", "background") + .attr("height", vars.height.viz) + .attr("width", vars.width.viz) + .style("fill", vars.color.missing) + // draw line separater w/ enter/update/exit + var lines_horiz = vars.group.selectAll("line.horiz").data(vars.data.viz); + lines_horiz.enter().append("line").attr("class", "horiz") + lines_horiz + .attr("x1", 0) + .attr("y1", function(d, row_i){ return (item_height * row_i) + item_height }) + .attr("x2", vars.width.viz) + .attr("y2", function(d, row_i){ return (item_height * row_i) + item_height }) + .style("fill", "#fff") + .style("stroke", "#fff") + lines_horiz.exit().remove() + // draw line separater w/ enter/update/exit + var lines_vert = vars.group.selectAll("line.vert").data(cols); + lines_vert.enter().append("line").attr("class", "vert") + lines_vert + .attr("x1", function(d, col_i){ return (item_width * col_i) + item_width }) + .attr("y1", 0) + .attr("x2", function(d, col_i){ return (item_width * col_i) + item_width }) + .attr("y2", vars.height.viz) + .style("fill", "#fff") + .style("stroke", "#fff") + lines_vert.exit().remove() + + var ret = [] + var colors = {} + + // doing 2 things here, first we add our column headers to our ret array as + // items dor d3plus to draw. We also compute the color scales for each column + cols.forEach(function(col, col_i){ + // add columns + var header = {"d3plus":{ + "x": (item_width * col_i) + item_width/2, + "y": item_height/2, + "width": item_width, + "height": item_height, + "id": "d3p_header_"+col.toString().replace(/ /g,"_"), + "shape": "square", + "color": "#fff", + "text": vars.format.value(col) + }} + if(col == vars.id.value){ + header.d3plus.color = "#fff"; + } + if(col == "label"){ + header.d3plus.label = false; + header.d3plus.color = "#fff"; + header.d3plus.stroke = "#fff"; + } + ret.push(header) + + // set up color scales + if(vars.data.keys[col] == "number"){ + var domain_extent = d3.extent(vars.data.viz, function(d){ return d[col]; }) + if(domain_extent[0] == domain_extent[1]){ + domain_extent = [domain_extent[0]-1, domain_extent[1]] + } + colors[col] = d3.scale.linear().domain(domain_extent).range([vars.color.missing,rand_col(col)]) + } + else if(vars.data.keys[col] == "boolean"){ + colors[col] = function(bool){ + return bool ? rand_col(col) : vars.color.missing; + } + } + }) + + vars.data.viz.forEach(function(d, row_i){ + // offset for column headers + row_i += 1; + + // loop through each user defined column to create new "object" to draw + cols.forEach(function(col, col_i){ + + // need to clone data since we'll be dupliating it for each column + var d_clone = copy(d); + + // set unique ID otherwise it'd be the same in each column + d_clone.d3plus.id = "d3p_"+d_clone[vars.id.value].toString().replace(/ /g,"_")+"_"+col; + d_clone.d3plus.x = (item_width * col_i) + item_width/2; + d_clone.d3plus.y = (item_height * row_i) + item_height/2; + d_clone.d3plus.width = item_width; + d_clone.d3plus.height = item_height; + + if(col == "label"){ + d_clone.d3plus.shape = "square"; + d_clone.d3plus.color = "#fff"; + // special case for top left corner + ret.push(d_clone) + } + + // be sure that this column is actually in this data item + if(d3.keys(d).indexOf(col) >= 0 && col in d){ + if(colors[col]){ + d_clone.d3plus.color = colors[col](d_clone[col]); + } + d_clone.d3plus.text = vars.format.value(d_clone[col]); + if(vars.data.keys[col] == "boolean"){ + d_clone.d3plus.label = false; + } + else if(vars.data.keys[col] == "string"){ + d_clone.d3plus.color = vars.color.missing; + d_clone.d3plus.stroke = "#fff"; + d_clone.d3plus.shape = "square"; + } + ret.push(d_clone) + } + }) + + }) + + return ret + +}; + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Visualization Settings and Helper Functions +//------------------------------------------------------------------------------ +table.shapes = ["check", "cross", "diamond", "square", "triangle", "triangle_up", "triangle_down"] +table.requirements = ["data", "cols"] + +module.exports = table + +},{"../../color/random.coffee":49,"../../core/fetch/value.coffee":69,"../../util/copy.coffee":210,"../../util/uniques.coffee":213}],335:[function(require,module,exports){ +var dataThreshold, groupData, mergeObject, tree_map; + +dataThreshold = require("../../core/data/threshold.js"); + +groupData = require("../../core/data/group.coffee"); + +mergeObject = require("../../object/merge.coffee"); + +tree_map = function(vars) { + var d, data, groupedData, i, len, returnData, root; + groupedData = groupData(vars, vars.data.viz); + data = d3.layout.treemap().mode(vars.type.mode.value).round(true).size([vars.width.viz, vars.height.viz]).children(function(d) { + return d.values; + }).padding(vars.data.padding.value).sort(function(a, b) { + var sizeDiff; + sizeDiff = a.value - b.value; + if (sizeDiff === 0) { + return a.id < b.id; + } else { + return sizeDiff; + } + }).nodes({ + name: "root", + values: groupedData + }).filter(function(d) { + return !d.values && d.area; + }); + if (data.length) { + root = data[0]; + while (root.parent) { + root = root.parent; + } + returnData = []; + for (i = 0, len = data.length; i < len; i++) { + d = data[i]; + d.d3plus.d3plus = mergeObject(d.d3plus.d3plus, { + x: d.x + d.dx / 2, + y: d.y + d.dy / 2, + width: d.dx, + height: d.dy, + share: d.value / root.value + }); + returnData.push(d.d3plus); + } + } + return returnData; +}; + +tree_map.filter = dataThreshold; + +tree_map.modes = ["squarify", "slice", "dice", "slice-dice"]; + +tree_map.requirements = ["data", "size"]; + +tree_map.shapes = ["square"]; + +tree_map.threshold = function(vars) { + return (40 * 40) / (vars.width.viz * vars.height.viz); +}; + +module.exports = tree_map; + + +},{"../../core/data/group.coffee":59,"../../core/data/threshold.js":63,"../../object/merge.coffee":174}],336:[function(require,module,exports){ +var attach, axis, container, flash, getSteps, print, validObject; + +attach = require("../core/methods/attach.coffee"); + +axis = require("./methods/helpers/axis.coffee"); + +flash = require("./helpers/ui/message.js"); + +getSteps = require("./helpers/drawSteps.js"); + +print = require("../core/console/print.coffee"); + +container = require("./helpers/container.coffee"); + +validObject = require("../object/validate.coffee"); + +module.exports = function() { + var vars; + vars = { + g: { + apps: {} + }, + types: { + area: require("./types/area.coffee"), + bar: require("./types/bar.coffee"), + bubbles: require("./types/bubbles.coffee"), + box: require("./types/box.coffee"), + chart: require("./types/deprecated/chart.coffee"), + geo_map: require("./types/geo_map.coffee"), + line: require("./types/line.coffee"), + network: require("./types/network.js"), + paths: require("./types/paths.coffee"), + pie: require("./types/pie.coffee"), + radar: require("./types/radar.coffee"), + rings: require("./types/rings.js"), + sankey: require("./types/sankey.coffee"), + scatter: require("./types/scatter.coffee"), + stacked: require("./types/area.coffee"), + table: require("./types/table.js"), + tree_map: require("./types/tree_map.coffee") + } + }; + vars.self = function(selection) { + selection.each(function() { + var lastMessage, nextStep, runFunction, runStep, small_height, small_width, steps; + vars.draw.frozen = true; + vars.error.internal = null; + if (!("timing" in vars.draw)) { + vars.draw.timing = vars.timing.transitions; + } + if (vars.error.value) { + vars.draw.timing = 0; + } + container(vars); + small_width = vars.width.value <= vars.width.small; + small_height = vars.height.value <= vars.height.small; + vars.small = small_width || small_height; + vars.width.viz = vars.width.value; + vars.height.viz = vars.height.value; + lastMessage = false; + nextStep = function() { + if (steps.length) { + runStep(); + } else { + if (vars.dev.value) { + print.groupEnd(); + print.timeEnd("total draw time"); + print.log("\n"); + } + } + }; + runFunction = function(step, name) { + name = name || "function"; + if (step[name] instanceof Array) { + step[name].forEach(function(f) { + f(vars, nextStep); + }); + } else { + if (typeof step[name] === "function") { + step[name](vars, nextStep); + } + } + if (!step.wait) { + nextStep(); + } + }; + runStep = function() { + var message, run, same, step; + step = steps.shift(); + same = vars.g.message && lastMessage === step.message; + run = "check" in step ? step.check : true; + if (typeof run === "function") { + run = run(vars); + } + if (run) { + if (!same) { + if (vars.dev.value) { + if (lastMessage !== false) { + print.groupEnd(); + } + print.group(step.message); + } + if (typeof vars.messages.value === "string") { + lastMessage = vars.messages.value; + message = vars.messages.value; + } else { + lastMessage = step.message; + message = vars.format.value(step.message); + } + if (vars.draw.update) { + flash(vars, message); + if (vars.error.value) { + runFunction(step); + } else { + setTimeout((function() { + return runFunction(step); + }), 10); + } + } else { + runFunction(step); + } + } else { + runFunction(step); + } + } else { + if ("otherwise" in step) { + if (vars.error.value) { + runFunction(step, "otherwise"); + } else { + setTimeout((function() { + return runFunction(step, "otherwise"); + }), 10); + } + } else { + nextStep(); + } + } + }; + vars.messages.style.backup = vars.group && vars.group.attr("opacity") === "1" ? "small" : "large"; + steps = getSteps(vars); + runStep(); + }); + return vars.self; + }; + attach(vars, { + active: require("./methods/active.coffee"), + aggs: require("./methods/aggs.coffee"), + attrs: require("./methods/attrs.coffee"), + axes: require("./methods/axes.coffee"), + background: require("./methods/background.coffee"), + "class": require("./methods/class.coffee"), + color: require("./methods/color.coffee"), + cols: require("./methods/cols.js"), + config: require("./methods/config.coffee"), + container: require("./methods/container.coffee"), + coords: require("./methods/coords.coffee"), + csv: require("./methods/csv.coffee"), + data: require("./methods/data.coffee"), + depth: require("./methods/depth.coffee"), + descs: require("./methods/descs.coffee"), + dev: require("./methods/dev.coffee"), + draw: require("./methods/draw.js"), + edges: require("./methods/edges.js"), + error: require("./methods/error.coffee"), + focus: require("./methods/focus.coffee"), + font: require("./methods/font.coffee"), + footer: require("./methods/footer.coffee"), + format: require("./methods/format.coffee"), + height: require("./methods/height.coffee"), + history: require("./methods/history.coffee"), + icon: require("./methods/icon.coffee"), + id: require("./methods/id.coffee"), + labels: require("./methods/labels.coffee"), + legend: require("./methods/legend.coffee"), + links: require("./methods/links.coffee"), + margin: require("./methods/margin.coffee"), + messages: require("./methods/messages.coffee"), + mouse: require("./methods/mouse.coffee"), + nodes: require("./methods/nodes.coffee"), + order: require("./methods/order.coffee"), + resize: require("./methods/resize.coffee"), + shape: require("./methods/shape.coffee"), + size: require("./methods/size.coffee"), + style: require("./methods/style.coffee"), + temp: require("./methods/temp.coffee"), + text: require("./methods/text.coffee"), + time: require("./methods/time.coffee"), + timeline: require("./methods/timeline.coffee"), + timing: require("./methods/timing.coffee"), + title: require("./methods/title.coffee"), + tooltip: require("./methods/tooltip.coffee"), + total: require("./methods/total.coffee"), + type: require("./methods/type.coffee"), + ui: require("./methods/ui.coffee"), + width: require("./methods/width.coffee"), + x: axis("x"), + x2: axis("x2"), + y: axis("y"), + y2: axis("y2"), + zoom: require("./methods/zoom.js") + }); + return vars.self; +}; + + +},{"../core/console/print.coffee":54,"../core/methods/attach.coffee":82,"../object/validate.coffee":175,"./helpers/container.coffee":214,"./helpers/drawSteps.js":215,"./helpers/ui/message.js":249,"./methods/active.coffee":258,"./methods/aggs.coffee":259,"./methods/attrs.coffee":260,"./methods/axes.coffee":261,"./methods/background.coffee":262,"./methods/class.coffee":263,"./methods/color.coffee":264,"./methods/cols.js":265,"./methods/config.coffee":266,"./methods/container.coffee":267,"./methods/coords.coffee":268,"./methods/csv.coffee":269,"./methods/data.coffee":270,"./methods/depth.coffee":271,"./methods/descs.coffee":272,"./methods/dev.coffee":273,"./methods/draw.js":274,"./methods/edges.js":275,"./methods/error.coffee":276,"./methods/focus.coffee":277,"./methods/font.coffee":278,"./methods/footer.coffee":279,"./methods/format.coffee":280,"./methods/height.coffee":281,"./methods/helpers/axis.coffee":282,"./methods/history.coffee":283,"./methods/icon.coffee":284,"./methods/id.coffee":285,"./methods/labels.coffee":286,"./methods/legend.coffee":287,"./methods/links.coffee":288,"./methods/margin.coffee":289,"./methods/messages.coffee":290,"./methods/mouse.coffee":291,"./methods/nodes.coffee":292,"./methods/order.coffee":293,"./methods/resize.coffee":294,"./methods/shape.coffee":295,"./methods/size.coffee":296,"./methods/style.coffee":297,"./methods/temp.coffee":298,"./methods/text.coffee":299,"./methods/time.coffee":300,"./methods/timeline.coffee":301,"./methods/timing.coffee":302,"./methods/title.coffee":303,"./methods/tooltip.coffee":304,"./methods/total.coffee":305,"./methods/type.coffee":306,"./methods/ui.coffee":307,"./methods/width.coffee":308,"./methods/zoom.js":309,"./types/area.coffee":310,"./types/bar.coffee":311,"./types/box.coffee":312,"./types/bubbles.coffee":313,"./types/deprecated/chart.coffee":314,"./types/geo_map.coffee":315,"./types/line.coffee":325,"./types/network.js":326,"./types/paths.coffee":327,"./types/pie.coffee":328,"./types/radar.coffee":329,"./types/rings.js":330,"./types/sankey.coffee":331,"./types/scatter.coffee":333,"./types/table.js":334,"./types/tree_map.coffee":335}]},{},[166,165]); diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/libs/d3plus/d3plus.full.min.js b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/libs/d3plus/d3plus.full.min.js new file mode 100644 index 0000000..ab70789 --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/libs/d3plus/d3plus.full.min.js @@ -0,0 +1,23 @@ +!function e(t,n,r){function a(o,l){if(!n[o]){if(!t[o]){var s="function"==typeof require&&require;if(!l&&s)return s(o,!0);if(i)return i(o,!0);var u=new Error("Cannot find module '"+o+"'");throw u.code="MODULE_NOT_FOUND",u}var c=n[o]={exports:{}};t[o][0].call(c.exports,function(e){var n=t[o][1][e];return a(n?n:e)},c,c.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o0)throw new Error("Invalid string. Length must be a multiple of 4");i="="===e[l-2]?2:"="===e[l-1]?1:0,o=new c(3*l/4-i),r=i>0?l-4:l;var s=0;for(t=0,n=0;t>16&255,o[s++]=a>>8&255,o[s++]=255&a;return 2===i?(a=u[e.charCodeAt(t)]<<2|u[e.charCodeAt(t+1)]>>4,o[s++]=255&a):1===i&&(a=u[e.charCodeAt(t)]<<10|u[e.charCodeAt(t+1)]<<4|u[e.charCodeAt(t+2)]>>2,o[s++]=a>>8&255,o[s++]=255&a),o}function i(e){return s[e>>18&63]+s[e>>12&63]+s[e>>6&63]+s[63&e]}function o(e,t,n){for(var r,a=[],o=t;oc?c:u+l));return 1===r?(t=e[n-1],a+=s[t>>2],a+=s[t<<4&63],a+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],a+=s[t>>10],a+=s[t>>4&63],a+=s[t<<2&63],a+="="),i.push(a),i.join("")}n.toByteArray=a,n.fromByteArray=l;var s=[],u=[],c="undefined"!=typeof Uint8Array?Uint8Array:Array;r()},{}],2:[function(e,t,n){(function(t){"use strict";function r(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}function a(){return o.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function i(e,t){if(a()=a())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a().toString(16)+" bytes");return 0|e}function g(e){return+e!=e&&(e=0),o.alloc(+e)}function m(e,t){if(o.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return H(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return Z(e).length;default:if(r)return H(e).length;t=(""+t).toLowerCase(),r=!0}}function y(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if(n>>>=0,t>>>=0,n<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return C(this,t,n);case"utf8":case"utf-8":return S(this,t,n);case"ascii":return N(this,t,n);case"latin1":case"binary":return F(this,t,n);case"base64":return E(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function x(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function b(e,t,n,r,a){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)return-1;n=0}if("string"==typeof t&&(t=o.from(t,r)),o.isBuffer(t))return 0===t.length?-1:w(e,t,n,r,a);if("number"==typeof t)return t=255&t,o.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):w(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function w(e,t,n,r,a){function i(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}var o=1,l=e.length,s=t.length;if(void 0!==r&&(r=String(r).toLowerCase(),"ucs2"===r||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,l/=2,s/=2,n/=2}var u;if(a){var c=-1;for(u=n;ul&&(n=l-s),u=n;u>=0;u--){for(var f=!0,d=0;da&&(r=a)):r=a;var i=t.length;if(i%2!==0)throw new TypeError("Invalid hex string");r>i/2&&(r=i/2);for(var o=0;o239?4:i>223?3:i>191?2:1;if(a+l<=n){var s,u,c,f;switch(l){case 1:i<128&&(o=i);break;case 2:s=e[a+1],128===(192&s)&&(f=(31&i)<<6|63&s,f>127&&(o=f));break;case 3:s=e[a+1],u=e[a+2],128===(192&s)&&128===(192&u)&&(f=(15&i)<<12|(63&s)<<6|63&u,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:s=e[a+1],u=e[a+2],c=e[a+3],128===(192&s)&&128===(192&u)&&128===(192&c)&&(f=(15&i)<<18|(63&s)<<12|(63&u)<<6|63&c,f>65535&&f<1114112&&(o=f))}}null===o?(o=65533,l=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|1023&o),r.push(o),a+=l}return O(r)}function O(e){var t=e.length;if(t<=ee)return String.fromCharCode.apply(String,e);for(var n="",r=0;rr)&&(n=r);for(var a="",i=t;in)throw new RangeError("Trying to access beyond buffer length")}function P(e,t,n,r,a,i){if(!o.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||te.length)throw new RangeError("Index out of range")}function B(e,t,n,r){t<0&&(t=65535+t+1);for(var a=0,i=Math.min(e.length-n,2);a>>8*(r?a:1-a)}function D(e,t,n,r){t<0&&(t=4294967295+t+1);for(var a=0,i=Math.min(e.length-n,4);a>>8*(r?a:3-a)&255}function R(e,t,n,r,a,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function I(e,t,n,r,a){return a||R(e,t,n,4,3.4028234663852886e38,-3.4028234663852886e38),K.write(e,t,n,r,23,4),n+4}function L(e,t,n,r,a){return a||R(e,t,n,8,1.7976931348623157e308,-1.7976931348623157e308),K.write(e,t,n,r,52,8),n+8}function V(e){if(e=U(e).replace(te,""),e.length<2)return"";for(;e.length%4!==0;)e+="=";return e}function U(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function Y(e){return e<16?"0"+e.toString(16):e.toString(16)}function H(e,t){t=t||1/0;for(var n,r=e.length,a=null,i=[],o=0;o55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&i.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),a=n;continue}n=(a-55296<<10|n-56320)+65536}else a&&(t-=3)>-1&&i.push(239,191,189);if(a=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function X(e){for(var t=[],n=0;n>8,a=n%256,i.push(a),i.push(r);return i}function Z(e){return Q.toByteArray(V(e))}function W(e,t,n,r){for(var a=0;a=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function J(e){return e!==e}var Q=e("base64-js"),K=e("ieee754"),$=e("isarray");n.Buffer=o,n.SlowBuffer=g,n.INSPECT_MAX_BYTES=50,o.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:r(),n.kMaxLength=a(),o.poolSize=8192,o._augment=function(e){return e.__proto__=o.prototype,e},o.from=function(e,t,n){return l(null,e,t,n)},o.TYPED_ARRAY_SUPPORT&&(o.prototype.__proto__=Uint8Array.prototype,o.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&o[Symbol.species]===o&&Object.defineProperty(o,Symbol.species,{value:null,configurable:!0})),o.alloc=function(e,t,n){return u(null,e,t,n)},o.allocUnsafe=function(e){return c(null,e)},o.allocUnsafeSlow=function(e){return c(null,e)},o.isBuffer=function(e){return!(null==e||!e._isBuffer)},o.compare=function(e,t){if(!o.isBuffer(e)||!o.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,a=0,i=Math.min(n,r);a0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},o.prototype.compare=function(e,t,n,r,a){if(!o.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,a>>>=0,this===e)return 0;for(var i=a-r,l=n-t,s=Math.min(i,l),u=this.slice(r,a),c=e.slice(t,n),f=0;fa)&&(n=a),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!1;;)switch(r){case"hex":return _(this,e,t,n);case"utf8":case"utf-8":return k(this,e,t,n);case"ascii":return z(this,e,t,n);case"latin1":case"binary":return M(this,e,t,n);case"base64":return A(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var ee=4096;o.prototype.slice=function(e,t){var n=this.length;e=~~e,t=void 0===t?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t0&&(a*=256);)r+=this[e+--t]*a;return r},o.prototype.readUInt8=function(e,t){return t||q(e,1,this.length),this[e]},o.prototype.readUInt16LE=function(e,t){return t||q(e,2,this.length),this[e]|this[e+1]<<8},o.prototype.readUInt16BE=function(e,t){return t||q(e,2,this.length),this[e]<<8|this[e+1]},o.prototype.readUInt32LE=function(e,t){return t||q(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},o.prototype.readUInt32BE=function(e,t){return t||q(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},o.prototype.readIntLE=function(e,t,n){e=0|e,t=0|t,n||q(e,t,this.length);for(var r=this[e],a=1,i=0;++i=a&&(r-=Math.pow(2,8*t)),r},o.prototype.readIntBE=function(e,t,n){e=0|e,t=0|t,n||q(e,t,this.length);for(var r=t,a=1,i=this[e+--r];r>0&&(a*=256);)i+=this[e+--r]*a;return a*=128,i>=a&&(i-=Math.pow(2,8*t)),i},o.prototype.readInt8=function(e,t){return t||q(e,1,this.length),128&this[e]?(255-this[e]+1)*-1:this[e]},o.prototype.readInt16LE=function(e,t){t||q(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},o.prototype.readInt16BE=function(e,t){t||q(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},o.prototype.readInt32LE=function(e,t){return t||q(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},o.prototype.readInt32BE=function(e,t){return t||q(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},o.prototype.readFloatLE=function(e,t){return t||q(e,4,this.length),K.read(this,e,!0,23,4)},o.prototype.readFloatBE=function(e,t){return t||q(e,4,this.length),K.read(this,e,!1,23,4)},o.prototype.readDoubleLE=function(e,t){return t||q(e,8,this.length),K.read(this,e,!0,52,8)},o.prototype.readDoubleBE=function(e,t){return t||q(e,8,this.length),K.read(this,e,!1,52,8)},o.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t=0|t,n=0|n,!r){var a=Math.pow(2,8*n)-1;P(this,e,t,n,a,0)}var i=1,o=0;for(this[t]=255&e;++o=0&&(o*=256);)this[t+i]=e/o&255;return t+n},o.prototype.writeUInt8=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,1,255,0),o.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},o.prototype.writeUInt16LE=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,2,65535,0),o.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):B(this,e,t,!0),t+2},o.prototype.writeUInt16BE=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,2,65535,0),o.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):B(this,e,t,!1),t+2},o.prototype.writeUInt32LE=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,4,4294967295,0),o.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):D(this,e,t,!0),t+4},o.prototype.writeUInt32BE=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,4,4294967295,0),o.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):D(this,e,t,!1),t+4},o.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t=0|t,!r){var a=Math.pow(2,8*n-1);P(this,e,t,n,a-1,-a)}var i=0,o=1,l=0;for(this[t]=255&e;++i>0)-l&255;return t+n},o.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t=0|t,!r){var a=Math.pow(2,8*n-1);P(this,e,t,n,a-1,-a)}var i=n-1,o=1,l=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===l&&0!==this[t+i+1]&&(l=1),this[t+i]=(e/o>>0)-l&255;return t+n},o.prototype.writeInt8=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,1,127,-128),o.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},o.prototype.writeInt16LE=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,2,32767,-32768),o.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):B(this,e,t,!0),t+2},o.prototype.writeInt16BE=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,2,32767,-32768),o.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):B(this,e,t,!1),t+2},o.prototype.writeInt32LE=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,4,2147483647,-2147483648),o.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):D(this,e,t,!0),t+4},o.prototype.writeInt32BE=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),o.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):D(this,e,t,!1),t+4},o.prototype.writeFloatLE=function(e,t,n){return I(this,e,t,!0,n)},o.prototype.writeFloatBE=function(e,t,n){return I(this,e,t,!1,n)},o.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},o.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},o.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--a)e[a+t]=this[a+n];else if(i<1e3||!o.TYPED_ARRAY_SUPPORT)for(a=0;a>>=0,n=void 0===n?this.length:n>>>0,e||(e=0);var i;if("number"==typeof e)for(i=t;it?1:e>=t?0:NaN}function a(e){return null===e?NaN:+e}function i(e){return!isNaN(e)}function o(e){return{left:function(t,n,r,a){for(arguments.length<3&&(r=0),arguments.length<4&&(a=t.length);r>>1;e(t[i],n)<0?r=i+1:a=i}return r},right:function(t,n,r,a){for(arguments.length<3&&(r=0),arguments.length<4&&(a=t.length);r>>1;e(t[i],n)>0?a=i:r=i+1}return r}}}function l(e){return e.length}function s(e){for(var t=1;e*t%1;)t*=10;return t}function u(e,t){for(var n in t)Object.defineProperty(e.prototype,n,{value:t[n],enumerable:!1})}function c(){this._=Object.create(null)}function f(e){return(e+="")===bo||e[0]===wo?wo+e:e}function d(e){return(e+="")[0]===wo?e.slice(1):e}function p(e){return f(e)in this._}function h(e){return(e=f(e))in this._&&delete this._[e]}function v(){var e=[];for(var t in this._)e.push(d(t));return e}function g(){var e=0;for(var t in this._)++e;return e}function m(){for(var e in this._)return!1;return!0}function y(){this._=Object.create(null)}function x(e){return e}function b(e,t,n){return function(){var r=n.apply(t,arguments);return r===t?e:r}}function w(e,t){if(t in e)return t;t=t.charAt(0).toUpperCase()+t.slice(1);for(var n=0,r=_o.length;n=t&&(t=a+1);!(o=l[t])&&++t0&&(e=e.slice(0,l));var u=No.get(e);return u&&(e=u,s=W),l?t?a:r:t?_:i}function Z(e,t){return function(n){var r=so.event;so.event=n,t[0]=this.__data__;try{e.apply(this,t)}finally{so.event=r}}}function W(e,t){var n=Z(e,t);return function(e){var t=this,r=e.relatedTarget;r&&(r===t||8&r.compareDocumentPosition(t))||n.call(t,e)}}function J(t){var r=".dragsuppress-"+ ++Co,a="click"+r,i=so.select(n(t)).on("touchmove"+r,M).on("dragstart"+r,M).on("selectstart"+r,M);if(null==Fo&&(Fo=!("onselectstart"in t)&&w(t.style,"userSelect")),Fo){var o=e(t).style,l=o[Fo];o[Fo]="none"}return function(e){if(i.on(r,null),Fo&&(o[Fo]=l),e){var t=function(){i.on(a,null)};i.on(a,function(){M(),t()},!0),setTimeout(t,0)}}}function Q(e,t){t.changedTouches&&(t=t.changedTouches[0]);var r=e.ownerSVGElement||e;if(r.createSVGPoint){var a=r.createSVGPoint();if(To<0){var i=n(e);if(i.scrollX||i.scrollY){r=so.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var o=r[0][0].getScreenCTM();To=!(o.f||o.e),r.remove()}}return To?(a.x=t.pageX,a.y=t.pageY):(a.x=t.clientX,a.y=t.clientY),a=a.matrixTransform(e.getScreenCTM().inverse()),[a.x,a.y]}var l=e.getBoundingClientRect();return[t.clientX-l.left-e.clientLeft,t.clientY-l.top-e.clientTop]}function K(){return so.event.changedTouches[0].identifier}function $(e){return e>0?1:e<0?-1:0}function ee(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function te(e){return e>1?0:e<-1?Bo:Math.acos(e)}function ne(e){return e>1?Io:e<-1?-Io:Math.asin(e)}function re(e){return((e=Math.exp(e))-1/e)/2}function ae(e){return((e=Math.exp(e))+1/e)/2}function ie(e){return((e=Math.exp(2*e))-1)/(e+1)}function oe(e){return(e=Math.sin(e/2))*e}function le(){}function se(e,t,n){return this instanceof se?(this.h=+e,this.s=+t,void(this.l=+n)):arguments.length<2?e instanceof se?new se(e.h,e.s,e.l):_e(""+e,ke,se):new se(e,t,n)}function ue(e,t,n){function r(e){return e>360?e-=360:e<0&&(e+=360),e<60?i+(o-i)*e/60:e<180?o:e<240?i+(o-i)*(240-e)/60:i}function a(e){return Math.round(255*r(e))}var i,o;return e=isNaN(e)?0:(e%=360)<0?e+360:e,t=isNaN(t)?0:t<0?0:t>1?1:t,n=n<0?0:n>1?1:n,o=n<=.5?n*(1+t):n+t-n*t,i=2*n-o,new ye(a(e+120),a(e),a(e-120))}function ce(e,t,n){return this instanceof ce?(this.h=+e,this.c=+t,void(this.l=+n)):arguments.length<2?e instanceof ce?new ce(e.h,e.c,e.l):e instanceof de?he(e.l,e.a,e.b):he((e=ze((e=so.rgb(e)).r,e.g,e.b)).l,e.a,e.b):new ce(e,t,n)}function fe(e,t,n){return isNaN(e)&&(e=0),isNaN(t)&&(t=0),new de(n,Math.cos(e*=Lo)*t,Math.sin(e)*t)}function de(e,t,n){return this instanceof de?(this.l=+e,this.a=+t,void(this.b=+n)):arguments.length<2?e instanceof de?new de(e.l,e.a,e.b):e instanceof ce?fe(e.h,e.c,e.l):ze((e=ye(e)).r,e.g,e.b):new de(e,t,n)}function pe(e,t,n){var r=(e+16)/116,a=r+t/500,i=r-n/200;return a=ve(a)*Ko,r=ve(r)*$o,i=ve(i)*el,new ye(me(3.2404542*a-1.5371385*r-.4985314*i),me(-.969266*a+1.8760108*r+.041556*i),me(.0556434*a-.2040259*r+1.0572252*i))}function he(e,t,n){return e>0?new ce(Math.atan2(n,t)*Vo,Math.sqrt(t*t+n*n),e):new ce(NaN,NaN,e)}function ve(e){return e>.206893034?e*e*e:(e-4/29)/7.787037}function ge(e){return e>.008856?Math.pow(e,1/3):7.787037*e+4/29}function me(e){return Math.round(255*(e<=.00304?12.92*e:1.055*Math.pow(e,1/2.4)-.055))}function ye(e,t,n){return this instanceof ye?(this.r=~~e,this.g=~~t,void(this.b=~~n)):arguments.length<2?e instanceof ye?new ye(e.r,e.g,e.b):_e(""+e,ye,ue):new ye(e,t,n)}function xe(e){return new ye(e>>16,e>>8&255,255&e)}function be(e){return xe(e)+""}function we(e){return e<16?"0"+Math.max(0,e).toString(16):Math.min(255,e).toString(16)}function _e(e,t,n){var r,a,i,o=0,l=0,s=0;if(r=/([a-z]+)\((.*)\)/.exec(e=e.toLowerCase()))switch(a=r[2].split(","),r[1]){case"hsl":return n(parseFloat(a[0]),parseFloat(a[1])/100,parseFloat(a[2])/100);case"rgb":return t(Ae(a[0]),Ae(a[1]),Ae(a[2]))}return(i=rl.get(e))?t(i.r,i.g,i.b):(null==e||"#"!==e.charAt(0)||isNaN(i=parseInt(e.slice(1),16))||(4===e.length?(o=(3840&i)>>4,o=o>>4|o,l=240&i,l=l>>4|l,s=15&i,s=s<<4|s):7===e.length&&(o=(16711680&i)>>16,l=(65280&i)>>8,s=255&i)),t(o,l,s))}function ke(e,t,n){var r,a,i=Math.min(e/=255,t/=255,n/=255),o=Math.max(e,t,n),l=o-i,s=(o+i)/2;return l?(a=s<.5?l/(o+i):l/(2-o-i),r=e==o?(t-n)/l+(t0&&s<1?0:r),new se(r,a,s)}function ze(e,t,n){e=Me(e),t=Me(t),n=Me(n);var r=ge((.4124564*e+.3575761*t+.1804375*n)/Ko),a=ge((.2126729*e+.7151522*t+.072175*n)/$o),i=ge((.0193339*e+.119192*t+.9503041*n)/el);return de(116*a-16,500*(r-a),200*(a-i))}function Me(e){return(e/=255)<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function Ae(e){var t=parseFloat(e);return"%"===e.charAt(e.length-1)?Math.round(2.55*t):t}function je(e){return"function"==typeof e?e:function(){return e}}function Ee(e){return function(t,n,r){return 2===arguments.length&&"function"==typeof n&&(r=n,n=null),Se(t,n,e,r)}}function Se(e,t,n,r){function a(){var e,t=s.status;if(!t&&Ne(s)||t>=200&&t<300||304===t){try{e=n.call(i,s)}catch(e){return void o.error.call(i,e)}o.load.call(i,e)}else o.error.call(i,s)}var i={},o=so.dispatch("beforesend","progress","load","error"),l={},s=new XMLHttpRequest,u=null; +return!this.XDomainRequest||"withCredentials"in s||!/^(http(s)?:)?\/\//.test(e)||(s=new XDomainRequest),"onload"in s?s.onload=s.onerror=a:s.onreadystatechange=function(){s.readyState>3&&a()},s.onprogress=function(e){var t=so.event;so.event=e;try{o.progress.call(i,s)}finally{so.event=t}},i.header=function(e,t){return e=(e+"").toLowerCase(),arguments.length<2?l[e]:(null==t?delete l[e]:l[e]=t+"",i)},i.mimeType=function(e){return arguments.length?(t=null==e?null:e+"",i):t},i.responseType=function(e){return arguments.length?(u=e,i):u},i.response=function(e){return n=e,i},["get","post"].forEach(function(e){i[e]=function(){return i.send.apply(i,[e].concat(co(arguments)))}}),i.send=function(n,r,a){if(2===arguments.length&&"function"==typeof r&&(a=r,r=null),s.open(n,e,!0),null==t||"accept"in l||(l.accept=t+",*/*"),s.setRequestHeader)for(var c in l)s.setRequestHeader(c,l[c]);return null!=t&&s.overrideMimeType&&s.overrideMimeType(t),null!=u&&(s.responseType=u),null!=a&&i.on("error",a).on("load",function(e){a(null,e)}),o.beforesend.call(i,s),s.send(null==r?null:r),i},i.abort=function(){return s.abort(),i},so.rebind(i,o,"on"),null==r?i:i.get(Oe(r))}function Oe(e){return 1===e.length?function(t,n){e(null==t?n:null)}:e}function Ne(e){var t=e.responseType;return t&&"text"!==t?e.response:e.responseText}function Fe(e,t,n){var r=arguments.length;r<2&&(t=0),r<3&&(n=Date.now());var a=n+t,i={c:e,t:a,n:null};return il?il.n=i:al=i,il=i,ol||(ll=clearTimeout(ll),ol=1,sl(Ce)),i}function Ce(){var e=Te(),t=qe()-e;t>24?(isFinite(t)&&(clearTimeout(ll),ll=setTimeout(Ce,t)),ol=0):(ol=1,sl(Ce))}function Te(){for(var e=Date.now(),t=al;t;)e>=t.t&&t.c(e-t.t)&&(t.c=null),t=t.n;return e}function qe(){for(var e,t=al,n=1/0;t;)t.c?(t.t8?function(e){return e/n}:function(e){return e*n},symbol:e}}function De(e){var t=e.decimal,n=e.thousands,r=e.grouping,a=e.currency,i=r&&n?function(e,t){for(var a=e.length,i=[],o=0,l=r[0],s=0;a>0&&l>0&&(s+l+1>t&&(l=Math.max(1,t-s)),i.push(e.substring(a-=l,a+l)),!((s+=l+1)>t));)l=r[o=(o+1)%r.length];return i.reverse().join(n)}:x;return function(e){var n=cl.exec(e),r=n[1]||" ",o=n[2]||">",l=n[3]||"-",s=n[4]||"",u=n[5],c=+n[6],f=n[7],d=n[8],p=n[9],h=1,v="",g="",m=!1,y=!0;switch(d&&(d=+d.substring(1)),(u||"0"===r&&"="===o)&&(u=r="0",o="="),p){case"n":f=!0,p="g";break;case"%":h=100,g="%",p="f";break;case"p":h=100,g="%",p="r";break;case"b":case"o":case"x":case"X":"#"===s&&(v="0"+p.toLowerCase());case"c":y=!1;case"d":m=!0,d=0;break;case"s":h=-1,p="r"}"$"===s&&(v=a[0],g=a[1]),"r"!=p||d||(p="g"),null!=d&&("g"==p?d=Math.max(1,Math.min(21,d)):"e"!=p&&"f"!=p||(d=Math.max(0,Math.min(20,d)))),p=fl.get(p)||Re;var x=u&&f;return function(e){var n=g;if(m&&e%1)return"";var a=e<0||0===e&&1/e<0?(e=-e,"-"):"-"===l?"":l;if(h<0){var s=so.formatPrefix(e,d);e=s.scale(e),n=s.symbol+g}else e*=h;e=p(e,d);var b,w,_=e.lastIndexOf(".");if(_<0){var k=y?e.lastIndexOf("e"):-1;k<0?(b=e,w=""):(b=e.substring(0,k),w=e.substring(k))}else b=e.substring(0,_),w=t+e.substring(_+1);!u&&f&&(b=i(b,1/0));var z=v.length+b.length+w.length+(x?0:a.length),M=z"===o?M+a+e:"^"===o?M.substring(0,z>>=1)+a+e+M.substring(z):a+(x?e:M+e))+n}}}function Re(e){return e+""}function Ie(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function Le(e,t,n){function r(t){var n=e(t),r=i(n,1);return t-n1)for(;o=u)return-1;if(a=t.charCodeAt(l++),37===a){if(o=t.charAt(l++),i=S[o in vl?t.charAt(l++):o],!i||(r=i(e,n,r))<0)return-1}else if(a!=n.charCodeAt(r++))return-1}return r}function r(e,t,n){_.lastIndex=0;var r=_.exec(t.slice(n));return r?(e.w=k.get(r[0].toLowerCase()),n+r[0].length):-1}function a(e,t,n){b.lastIndex=0;var r=b.exec(t.slice(n));return r?(e.w=w.get(r[0].toLowerCase()),n+r[0].length):-1}function i(e,t,n){A.lastIndex=0;var r=A.exec(t.slice(n));return r?(e.m=j.get(r[0].toLowerCase()),n+r[0].length):-1}function o(e,t,n){z.lastIndex=0;var r=z.exec(t.slice(n));return r?(e.m=M.get(r[0].toLowerCase()),n+r[0].length):-1}function l(e,t,r){return n(e,E.c.toString(),t,r)}function s(e,t,r){return n(e,E.x.toString(),t,r)}function u(e,t,r){return n(e,E.X.toString(),t,r)}function c(e,t,n){var r=x.get(t.slice(n,n+=2).toLowerCase());return null==r?-1:(e.p=r,n)}var f=e.dateTime,d=e.date,p=e.time,h=e.periods,v=e.days,g=e.shortDays,m=e.months,y=e.shortMonths;t.utc=function(e){function n(e){try{pl=Ie;var t=new pl;return t._=e,r(t)}finally{pl=Date}}var r=t(e);return n.parse=function(e){try{pl=Ie;var t=r.parse(e);return t&&t._}finally{pl=Date}},n.toString=r.toString,n},t.multi=t.utc.multi=ut;var x=so.map(),b=He(v),w=Xe(v),_=He(g),k=Xe(g),z=He(m),M=Xe(m),A=He(y),j=Xe(y);h.forEach(function(e,t){x.set(e.toLowerCase(),t)});var E={a:function(e){return g[e.getDay()]},A:function(e){return v[e.getDay()]},b:function(e){return y[e.getMonth()]},B:function(e){return m[e.getMonth()]},c:t(f),d:function(e,t){return Ye(e.getDate(),t,2)},e:function(e,t){return Ye(e.getDate(),t,2)},H:function(e,t){return Ye(e.getHours(),t,2)},I:function(e,t){return Ye(e.getHours()%12||12,t,2)},j:function(e,t){return Ye(1+dl.dayOfYear(e),t,3)},L:function(e,t){return Ye(e.getMilliseconds(),t,3)},m:function(e,t){return Ye(e.getMonth()+1,t,2)},M:function(e,t){return Ye(e.getMinutes(),t,2)},p:function(e){return h[+(e.getHours()>=12)]},S:function(e,t){return Ye(e.getSeconds(),t,2)},U:function(e,t){return Ye(dl.sundayOfYear(e),t,2)},w:function(e){return e.getDay()},W:function(e,t){return Ye(dl.mondayOfYear(e),t,2)},x:t(d),X:t(p),y:function(e,t){return Ye(e.getFullYear()%100,t,2)},Y:function(e,t){return Ye(e.getFullYear()%1e4,t,4)},Z:lt,"%":function(){return"%"}},S={a:r,A:a,b:i,B:o,c:l,d:tt,e:tt,H:rt,I:rt,j:nt,L:ot,m:et,M:at,p:c,S:it,U:Ze,w:Ge,W:We,x:s,X:u,y:Qe,Y:Je,Z:Ke,"%":st};return t}function Ye(e,t,n){var r=e<0?"-":"",a=(r?-e:e)+"",i=a.length;return r+(i68?1900:2e3)}function et(e,t,n){gl.lastIndex=0;var r=gl.exec(t.slice(n,n+2));return r?(e.m=r[0]-1,n+r[0].length):-1}function tt(e,t,n){gl.lastIndex=0;var r=gl.exec(t.slice(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function nt(e,t,n){gl.lastIndex=0;var r=gl.exec(t.slice(n,n+3));return r?(e.j=+r[0],n+r[0].length):-1}function rt(e,t,n){gl.lastIndex=0;var r=gl.exec(t.slice(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function at(e,t,n){gl.lastIndex=0;var r=gl.exec(t.slice(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function it(e,t,n){gl.lastIndex=0;var r=gl.exec(t.slice(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function ot(e,t,n){gl.lastIndex=0;var r=gl.exec(t.slice(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function lt(e){var t=e.getTimezoneOffset(),n=t>0?"-":"+",r=xo(t)/60|0,a=xo(t)%60;return n+Ye(r,"0",2)+Ye(a,"0",2)}function st(e,t,n){ml.lastIndex=0;var r=ml.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function ut(e){for(var t=e.length,n=-1;++n=0?1:-1,l=o*n,s=Math.cos(t),u=Math.sin(t),c=i*u,f=a*s+c*Math.cos(l),d=c*o*Math.sin(l);kl.add(Math.atan2(d,f)),r=e,a=s,i=u}var t,n,r,a,i;zl.point=function(o,l){zl.point=e,r=(t=o)*Lo,a=Math.cos(l=(n=l)*Lo/2+Bo/4),i=Math.sin(l)},zl.lineEnd=function(){e(t,n)}}function gt(e){var t=e[0],n=e[1],r=Math.cos(n);return[r*Math.cos(t),r*Math.sin(t),Math.sin(n)]}function mt(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function yt(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function xt(e,t){e[0]+=t[0],e[1]+=t[1],e[2]+=t[2]}function bt(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function wt(e){var t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t,e[1]/=t,e[2]/=t}function _t(e){return[Math.atan2(e[1],e[0]),ne(e[2])]}function kt(e,t){return xo(e[0]-t[0])=0;--l)a.point((f=c[l])[0],f[1])}else r(p.x,p.p.x,-1,a);p=p.p}p=p.o,c=p.z,h=!h}while(!p.v);a.lineEnd()}}}function Ft(e){if(t=e.length){for(var t,n,r=0,a=e[0];++r0){for(w||(i.polygonStart(),w=!0),i.lineStart();++o1&&2&t&&n.push(n.pop().concat(n.shift())),p.push(n.filter(qt))}var p,h,v,g=t(i),m=a.invert(r[0],r[1]),y={point:o,lineStart:s,lineEnd:u,polygonStart:function(){y.point=c,y.lineStart=f,y.lineEnd=d,p=[],h=[]},polygonEnd:function(){y.point=o,y.lineStart=s,y.lineEnd=u,p=so.merge(p);var e=Lt(m,h);p.length?(w||(i.polygonStart(),w=!0),Nt(p,Bt,e,n,i)):e&&(w||(i.polygonStart(),w=!0),i.lineStart(),n(null,null,1,i),i.lineEnd()),w&&(i.polygonEnd(),w=!1),p=h=null},sphere:function(){i.polygonStart(),i.lineStart(),n(null,null,1,i),i.lineEnd(),i.polygonEnd()}},x=Pt(),b=t(x),w=!1;return y}}function qt(e){return e.length>1}function Pt(){var e,t=[];return{lineStart:function(){t.push(e=[])},point:function(t,n){e.push([t,n])},lineEnd:_,buffer:function(){var n=t;return t=[],e=null,n},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function Bt(e,t){return((e=e.x)[0]<0?e[1]-Io-qo:Io-e[1])-((t=t.x)[0]<0?t[1]-Io-qo:Io-t[1])}function Dt(e){var t,n=NaN,r=NaN,a=NaN;return{lineStart:function(){e.lineStart(),t=1},point:function(i,o){var l=i>0?Bo:-Bo,s=xo(i-n);xo(s-Bo)0?Io:-Io),e.point(a,r),e.lineEnd(),e.lineStart(),e.point(l,r),e.point(i,r),t=0):a!==l&&s>=Bo&&(xo(n-a)qo?Math.atan((Math.sin(t)*(i=Math.cos(r))*Math.sin(n)-Math.sin(r)*(a=Math.cos(t))*Math.sin(e))/(a*i*o)):(t+r)/2}function It(e,t,n,r){var a;if(null==e)a=n*Io,r.point(-Bo,a),r.point(0,a),r.point(Bo,a),r.point(Bo,0),r.point(Bo,-a),r.point(0,-a),r.point(-Bo,-a),r.point(-Bo,0),r.point(-Bo,a);else if(xo(e[0]-t[0])>qo){var i=e[0]=0?1:-1,k=_*w,z=k>Bo,M=h*x;if(kl.add(Math.atan2(M*_*Math.sin(k),v*b+M*Math.cos(k))),i+=z?w+_*Do:w,z^d>=n^m>=n){var A=yt(gt(f),gt(e));wt(A);var j=yt(a,A);wt(j);var E=(z^w>=0?-1:1)*ne(j[2]);(r>E||r===E&&(A[0]||A[1]))&&(o+=z^w>=0?1:-1)}if(!g++)break;d=m,h=x,v=b,f=e}}return(i<-qo||ii}function n(e){var n,i,s,u,c;return{lineStart:function(){u=s=!1,c=1},point:function(f,d){var p,h=[f,d],v=t(f,d),g=o?v?0:a(f,d):v?a(f+(f<0?Bo:-Bo),d):0;if(!n&&(u=s=v)&&e.lineStart(),v!==s&&(p=r(n,h),(kt(n,p)||kt(h,p))&&(h[0]+=qo,h[1]+=qo,v=t(h[0],h[1]))),v!==s)c=0,v?(e.lineStart(),p=r(h,n),e.point(p[0],p[1])):(p=r(n,h),e.point(p[0],p[1]),e.lineEnd()),n=p;else if(l&&n&&o^v){var m;g&i||!(m=r(h,n,!0))||(c=0,o?(e.lineStart(),e.point(m[0][0],m[0][1]),e.point(m[1][0],m[1][1]),e.lineEnd()):(e.point(m[1][0],m[1][1]),e.lineEnd(),e.lineStart(),e.point(m[0][0],m[0][1])))}!v||n&&kt(n,h)||e.point(h[0],h[1]),n=h,s=v,i=g},lineEnd:function(){s&&e.lineEnd(),n=null},clean:function(){return c|(u&&s)<<1}}}function r(e,t,n){var r=gt(e),a=gt(t),o=[1,0,0],l=yt(r,a),s=mt(l,l),u=l[0],c=s-u*u;if(!c)return!n&&e;var f=i*s/c,d=-i*u/c,p=yt(o,l),h=bt(o,f),v=bt(l,d);xt(h,v);var g=p,m=mt(h,g),y=mt(g,g),x=m*m-y*(mt(h,h)-1);if(!(x<0)){var b=Math.sqrt(x),w=bt(g,(-m-b)/y);if(xt(w,h),w=_t(w),!n)return w;var _,k=e[0],z=t[0],M=e[1],A=t[1];z0^w[1]<(xo(w[0]-k)Bo^(k<=w[0]&&w[0]<=z)){var O=bt(g,(-m+b)/y);return xt(O,h),[w,_t(O)]}}}function a(t,n){var r=o?e:Bo-e,a=0;return t<-r?a|=1:t>r&&(a|=2),n<-r?a|=4:n>r&&(a|=8),a}var i=Math.cos(e),o=i>0,l=xo(i)>qo,s=gn(e,6*Lo);return Tt(t,n,s,o?[0,-e]:[-Bo,e-Bo])}function Ut(e,t,n,r){return function(a){var i,o=a.a,l=a.b,s=o.x,u=o.y,c=l.x,f=l.y,d=0,p=1,h=c-s,v=f-u;if(i=e-s,h||!(i>0)){if(i/=h,h<0){if(i0){if(i>p)return;i>d&&(d=i)}if(i=n-s,h||!(i<0)){if(i/=h,h<0){if(i>p)return;i>d&&(d=i)}else if(h>0){if(i0)){if(i/=v,v<0){if(i0){if(i>p)return;i>d&&(d=i)}if(i=r-u,v||!(i<0)){if(i/=v,v<0){if(i>p)return;i>d&&(d=i)}else if(v>0){if(i0&&(a.a={x:s+d*h,y:u+d*v}),p<1&&(a.b={x:s+p*h,y:u+p*v}),a}}}}}}function Yt(e,t,n,r){function a(r,a){return xo(r[0]-e)0?0:3:xo(r[0]-n)0?2:1:xo(r[1]-t)0?1:0:a>0?3:2}function i(e,t){return o(e.x,t.x)}function o(e,t){var n=a(e,1),r=a(t,1);return n!==r?n-r:0===n?t[1]-e[1]:1===n?e[0]-t[0]:2===n?e[1]-t[1]:t[0]-e[0]}return function(l){function s(e){for(var t=0,n=g.length,r=e[1],a=0;ar&&ee(u,i,e)>0&&++t:i[1]<=r&&ee(u,i,e)<0&&--t,u=i;return 0!==t}function u(i,l,s,u){var c=0,f=0;if(null==i||(c=a(i,s))!==(f=a(l,s))||o(i,l)<0^s>0){do u.point(0===c||3===c?e:n,c>1?r:t);while((c=(c+s+4)%4)!==f)}else u.point(l[0],l[1])}function c(a,i){return e<=a&&a<=n&&t<=i&&i<=r}function f(e,t){c(e,t)&&l.point(e,t)}function d(){S.point=h,g&&g.push(m=[]),z=!0,k=!1,w=_=NaN}function p(){v&&(h(y,x),b&&k&&j.rejoin(),v.push(j.buffer())),S.point=f,k&&l.lineEnd()}function h(e,t){e=Math.max(-Dl,Math.min(Dl,e)),t=Math.max(-Dl,Math.min(Dl,t));var n=c(e,t);if(g&&m.push([e,t]),z)y=e,x=t,b=n,z=!1,n&&(l.lineStart(),l.point(e,t));else if(n&&k)l.point(e,t);else{var r={a:{x:w,y:_},b:{x:e,y:t}};E(r)?(k||(l.lineStart(),l.point(r.a.x,r.a.y)),l.point(r.b.x,r.b.y),n||l.lineEnd(),M=!1):n&&(l.lineStart(),l.point(e,t),M=!1)}w=e,_=t,k=n}var v,g,m,y,x,b,w,_,k,z,M,A=l,j=Pt(),E=Ut(e,t,n,r),S={point:f,lineStart:d,lineEnd:p,polygonStart:function(){l=j,v=[],g=[],M=!0},polygonEnd:function(){l=A,v=so.merge(v);var t=s([e,r]),n=M&&t,a=v.length;(n||a)&&(l.polygonStart(),n&&(l.lineStart(),u(null,null,1,l),l.lineEnd()),a&&Nt(v,i,t,u,l),l.polygonEnd()),v=g=m=null}};return S}}function Ht(e){var t=0,n=Bo/3,r=sn(e),a=r(t,n);return a.parallels=function(e){return arguments.length?r(t=e[0]*Bo/180,n=e[1]*Bo/180):[t/Bo*180,n/Bo*180]},a}function Xt(e,t){function n(e,t){var n=Math.sqrt(i-2*a*Math.sin(t))/a;return[n*Math.sin(e*=a),o-n*Math.cos(e)]}var r=Math.sin(e),a=(r+Math.sin(t))/2,i=1+r*(2*a-r),o=Math.sqrt(i)/a;return n.invert=function(e,t){var n=o-t;return[Math.atan2(e,n)/a,ne((i-(e*e+n*n)*a*a)/(2*a))]},n}function Gt(){function e(e,t){Il+=a*e-r*t,r=e,a=t}var t,n,r,a;Hl.point=function(i,o){Hl.point=e,t=r=i,n=a=o},Hl.lineEnd=function(){e(t,n)}}function Zt(e,t){eUl&&(Ul=e),tYl&&(Yl=t)}function Wt(){function e(e,t){o.push("M",e,",",t,i)}function t(e,t){o.push("M",e,",",t),l.point=n}function n(e,t){o.push("L",e,",",t)}function r(){l.point=e}function a(){o.push("Z")}var i=Jt(4.5),o=[],l={point:e,lineStart:function(){l.point=t},lineEnd:r,polygonStart:function(){l.lineEnd=a},polygonEnd:function(){l.lineEnd=r,l.point=e},pointRadius:function(e){return i=Jt(e),l},result:function(){if(o.length){var e=o.join("");return o=[],e}}};return l}function Jt(e){return"m0,"+e+"a"+e+","+e+" 0 1,1 0,"+-2*e+"a"+e+","+e+" 0 1,1 0,"+2*e+"z"}function Qt(e,t){jl+=e,El+=t,++Sl}function Kt(){function e(e,r){var a=e-t,i=r-n,o=Math.sqrt(a*a+i*i);Ol+=o*(t+e)/2,Nl+=o*(n+r)/2,Fl+=o,Qt(t=e,n=r)}var t,n;Gl.point=function(r,a){Gl.point=e,Qt(t=r,n=a)}}function $t(){Gl.point=Qt}function en(){function e(e,t){var n=e-r,i=t-a,o=Math.sqrt(n*n+i*i);Ol+=o*(r+e)/2,Nl+=o*(a+t)/2,Fl+=o,o=a*e-r*t,Cl+=o*(r+e),Tl+=o*(a+t),ql+=3*o,Qt(r=e,a=t)}var t,n,r,a;Gl.point=function(i,o){Gl.point=e,Qt(t=r=i,n=a=o)},Gl.lineEnd=function(){e(t,n)}}function tn(e){function t(t,n){e.moveTo(t+o,n),e.arc(t,n,o,0,Do)}function n(t,n){e.moveTo(t,n),l.point=r}function r(t,n){e.lineTo(t,n)}function a(){l.point=t}function i(){e.closePath()}var o=4.5,l={point:t,lineStart:function(){l.point=n},lineEnd:a,polygonStart:function(){l.lineEnd=i},polygonEnd:function(){l.lineEnd=a,l.point=t},pointRadius:function(e){return o=e,l},result:_};return l}function nn(e){function t(e){return(l?r:n)(e)}function n(t){return on(t,function(n,r){n=e(n,r),t.point(n[0],n[1])})}function r(t){function n(n,r){n=e(n,r),t.point(n[0],n[1])}function r(){x=NaN,z.point=i,t.lineStart()}function i(n,r){var i=gt([n,r]),o=e(n,r);a(x,b,y,w,_,k,x=o[0],b=o[1],y=n,w=i[0],_=i[1],k=i[2],l,t),t.point(x,b)}function o(){z.point=n,t.lineEnd()}function s(){r(),z.point=u,z.lineEnd=c}function u(e,t){i(f=e,d=t),p=x,h=b,v=w,g=_,m=k,z.point=i}function c(){a(x,b,y,w,_,k,p,h,f,v,g,m,l,t),z.lineEnd=o,o()}var f,d,p,h,v,g,m,y,x,b,w,_,k,z={point:n,lineStart:r,lineEnd:o,polygonStart:function(){t.polygonStart(),z.lineStart=s},polygonEnd:function(){t.polygonEnd(),z.lineStart=r}};return z}function a(t,n,r,l,s,u,c,f,d,p,h,v,g,m){var y=c-t,x=f-n,b=y*y+x*x;if(b>4*i&&g--){var w=l+p,_=s+h,k=u+v,z=Math.sqrt(w*w+_*_+k*k),M=Math.asin(k/=z),A=xo(xo(k)-1)i||xo((y*O+x*N)/b-.5)>.3||l*p+s*h+u*v0&&16,t):Math.sqrt(i)},t}function rn(e){var t=nn(function(t,n){return e([t*Vo,n*Vo])});return function(e){return un(t(e))}}function an(e){this.stream=e}function on(e,t){return{point:t,sphere:function(){e.sphere()},lineStart:function(){e.lineStart()},lineEnd:function(){e.lineEnd()},polygonStart:function(){e.polygonStart()},polygonEnd:function(){e.polygonEnd()}}}function ln(e){return sn(function(){return e})()}function sn(e){function t(e){return e=l(e[0]*Lo,e[1]*Lo),[e[0]*d+s,u-e[1]*d]}function n(e){return e=l.invert((e[0]-s)/d,(u-e[1])/d),e&&[e[0]*Vo,e[1]*Vo]}function r(){l=St(o=dn(m,y,b),i);var e=i(v,g);return s=p-e[0]*d,u=h+e[1]*d,a()}function a(){return c&&(c.valid=!1,c=null),t}var i,o,l,s,u,c,f=nn(function(e,t){return e=i(e,t),[e[0]*d+s,u-e[1]*d]}),d=150,p=480,h=250,v=0,g=0,m=0,y=0,b=0,w=Bl,_=x,k=null,z=null;return t.stream=function(e){return c&&(c.valid=!1),c=un(w(o,f(_(e)))),c.valid=!0,c},t.clipAngle=function(e){return arguments.length?(w=null==e?(k=e,Bl):Vt((k=+e)*Lo),a()):k},t.clipExtent=function(e){return arguments.length?(z=e,_=e?Yt(e[0][0],e[0][1],e[1][0],e[1][1]):x,a()):z},t.scale=function(e){return arguments.length?(d=+e,r()):d},t.translate=function(e){return arguments.length?(p=+e[0],h=+e[1],r()):[p,h]},t.center=function(e){return arguments.length?(v=e[0]%360*Lo,g=e[1]%360*Lo,r()):[v*Vo,g*Vo]},t.rotate=function(e){return arguments.length?(m=e[0]%360*Lo,y=e[1]%360*Lo,b=e.length>2?e[2]%360*Lo:0,r()):[m*Vo,y*Vo,b*Vo]},so.rebind(t,f,"precision"),function(){return i=e.apply(this,arguments),t.invert=i.invert&&n,r()}}function un(e){return on(e,function(t,n){e.point(t*Lo,n*Lo)})}function cn(e,t){return[e,t]}function fn(e,t){return[e>Bo?e-Do:e<-Bo?e+Do:e,t]}function dn(e,t,n){return e?t||n?St(hn(e),vn(t,n)):hn(e):t||n?vn(t,n):fn}function pn(e){return function(t,n){return t+=e,[t>Bo?t-Do:t<-Bo?t+Do:t,n]}}function hn(e){var t=pn(e);return t.invert=pn(-e),t}function vn(e,t){function n(e,t){var n=Math.cos(t),l=Math.cos(e)*n,s=Math.sin(e)*n,u=Math.sin(t),c=u*r+l*a;return[Math.atan2(s*i-c*o,l*r-u*a),ne(c*i+s*o)]}var r=Math.cos(e),a=Math.sin(e),i=Math.cos(t),o=Math.sin(t);return n.invert=function(e,t){var n=Math.cos(t),l=Math.cos(e)*n,s=Math.sin(e)*n,u=Math.sin(t),c=u*i-s*o;return[Math.atan2(s*i+u*o,l*r+c*a),ne(c*r-l*a)]},n}function gn(e,t){var n=Math.cos(e),r=Math.sin(e);return function(a,i,o,l){var s=o*t;null!=a?(a=mn(n,a),i=mn(n,i),(o>0?ai)&&(a+=o*Do)):(a=e+o*Do,i=e-.5*s);for(var u,c=a;o>0?c>i:c0?t<-Io+qo&&(t=-Io+qo):t>Io-qo&&(t=Io-qo);var n=o/Math.pow(a(t),i);return[n*Math.sin(i*e),o-n*Math.cos(i*e)]}var r=Math.cos(e),a=function(e){return Math.tan(Bo/4+e/2)},i=e===t?Math.sin(e):Math.log(r/Math.cos(t))/Math.log(a(t)/a(e)),o=r*Math.pow(a(e),i)/i;return i?(n.invert=function(e,t){var n=o-t,r=$(i)*Math.sqrt(e*e+n*n);return[Math.atan2(e,n)/i,2*Math.atan(Math.pow(o/r,1/i))-Io]},n):jn}function An(e,t){function n(e,t){var n=i-t;return[n*Math.sin(a*e),i-n*Math.cos(a*e)]}var r=Math.cos(e),a=e===t?Math.sin(e):(r-Math.cos(t))/(t-e),i=r/a+e;return xo(a)1&&ee(e[n[r-2]],e[n[r-1]],e[a])<=0;)--r;n[r++]=a}return n.slice(0,r)}function Cn(e,t){return e[0]-t[0]||e[1]-t[1]}function Tn(e,t,n){return(n[0]-t[0])*(e[1]-t[1])<(n[1]-t[1])*(e[0]-t[0])}function qn(e,t,n,r){var a=e[0],i=n[0],o=t[0]-a,l=r[0]-i,s=e[1],u=n[1],c=t[1]-s,f=r[1]-u,d=(l*(s-u)-f*(a-i))/(f*o-l*c);return[a+d*o,s+d*c]}function Pn(e){var t=e[0],n=e[e.length-1];return!(t[0]-n[0]||t[1]-n[1])}function Bn(){ar(this),this.edge=this.site=this.circle=null}function Dn(e){var t=ls.pop()||new Bn;return t.site=e,t}function Rn(e){Wn(e),as.remove(e),ls.push(e),ar(e)}function In(e){var t=e.circle,n=t.x,r=t.cy,a={x:n,y:r},i=e.P,o=e.N,l=[e];Rn(e);for(var s=i;s.circle&&xo(n-s.circle.x)qo)l=l.L;else{if(a=i-Un(l,o),!(a>qo)){r>-qo?(t=l.P,n=l):a>-qo?(t=l,n=l.N):t=n=l;break}if(!l.R){t=l;break}l=l.R}var s=Dn(e);if(as.insert(t,s),t||n){if(t===n)return Wn(t),n=Dn(t.site),as.insert(s,n),s.edge=n.edge=$n(t.site,s.site),Zn(t),void Zn(n);if(!n)return void(s.edge=$n(t.site,s.site));Wn(t),Wn(n);var u=t.site,c=u.x,f=u.y,d=e.x-c,p=e.y-f,h=n.site,v=h.x-c,g=h.y-f,m=2*(d*g-p*v),y=d*d+p*p,x=v*v+g*g,b={x:(g*y-p*x)/m+c,y:(d*x-v*y)/m+f};tr(n.edge,u,h,b),s.edge=$n(u,e,null,b),n.edge=$n(e,h,null,b),Zn(t),Zn(n)}}function Vn(e,t){var n=e.site,r=n.x,a=n.y,i=a-t;if(!i)return r;var o=e.P;if(!o)return-(1/0);n=o.site;var l=n.x,s=n.y,u=s-t;if(!u)return l;var c=l-r,f=1/i-1/u,d=c/u;return f?(-d+Math.sqrt(d*d-2*f*(c*c/(-2*u)-s+u/2+a-i/2)))/f+r:(r+l)/2}function Un(e,t){var n=e.N;if(n)return Vn(n,t);var r=e.site;return r.y===t?r.x:1/0}function Yn(e){this.site=e,this.edges=[]}function Hn(e){for(var t,n,r,a,i,o,l,s,u,c,f=e[0][0],d=e[1][0],p=e[0][1],h=e[1][1],v=rs,g=v.length;g--;)if(i=v[g],i&&i.prepare())for(l=i.edges,s=l.length,o=0;oqo||xo(a-n)>qo)&&(l.splice(o,0,new nr(er(i.site,c,xo(r-f)qo?{x:f,y:xo(t-f)qo?{x:xo(n-h)qo?{x:d,y:xo(t-d)qo?{x:xo(n-p)=-Po)){var p=s*s+u*u,h=c*c+f*f,v=(f*p-u*h)/d,g=(s*h-c*p)/d,f=g+l,m=ss.pop()||new Gn;m.arc=e,m.site=a,m.x=v+o,m.y=f+Math.sqrt(v*v+g*g),m.cy=f,e.circle=m;for(var y=null,x=os._;x;)if(m.y=l)return;if(d>h){if(i){if(i.y>=u)return}else i={x:g,y:s};n={x:g,y:u}}else{if(i){if(i.y1)if(d>h){if(i){if(i.y>=u)return}else i={x:(s-a)/r,y:s};n={x:(u-a)/r,y:u}}else{if(i){if(i.y=l)return}else i={x:o,y:r*o+a};n={x:l,y:r*l+a}}else{if(i){if(i.xi||f>o||d=b,k=n>=w,z=k<<1|_,M=z+4;zi&&(a=t.slice(i,a),l[o]?l[o]+=a:l[++o]=a),(n=n[0])===(r=r[0])?l[o]?l[o]+=r:l[++o]=r:(l[++o]=null,s.push({i:o,x:yr(n,r)})),i=fs.lastIndex;return i=0&&!(n=so.interpolators[r](e,t)););return n}function wr(e,t){var n,r=[],a=[],i=e.length,o=t.length,l=Math.min(e.length,t.length);for(n=0;n=1?1:e(t)}}function kr(e){return function(t){return 1-e(1-t)}}function zr(e){return function(t){return.5*(t<.5?e(2*t):2-e(2-2*t))}}function Mr(e){return e*e}function Ar(e){return e*e*e}function jr(e){if(e<=0)return 0;if(e>=1)return 1;var t=e*e,n=t*e;return 4*(e<.5?n:3*(e-t)+n-.75)}function Er(e){return function(t){return Math.pow(t,e)}}function Sr(e){return 1-Math.cos(e*Io)}function Or(e){return Math.pow(2,10*(e-1))}function Nr(e){return 1-Math.sqrt(1-e*e)}function Fr(e,t){var n;return arguments.length<2&&(t=.45),arguments.length?n=t/Do*Math.asin(1/e):(e=1,n=t/4),function(r){return 1+e*Math.pow(2,-10*r)*Math.sin((r-n)*Do/t)}}function Cr(e){return e||(e=1.70158),function(t){return t*t*((e+1)*t-e)}}function Tr(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375}function qr(e,t){e=so.hcl(e),t=so.hcl(t);var n=e.h,r=e.c,a=e.l,i=t.h-n,o=t.c-r,l=t.l-a;return isNaN(o)&&(o=0,r=isNaN(r)?t.c:r),isNaN(i)?(i=0,n=isNaN(n)?t.h:n):i>180?i-=360:i<-180&&(i+=360),function(e){return fe(n+i*e,r+o*e,a+l*e)+""}}function Pr(e,t){e=so.hsl(e),t=so.hsl(t);var n=e.h,r=e.s,a=e.l,i=t.h-n,o=t.s-r,l=t.l-a;return isNaN(o)&&(o=0,r=isNaN(r)?t.s:r),isNaN(i)?(i=0,n=isNaN(n)?t.h:n):i>180?i-=360:i<-180&&(i+=360),function(e){return ue(n+i*e,r+o*e,a+l*e)+""}}function Br(e,t){e=so.lab(e),t=so.lab(t);var n=e.l,r=e.a,a=e.b,i=t.l-n,o=t.a-r,l=t.b-a;return function(e){return pe(n+i*e,r+o*e,a+l*e)+""}}function Dr(e,t){return t-=e,function(n){return Math.round(e+t*n)}}function Rr(e){var t=[e.a,e.b],n=[e.c,e.d],r=Lr(t),a=Ir(t,n),i=Lr(Vr(n,t,-a))||0;t[0]*n[1]180?t+=360:t-e>180&&(e+=360),r.push({i:n.push(Ur(n)+"rotate(",null,")")-2,x:yr(e,t)})):t&&n.push(Ur(n)+"rotate("+t+")")}function Xr(e,t,n,r){e!==t?r.push({i:n.push(Ur(n)+"skewX(",null,")")-2,x:yr(e,t)}):t&&n.push(Ur(n)+"skewX("+t+")")}function Gr(e,t,n,r){if(e[0]!==t[0]||e[1]!==t[1]){var a=n.push(Ur(n)+"scale(",null,",",null,")");r.push({i:a-4,x:yr(e[0],t[0])},{i:a-2,x:yr(e[1],t[1])})}else 1===t[0]&&1===t[1]||n.push(Ur(n)+"scale("+t+")")}function Zr(e,t){var n=[],r=[];return e=so.transform(e),t=so.transform(t),Yr(e.translate,t.translate,n,r),Hr(e.rotate,t.rotate,n,r),Xr(e.skew,t.skew,n,r),Gr(e.scale,t.scale,n,r),e=t=null,function(e){for(var t,a=-1,i=r.length;++a=0;)n.push(a[r])}function la(e,t){for(var n=[e],r=[];null!=(e=n.pop());)if(r.push(e),(i=e.children)&&(a=i.length))for(var a,i,o=-1;++oa&&(r=n,a=t);return r}function ya(e){return e.reduce(xa,0)}function xa(e,t){return e+t[1]}function ba(e,t){return wa(e,Math.ceil(Math.log(t.length)/Math.LN2+1))}function wa(e,t){for(var n=-1,r=+e[0],a=(e[1]-r)/t,i=[];++n<=t;)i[n]=a*n+r;return i}function _a(e){return[so.min(e),so.max(e)]}function ka(e,t){return e.value-t.value}function za(e,t){var n=e._pack_next;e._pack_next=t,t._pack_prev=e,t._pack_next=n,n._pack_prev=t}function Ma(e,t){e._pack_next=t,t._pack_prev=e}function Aa(e,t){var n=t.x-e.x,r=t.y-e.y,a=e.r+t.r;return.999*a*a>n*n+r*r}function ja(e){function t(e){c=Math.min(e.x-e.r,c),f=Math.max(e.x+e.r,f),d=Math.min(e.y-e.r,d),p=Math.max(e.y+e.r,p)}if((n=e.children)&&(u=n.length)){var n,r,a,i,o,l,s,u,c=1/0,f=-(1/0),d=1/0,p=-(1/0);if(n.forEach(Ea),r=n[0],r.x=-r.r,r.y=0,t(r),u>1&&(a=n[1],a.x=a.r,a.y=0,t(a),u>2))for(i=n[2],Na(r,a,i),t(i),za(r,i),r._pack_prev=i,za(i,a),a=r._pack_next,o=3;o=0;)t=a[i],t.z+=n,t.m+=n,n+=t.s+(r+=t.c)}function Ba(e,t,n){return e.a.parent===t.parent?e.a:n}function Da(e){return 1+so.max(e,function(e){return e.y})}function Ra(e){return e.reduce(function(e,t){return e+t.x},0)/e.length}function Ia(e){var t=e.children;return t&&t.length?Ia(t[0]):e}function La(e){var t,n=e.children;return n&&(t=n.length)?La(n[t-1]):e}function Va(e){return{x:e.x,y:e.y,dx:e.dx,dy:e.dy}}function Ua(e,t){var n=e.x+t[3],r=e.y+t[0],a=e.dx-t[1]-t[3],i=e.dy-t[0]-t[2];return a<0&&(n+=a/2,a=0),i<0&&(r+=i/2,i=0),{x:n,y:r,dx:a,dy:i}}function Ya(e){var t=e[0],n=e[e.length-1];return t2?Wa:Xa,s=r?Jr:Wr;return o=a(e,t,s,n),l=a(t,e,s,br),i}function i(e){return o(e)}var o,l;return i.invert=function(e){return l(e)},i.domain=function(t){return arguments.length?(e=t.map(Number),a()):e},i.range=function(e){return arguments.length?(t=e,a()):t},i.rangeRound=function(e){return i.range(e).interpolate(Dr)},i.clamp=function(e){return arguments.length?(r=e,a()):r},i.interpolate=function(e){return arguments.length?(n=e,a()):n},i.ticks=function(t){return ei(e,t)},i.tickFormat=function(t,n){return ti(e,t,n)},i.nice=function(t){return Ka(e,t),a()},i.copy=function(){return Ja(e,t,n,r)},a()}function Qa(e,t){return so.rebind(e,t,"range","rangeRound","interpolate","clamp")}function Ka(e,t){return Ga(e,Za($a(e,t)[2])),Ga(e,Za($a(e,t)[2])),e}function $a(e,t){null==t&&(t=10);var n=Ya(e),r=n[1]-n[0],a=Math.pow(10,Math.floor(Math.log(r/t)/Math.LN10)),i=t/r*a;return i<=.15?a*=10:i<=.35?a*=5:i<=.75&&(a*=2),n[0]=Math.ceil(n[0]/a)*a,n[1]=Math.floor(n[1]/a)*a+.5*a,n[2]=a,n}function ei(e,t){return so.range.apply(so,$a(e,t))}function ti(e,t,n){var r=$a(e,t);if(n){var a=cl.exec(n);if(a.shift(),"s"===a[8]){var i=so.formatPrefix(Math.max(xo(r[0]),xo(r[1])));return a[7]||(a[7]="."+ni(i.scale(r[2]))),a[8]="f",n=so.format(a.join("")),function(e){return n(i.scale(e))+i.symbol}}a[7]||(a[7]="."+ri(a[8],r)),n=a.join("")}else n=",."+ni(r[2])+"f";return so.format(n)}function ni(e){return-Math.floor(Math.log(e)/Math.LN10+.01)}function ri(e,t){var n=ni(t[2]);return e in ks?Math.abs(n-ni(Math.max(xo(t[0]),xo(t[1]))))+ +("e"!==e):n-2*("%"===e)}function ai(e,t,n,r){function a(e){return(n?Math.log(e<0?0:e):-Math.log(e>0?0:-e))/Math.log(t)}function i(e){return n?Math.pow(t,e):-Math.pow(t,-e)}function o(t){return e(a(t))}return o.invert=function(t){return i(e.invert(t))},o.domain=function(t){return arguments.length?(n=t[0]>=0,e.domain((r=t.map(Number)).map(a)),o):r},o.base=function(n){return arguments.length?(t=+n,e.domain(r.map(a)),o):t},o.nice=function(){var t=Ga(r.map(a),n?Math:Ms);return e.domain(t),r=t.map(i),o},o.ticks=function(){var e=Ya(r),o=[],l=e[0],s=e[1],u=Math.floor(a(l)),c=Math.ceil(a(s)),f=t%1?2:t;if(isFinite(c-u)){if(n){for(;u0;d--)o.push(i(u)*d);for(u=0;o[u]s;c--);o=o.slice(u,c)}return o},o.tickFormat=function(e,n){if(!arguments.length)return zs;arguments.length<2?n=zs:"function"!=typeof n&&(n=so.format(n));var r=Math.max(1,t*e/o.ticks().length);return function(e){var o=e/i(Math.round(a(e)));return o*t0?l[n-1]:e[0],n0?0:1}function xi(e,t,n,r,a){var i=e[0]-t[0],o=e[1]-t[1],l=(a?r:-r)/Math.sqrt(i*i+o*o),s=l*o,u=-l*i,c=e[0]+s,f=e[1]+u,d=t[0]+s,p=t[1]+u,h=(c+d)/2,v=(f+p)/2,g=d-c,m=p-f,y=g*g+m*m,x=n-r,b=c*p-d*f,w=(m<0?-1:1)*Math.sqrt(Math.max(0,x*x*y-b*b)),_=(b*m-g*w)/y,k=(-b*g-m*w)/y,z=(b*m+g*w)/y,M=(-b*g+m*w)/y,A=_-h,j=k-v,E=z-h,S=M-v;return A*A+j*j>E*E+S*S&&(_=z,k=M),[[_-s,k-u],[_*n/x,k*n/x]]}function bi(e){function t(t){function o(){u.push("M",i(e(c),l))}for(var s,u=[],c=[],f=-1,d=t.length,p=je(n),h=je(r);++f1?e.join("L"):e+"Z"}function _i(e){return e.join("L")+"Z"}function ki(e){for(var t=0,n=e.length,r=e[0],a=[r[0],",",r[1]];++t1&&a.push("H",r[0]),a.join("")}function zi(e){for(var t=0,n=e.length,r=e[0],a=[r[0],",",r[1]];++t1){l=t[1],i=e[s],s++,r+="C"+(a[0]+o[0])+","+(a[1]+o[1])+","+(i[0]-l[0])+","+(i[1]-l[1])+","+i[0]+","+i[1];for(var u=2;u9&&(a=3*t/Math.sqrt(a),o[l]=a*n,o[l+1]=a*r));for(l=-1;++l<=s;)a=(e[Math.min(s,l+1)][0]-e[Math.max(0,l-1)][0])/(6*(1+o[l]*o[l])),i.push([a||0,o[l]*a||0]);return i}function Ii(e){return e.length<3?wi(e):e[0]+Si(e,Ri(e))}function Li(e){for(var t,n,r,a=-1,i=e.length;++a0;)p[--l].call(e,o);if(i>=1)return v.event&&v.event.end.call(e,e.__data__,t),--h.count?delete h[r]:delete e[n],1}var s,u,f,d,p,h=e[n]||(e[n]={active:0,count:0}),v=h[r];v||(s=a.time,u=Fe(i,0,s),v=h[r]={tween:new c,time:s,timer:u,delay:a.delay,duration:a.duration,ease:a.ease,index:t},a=null,++h.count)}function to(e,t,n){e.attr("transform",function(e){var r=t(e);return"translate("+(isFinite(r)?r:n(e))+",0)"})}function no(e,t,n){e.attr("transform",function(e){var r=t(e);return"translate(0,"+(isFinite(r)?r:n(e))+")"})}function ro(e){return e.toISOString()}function ao(e,t,n){function r(t){return e(t)}function a(e,n){var r=e[1]-e[0],a=r/n,i=so.bisect(Js,a);return i==Js.length?[t.year,$a(e.map(function(e){return e/31536e6}),n)[2]]:i?t[a/Js[i-1]1?{floor:function(t){for(;n(t=e.floor(t));)t=io(t-1);return t},ceil:function(t){for(;n(t=e.ceil(t));)t=io(+t+1);return t}}:e))},r.ticks=function(e,t){var n=Ya(r.domain()),i=null==e?a(n,10):"number"==typeof e?a(n,e):!e.range&&[{range:e},t];return i&&(e=i[0],t=i[1]),e.range(n[0],io(+n[1]+1),t<1?1:t)},r.tickFormat=function(){return n},r.copy=function(){return ao(e.copy(),t,n)},Qa(r,e)}function io(e){return new Date(e)}function oo(e){return JSON.parse(e.responseText)}function lo(e){var t=fo.createRange();return t.selectNode(fo.body),t.createContextualFragment(e.responseText)}var so={version:"3.5.15"},uo=[].slice,co=function(e){return uo.call(e)},fo=this.document;if(fo)try{co(fo.documentElement.childNodes)[0].nodeType}catch(e){co=function(e){for(var t=e.length,n=new Array(t);t--;)n[t]=e[t];return n}}if(Date.now||(Date.now=function(){return+new Date}),fo)try{fo.createElement("DIV").style.setProperty("opacity",0,"")}catch(e){var po=this.Element.prototype,ho=po.setAttribute,vo=po.setAttributeNS,go=this.CSSStyleDeclaration.prototype,mo=go.setProperty;po.setAttribute=function(e,t){ho.call(this,e,t+"")},po.setAttributeNS=function(e,t,n){vo.call(this,e,t,n+"")},go.setProperty=function(e,t,n){mo.call(this,e,t+"",n)}}so.ascending=r,so.descending=function(e,t){return te?1:t>=e?0:NaN},so.min=function(e,t){var n,r,a=-1,i=e.length;if(1===arguments.length){for(;++a=r){n=r;break}for(;++ar&&(n=r)}else{for(;++a=r){n=r;break}for(;++ar&&(n=r)}return n},so.max=function(e,t){var n,r,a=-1,i=e.length;if(1===arguments.length){for(;++a=r){n=r;break}for(;++an&&(n=r)}else{for(;++a=r){n=r;break}for(;++an&&(n=r)}return n},so.extent=function(e,t){var n,r,a,i=-1,o=e.length;if(1===arguments.length){for(;++i=r){n=a=r;break}for(;++ir&&(n=r),a=r){n=a=r;break}for(;++ir&&(n=r),a1)return s/(c-1)},so.deviation=function(){var e=so.variance.apply(this,arguments);return e?Math.sqrt(e):e};var yo=o(r);so.bisectLeft=yo.left,so.bisect=so.bisectRight=yo.right,so.bisector=function(e){return o(1===e.length?function(t,n){return r(e(t),n)}:e)},so.shuffle=function(e,t,n){(i=arguments.length)<3&&(n=e.length,i<2&&(t=0));for(var r,a,i=n-t;i;)a=Math.random()*i--|0,r=e[i+t],e[i+t]=e[a+t],e[a+t]=r;return e},so.permute=function(e,t){for(var n=t.length,r=new Array(n);n--;)r[n]=e[t[n]];return r},so.pairs=function(e){for(var t,n=0,r=e.length-1,a=e[0],i=new Array(r<0?0:r);n=0;)for(r=e[a],t=r.length;--t>=0;)n[--o]=r[t];return n};var xo=Math.abs;so.range=function(e,t,n){if(arguments.length<3&&(n=1,arguments.length<2&&(t=e,e=0)),(t-e)/n===1/0)throw new Error("infinite range");var r,a=[],i=s(xo(n)),o=-1;if(e*=i,t*=i,n*=i,n<0)for(;(r=e+n*++o)>t;)a.push(r/i);else for(;(r=e+n*++o)=i.length)return r?r.call(a,o):n?o.sort(n):o;for(var s,u,f,d,p=-1,h=o.length,v=i[l++],g=new c;++p=i.length)return e;var r=[],a=o[n++];return e.forEach(function(e,a){r.push({key:e,values:t(a,n)})}),a?r.sort(function(e,t){return a(e.key,t.key)}):r}var n,r,a={},i=[],o=[];return a.map=function(t,n){return e(n,t,0)},a.entries=function(n){return t(e(so.map,n,0),0)},a.key=function(e){return i.push(e),a},a.sortKeys=function(e){return o[i.length-1]=e,a},a.sortValues=function(e){return n=e,a},a.rollup=function(e){return r=e,a},a},so.set=function(e){var t=new y;if(e)for(var n=0,r=e.length;n=0&&(r=e.slice(n+1),e=e.slice(0,n)),e)return arguments.length<2?this[e].on(r):this[e].on(r,t);if(2===arguments.length){if(null==t)for(e in this)this.hasOwnProperty(e)&&this[e].on(r,null); +return this}},so.event=null,so.requote=function(e){return e.replace(ko,"\\$&")};var ko=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,zo={}.__proto__?function(e,t){e.__proto__=t}:function(e,t){for(var n in t)e[n]=t[n]},Mo=function(e,t){return t.querySelector(e)},Ao=function(e,t){return t.querySelectorAll(e)},jo=function(e,t){var n=e.matches||e[w(e,"matchesSelector")];return(jo=function(e,t){return n.call(e,t)})(e,t)};"function"==typeof Sizzle&&(Mo=function(e,t){return Sizzle(e,t)[0]||null},Ao=Sizzle,jo=Sizzle.matchesSelector),so.selection=function(){return so.select(fo.documentElement)};var Eo=so.selection.prototype=[];Eo.select=function(e){var t,n,r,a,i=[];e=S(e);for(var o=-1,l=this.length;++o=0&&"xmlns"!==(n=e.slice(0,t))&&(e=e.slice(t+1)),So.hasOwnProperty(n)?{space:So[n],local:e}:e}},Eo.attr=function(e,t){if(arguments.length<2){if("string"==typeof e){var n=this.node();return e=so.ns.qualify(e),e.local?n.getAttributeNS(e.space,e.local):n.getAttribute(e)}for(t in e)this.each(N(t,e[t]));return this}return this.each(N(e,t))},Eo.classed=function(e,t){if(arguments.length<2){if("string"==typeof e){var n=this.node(),r=(e=T(e)).length,a=-1;if(t=n.classList){for(;++a=0;)(n=r[a])&&(i&&i!==n.nextSibling&&i.parentNode.insertBefore(n,i),i=n);return this},Eo.sort=function(e){e=U.apply(this,arguments);for(var t=-1,n=this.length;++t0&&(t=t.transition().duration(S)),t.call(e.event)}function l(){w&&w.domain(b.range().map(function(e){return(e-z.x)/z.k}).map(b.invert)),k&&k.domain(_.range().map(function(e){return(e-z.y)/z.k}).map(_.invert))}function s(e){O++||e({type:"zoomstart"})}function u(e){l(),e({type:"zoom",scale:z.k,translate:[z.x,z.y]})}function c(e){--O||(e({type:"zoomend"}),g=null)}function f(){function e(){l=1,i(so.mouse(a),d),u(o)}function r(){f.on(F,null).on(C,null),p(l),c(o)}var a=this,o=q.of(a,arguments),l=0,f=so.select(n(a)).on(F,e).on(C,r),d=t(so.mouse(a)),p=J(a);Is.call(a),s(o)}function d(){function e(){var e=so.touches(h);return p=z.k,e.forEach(function(e){e.identifier in g&&(g[e.identifier]=t(e))}),e}function n(){var t=so.event.target;so.select(t).on(b,r).on(w,l),_.push(t);for(var n=so.event.changedTouches,a=0,i=n.length;a1){var c=s[0],f=s[1],d=c[0]-f[0],p=c[1]-f[1];m=d*d+p*p}}function r(){var e,t,n,r,o=so.touches(h);Is.call(h);for(var l=0,s=o.length;l=u)return o;if(a)return a=!1,i;var t=c;if(34===e.charCodeAt(t)){for(var n=t;n++=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,fl=so.map({b:function(e){return e.toString(2)},c:function(e){return String.fromCharCode(e)},o:function(e){return e.toString(8)},x:function(e){return e.toString(16)},X:function(e){return e.toString(16).toUpperCase()},g:function(e,t){return e.toPrecision(t)},e:function(e,t){return e.toExponential(t)},f:function(e,t){return e.toFixed(t)},r:function(e,t){return(e=so.round(e,Pe(e,t))).toFixed(Math.max(0,Math.min(20,Pe(e*(1+1e-15),t))))}}),dl=so.time={},pl=Date;Ie.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(){hl.setUTCDate.apply(this._,arguments)},setDay:function(){hl.setUTCDay.apply(this._,arguments)},setFullYear:function(){hl.setUTCFullYear.apply(this._,arguments)},setHours:function(){hl.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){hl.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){hl.setUTCMinutes.apply(this._,arguments)},setMonth:function(){hl.setUTCMonth.apply(this._,arguments)},setSeconds:function(){hl.setUTCSeconds.apply(this._,arguments)},setTime:function(){hl.setTime.apply(this._,arguments)}};var hl=Date.prototype;dl.year=Le(function(e){return e=dl.day(e),e.setMonth(0,1),e},function(e,t){e.setFullYear(e.getFullYear()+t)},function(e){return e.getFullYear()}),dl.years=dl.year.range,dl.years.utc=dl.year.utc.range,dl.day=Le(function(e){var t=new pl(2e3,0);return t.setFullYear(e.getFullYear(),e.getMonth(),e.getDate()),t},function(e,t){e.setDate(e.getDate()+t)},function(e){return e.getDate()-1}),dl.days=dl.day.range,dl.days.utc=dl.day.utc.range,dl.dayOfYear=function(e){var t=dl.year(e);return Math.floor((e-t-6e4*(e.getTimezoneOffset()-t.getTimezoneOffset()))/864e5)},["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(e,t){t=7-t;var n=dl[e]=Le(function(e){return(e=dl.day(e)).setDate(e.getDate()-(e.getDay()+t)%7),e},function(e,t){e.setDate(e.getDate()+7*Math.floor(t))},function(e){var n=dl.year(e).getDay();return Math.floor((dl.dayOfYear(e)+(n+t)%7)/7)-(n!==t)});dl[e+"s"]=n.range,dl[e+"s"].utc=n.utc.range,dl[e+"OfYear"]=function(e){var n=dl.year(e).getDay();return Math.floor((dl.dayOfYear(e)+(n+t)%7)/7)}}),dl.week=dl.sunday,dl.weeks=dl.sunday.range,dl.weeks.utc=dl.sunday.utc.range,dl.weekOfYear=dl.sundayOfYear;var vl={"-":"",_:" ",0:"0"},gl=/^\s*\d+/,ml=/^%/;so.locale=function(e){return{numberFormat:De(e),timeFormat:Ue(e)}};var yl=so.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"]});so.format=yl.numberFormat,so.geo={},ct.prototype={s:0,t:0,add:function(e){ft(e,this.t,xl),ft(xl.s,this.s,this),this.s?this.t+=xl.t:this.s=xl.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var xl=new ct;so.geo.stream=function(e,t){e&&bl.hasOwnProperty(e.type)?bl[e.type](e,t):dt(e,t)};var bl={Feature:function(e,t){dt(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,r=-1,a=n.length;++rp&&(p=t)}function t(t,n){var r=gt([t*Lo,n*Lo]);if(m){var a=yt(m,r),i=[a[1],-a[0],0],o=yt(i,a);wt(o),o=_t(o);var s=t-h,u=s>0?1:-1,v=o[0]*Vo*u,g=xo(s)>180;if(g^(u*hp&&(p=y)}else if(v=(v+360)%360-180,g^(u*hp&&(p=n);g?tl(c,d)&&(d=t):l(t,d)>l(c,d)&&(c=t):d>=c?(td&&(d=t)):t>h?l(c,t)>l(c,d)&&(d=t):l(t,d)>l(c,d)&&(c=t)}else e(t,n);m=r,h=t}function n(){w.point=t}function r(){b[0]=c,b[1]=d,w.point=e,m=null}function a(e,n){if(m){var r=e-h;y+=xo(r)>180?r+(r>0?360:-360):r}else v=e,g=n;zl.point(e,n),t(e,n)}function i(){zl.lineStart()}function o(){a(v,g),zl.lineEnd(),xo(y)>qo&&(c=-(d=180)),b[0]=c,b[1]=d,m=null}function l(e,t){return(t-=e)<0?t+360:t}function s(e,t){return e[0]-t[0]}function u(e,t){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:eqo?p=90:y<-qo&&(f=-90),b[0]=c,b[1]=d}};return function(e){p=d=-(c=f=1/0),x=[],so.geo.stream(e,w);var t=x.length;if(t){x.sort(s);for(var n,r=1,a=x[0],i=[a];rl(a[0],a[1])&&(a[1]=n[1]),l(n[0],a[1])>l(a[0],a[1])&&(a[0]=n[0])):i.push(a=n);for(var o,n,h=-(1/0),t=i.length-1,r=0,a=i[t];r<=t;a=n,++r)n=i[r],(o=l(a[1],n[0]))>h&&(h=o,c=n[0],d=a[1])}return x=b=null,c===1/0||f===1/0?[[NaN,NaN],[NaN,NaN]]:[[c,f],[d,p]]}}(),so.geo.centroid=function(e){Ml=Al=jl=El=Sl=Ol=Nl=Fl=Cl=Tl=ql=0,so.geo.stream(e,Pl);var t=Cl,n=Tl,r=ql,a=t*t+n*n+r*r;return a=.12&&a<.234&&r>=-.425&&r<-.214?o:a>=.166&&a<.234&&r>=-.214&&r<-.115?l:i).invert(e)},e.stream=function(e){var t=i.stream(e),n=o.stream(e),r=l.stream(e);return{point:function(e,a){t.point(e,a),n.point(e,a),r.point(e,a)},sphere:function(){t.sphere(),n.sphere(),r.sphere()},lineStart:function(){t.lineStart(),n.lineStart(),r.lineStart()},lineEnd:function(){t.lineEnd(),n.lineEnd(),r.lineEnd()},polygonStart:function(){t.polygonStart(),n.polygonStart(),r.polygonStart()},polygonEnd:function(){t.polygonEnd(),n.polygonEnd(),r.polygonEnd()}}},e.precision=function(t){return arguments.length?(i.precision(t),o.precision(t),l.precision(t),e):i.precision()},e.scale=function(t){return arguments.length?(i.scale(t),o.scale(.35*t),l.scale(t),e.translate(i.translate())):i.scale()},e.translate=function(t){if(!arguments.length)return i.translate();var u=i.scale(),c=+t[0],f=+t[1];return n=i.translate(t).clipExtent([[c-.455*u,f-.238*u],[c+.455*u,f+.238*u]]).stream(s).point,r=o.translate([c-.307*u,f+.201*u]).clipExtent([[c-.425*u+qo,f+.12*u+qo],[c-.214*u-qo,f+.234*u-qo]]).stream(s).point,a=l.translate([c-.205*u,f+.212*u]).clipExtent([[c-.214*u+qo,f+.166*u+qo],[c-.115*u-qo,f+.234*u-qo]]).stream(s).point,e},e.scale(1070)};var Rl,Il,Ll,Vl,Ul,Yl,Hl={point:_,lineStart:_,lineEnd:_,polygonStart:function(){Il=0,Hl.lineStart=Gt},polygonEnd:function(){Hl.lineStart=Hl.lineEnd=Hl.point=_,Rl+=xo(Il/2)}},Xl={point:Zt,lineStart:_,lineEnd:_,polygonStart:_,polygonEnd:_},Gl={point:Qt,lineStart:Kt,lineEnd:$t,polygonStart:function(){Gl.lineStart=en},polygonEnd:function(){Gl.point=Qt,Gl.lineStart=Kt,Gl.lineEnd=$t}};so.geo.path=function(){function e(e){return e&&("function"==typeof l&&i.pointRadius(+l.apply(this,arguments)),o&&o.valid||(o=a(i)),so.geo.stream(e,o)),i.result()}function t(){return o=null,e}var n,r,a,i,o,l=4.5;return e.area=function(e){return Rl=0,so.geo.stream(e,a(Hl)),Rl},e.centroid=function(e){return jl=El=Sl=Ol=Nl=Fl=Cl=Tl=ql=0,so.geo.stream(e,a(Gl)),ql?[Cl/ql,Tl/ql]:Fl?[Ol/Fl,Nl/Fl]:Sl?[jl/Sl,El/Sl]:[NaN,NaN]},e.bounds=function(e){return Ul=Yl=-(Ll=Vl=1/0),so.geo.stream(e,a(Xl)),[[Ll,Vl],[Ul,Yl]]},e.projection=function(e){return arguments.length?(a=(n=e)?e.stream||rn(e):x,t()):n},e.context=function(e){return arguments.length?(i=null==(r=e)?new Wt:new tn(e),"function"!=typeof l&&i.pointRadius(l),t()):r},e.pointRadius=function(t){return arguments.length?(l="function"==typeof t?t:(i.pointRadius(+t),+t),e):l},e.projection(so.geo.albersUsa()).context(null)},so.geo.transform=function(e){return{stream:function(t){var n=new an(t);for(var r in e)n[r]=e[r];return n}}},an.prototype={point:function(e,t){this.stream.point(e,t)},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()}},so.geo.projection=ln,so.geo.projectionMutator=sn,(so.geo.equirectangular=function(){return ln(cn)}).raw=cn.invert=cn,so.geo.rotation=function(e){function t(t){return t=e(t[0]*Lo,t[1]*Lo),t[0]*=Vo,t[1]*=Vo,t}return e=dn(e[0]%360*Lo,e[1]*Lo,e.length>2?e[2]*Lo:0),t.invert=function(t){return t=e.invert(t[0]*Lo,t[1]*Lo),t[0]*=Vo,t[1]*=Vo,t},t},fn.invert=cn,so.geo.circle=function(){function e(){var e="function"==typeof r?r.apply(this,arguments):r,t=dn(-e[0]*Lo,-e[1]*Lo,0).invert,a=[];return n(null,null,1,{point:function(e,n){a.push(e=t(e,n)),e[0]*=Vo,e[1]*=Vo}}),{type:"Polygon",coordinates:[a]}}var t,n,r=[0,0],a=6;return e.origin=function(t){return arguments.length?(r=t,e):r},e.angle=function(r){return arguments.length?(n=gn((t=+r)*Lo,a*Lo),e):t},e.precision=function(r){return arguments.length?(n=gn(t*Lo,(a=+r)*Lo),e):a},e.angle(90)},so.geo.distance=function(e,t){var n,r=(t[0]-e[0])*Lo,a=e[1]*Lo,i=t[1]*Lo,o=Math.sin(r),l=Math.cos(r),s=Math.sin(a),u=Math.cos(a),c=Math.sin(i),f=Math.cos(i);return Math.atan2(Math.sqrt((n=f*o)*n+(n=u*c-s*f*l)*n),s*c+u*f*l)},so.geo.graticule=function(){function e(){return{type:"MultiLineString",coordinates:t()}}function t(){return so.range(Math.ceil(i/g)*g,a,g).map(d).concat(so.range(Math.ceil(u/m)*m,s,m).map(p)).concat(so.range(Math.ceil(r/h)*h,n,h).filter(function(e){return xo(e%g)>qo}).map(c)).concat(so.range(Math.ceil(l/v)*v,o,v).filter(function(e){return xo(e%m)>qo}).map(f))}var n,r,a,i,o,l,s,u,c,f,d,p,h=10,v=h,g=90,m=360,y=2.5;return e.lines=function(){return t().map(function(e){return{type:"LineString",coordinates:e}})},e.outline=function(){return{type:"Polygon",coordinates:[d(i).concat(p(s).slice(1),d(a).reverse().slice(1),p(u).reverse().slice(1))]}},e.extent=function(t){return arguments.length?e.majorExtent(t).minorExtent(t):e.minorExtent()},e.majorExtent=function(t){return arguments.length?(i=+t[0][0],a=+t[1][0],u=+t[0][1],s=+t[1][1],i>a&&(t=i,i=a,a=t),u>s&&(t=u,u=s,s=t),e.precision(y)):[[i,u],[a,s]]},e.minorExtent=function(t){return arguments.length?(r=+t[0][0],n=+t[1][0],l=+t[0][1],o=+t[1][1],r>n&&(t=r,r=n,n=t),l>o&&(t=l,l=o,o=t),e.precision(y)):[[r,l],[n,o]]},e.step=function(t){return arguments.length?e.majorStep(t).minorStep(t):e.minorStep()},e.majorStep=function(t){return arguments.length?(g=+t[0],m=+t[1],e):[g,m]},e.minorStep=function(t){return arguments.length?(h=+t[0],v=+t[1],e):[h,v]},e.precision=function(t){return arguments.length?(y=+t,c=yn(l,o,90),f=xn(r,n,y),d=yn(u,s,90),p=xn(i,a,y),e):y},e.majorExtent([[-180,-90+qo],[180,90-qo]]).minorExtent([[-180,-80-qo],[180,80+qo]])},so.geo.greatArc=function(){function e(){return{type:"LineString",coordinates:[t||r.apply(this,arguments),n||a.apply(this,arguments)]}}var t,n,r=bn,a=wn;return e.distance=function(){return so.geo.distance(t||r.apply(this,arguments),n||a.apply(this,arguments)); +},e.source=function(n){return arguments.length?(r=n,t="function"==typeof n?null:n,e):r},e.target=function(t){return arguments.length?(a=t,n="function"==typeof t?null:t,e):a},e.precision=function(){return arguments.length?e:0},e},so.geo.interpolate=function(e,t){return _n(e[0]*Lo,e[1]*Lo,t[0]*Lo,t[1]*Lo)},so.geo.length=function(e){return Zl=0,so.geo.stream(e,Wl),Zl};var Zl,Wl={sphere:_,point:_,lineStart:kn,lineEnd:_,polygonStart:_,polygonEnd:_},Jl=zn(function(e){return Math.sqrt(2/(1+e))},function(e){return 2*Math.asin(e/2)});(so.geo.azimuthalEqualArea=function(){return ln(Jl)}).raw=Jl;var Ql=zn(function(e){var t=Math.acos(e);return t&&t/Math.sin(t)},x);(so.geo.azimuthalEquidistant=function(){return ln(Ql)}).raw=Ql,(so.geo.conicConformal=function(){return Ht(Mn)}).raw=Mn,(so.geo.conicEquidistant=function(){return Ht(An)}).raw=An;var Kl=zn(function(e){return 1/e},Math.atan);(so.geo.gnomonic=function(){return ln(Kl)}).raw=Kl,jn.invert=function(e,t){return[e,2*Math.atan(Math.exp(t))-Io]},(so.geo.mercator=function(){return En(jn)}).raw=jn;var $l=zn(function(){return 1},Math.asin);(so.geo.orthographic=function(){return ln($l)}).raw=$l;var es=zn(function(e){return 1/(1+e)},function(e){return 2*Math.atan(e)});(so.geo.stereographic=function(){return ln(es)}).raw=es,Sn.invert=function(e,t){return[-t,2*Math.atan(Math.exp(e))-Io]},(so.geo.transverseMercator=function(){var e=En(Sn),t=e.center,n=e.rotate;return e.center=function(e){return e?t([-e[1],e[0]]):(e=t(),[e[1],-e[0]])},e.rotate=function(e){return e?n([e[0],e[1],e.length>2?e[2]+90:90]):(e=n(),[e[0],e[1],e[2]-90])},n([0,0,90])}).raw=Sn,so.geom={},so.geom.hull=function(e){function t(e){if(e.length<3)return[];var t,a=je(n),i=je(r),o=e.length,l=[],s=[];for(t=0;t=0;--t)p.push(e[l[u[t]][2]]);for(t=+f;t=r&&u.x<=i&&u.y>=a&&u.y<=o?[[r,o],[i,o],[i,a],[r,a]]:[];c.point=e[l]}),t}function n(e){return e.map(function(e,t){return{x:Math.round(i(e,t)/qo)*qo,y:Math.round(o(e,t)/qo)*qo,i:t}})}var r=On,a=Nn,i=r,o=a,l=us;return e?t(e):(t.links=function(e){return sr(n(e)).edges.filter(function(e){return e.l&&e.r}).map(function(t){return{source:e[t.l.i],target:e[t.r.i]}})},t.triangles=function(e){var t=[];return sr(n(e)).cells.forEach(function(n,r){for(var a,i,o=n.site,l=n.edges.sort(Xn),s=-1,u=l.length,c=l[u-1].edge,f=c.l===o?c.r:c.l;++s=u,d=r>=c,p=d<<1|f;e.leaf=!1,e=e.nodes[p]||(e.nodes[p]=pr()),f?a=u:l=u,d?o=c:s=c,i(e,t,n,r,a,o,l,s)}var c,f,d,p,h,v,g,m,y,x=je(l),b=je(s);if(null!=t)v=t,g=n,m=r,y=a;else if(m=y=-(v=g=1/0),f=[],d=[],h=e.length,o)for(p=0;pm&&(m=c.x),c.y>y&&(y=c.y),f.push(c.x),d.push(c.y);else for(p=0;pm&&(m=w),_>y&&(y=_),f.push(w),d.push(_)}var k=m-v,z=y-g;k>z?y=g+k:m=v+z;var M=pr();if(M.add=function(e){i(M,e,+x(e,++p),+b(e,p),v,g,m,y)},M.visit=function(e){hr(e,M,v,g,m,y)},M.find=function(e){return vr(M,e[0],e[1],v,g,m,y)},p=-1,null==t){for(;++p=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):"in";return n=ps.get(n)||ds,r=hs.get(r)||x,_r(r(n.apply(null,uo.call(arguments,1))))},so.interpolateHcl=qr,so.interpolateHsl=Pr,so.interpolateLab=Br,so.interpolateRound=Dr,so.transform=function(e){var t=fo.createElementNS(so.ns.prefix.svg,"g");return(so.transform=function(e){if(null!=e){t.setAttribute("transform",e);var n=t.transform.baseVal.consolidate()}return new Rr(n?n.matrix:vs)})(e)},Rr.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var vs={a:1,b:0,c:0,d:1,e:0,f:0};so.interpolateTransform=Zr,so.layout={},so.layout.bundle=function(){return function(e){for(var t=[],n=-1,r=e.length;++n0?a=e:(n.c=null,n.t=NaN,n=null,u.end({type:"end",alpha:a=0})):e>0&&(u.start({type:"start",alpha:a=e}),n=Fe(s.tick)),s):a},s.start=function(){function e(e,r){if(!n){for(n=new Array(a),s=0;s=0;)o.push(c=u[s]),c.parent=i,c.depth=i.depth+1;r&&(i.value=0),i.children=u}else r&&(i.value=+r.call(e,i,i.depth)||0),delete i.children;return la(a,function(e){var n,a;t&&(n=e.children)&&n.sort(t),r&&(a=e.parent)&&(a.value+=e.value)}),l}var t=ca,n=sa,r=ua;return e.sort=function(n){return arguments.length?(t=n,e):t},e.children=function(t){return arguments.length?(n=t,e):n},e.value=function(t){return arguments.length?(r=t,e):r},e.revalue=function(t){return r&&(oa(t,function(e){e.children&&(e.value=0)}),la(t,function(t){var n;t.children||(t.value=+r.call(e,t,t.depth)||0),(n=t.parent)&&(n.value+=t.value)})),t},e},so.layout.partition=function(){function e(t,n,r,a){var i=t.children;if(t.x=n,t.y=t.depth*a,t.dx=r,t.dy=a,i&&(o=i.length)){var o,l,s,u=-1;for(r=t.value?r/t.value:0;++ul&&(l=r),o.push(r)}for(n=0;n0)for(i=-1;++i=c[0]&&l<=c[1]&&(o=s[so.bisect(f,l,1,p)-1],o.y+=h,o.push(e[i]));return s}var t=!0,n=Number,r=_a,a=ba;return e.value=function(t){return arguments.length?(n=t,e):n},e.range=function(t){return arguments.length?(r=je(t),e):r},e.bins=function(t){return arguments.length?(a="number"==typeof t?function(e){return wa(e,t)}:je(t),e):a},e.frequency=function(n){return arguments.length?(t=!!n,e):t},e},so.layout.pack=function(){function e(e,i){var o=n.call(this,e,i),l=o[0],s=a[0],u=a[1],c=null==t?Math.sqrt:"function"==typeof t?t:function(){return t};if(l.x=l.y=0,la(l,function(e){e.r=+c(e.value)}),la(l,ja),r){var f=r*(t?1:Math.max(2*l.r/s,2*l.r/u))/2;la(l,function(e){e.r+=f}),la(l,ja),la(l,function(e){e.r-=f})}return Oa(l,s/2,u/2,t?1:1/Math.max(2*l.r/s,2*l.r/u)),o}var t,n=so.layout.hierarchy().sort(ka),r=0,a=[1,1];return e.size=function(t){return arguments.length?(a=t,e):a},e.radius=function(n){return arguments.length?(t=null==n||"function"==typeof n?n:+n,e):t},e.padding=function(t){return arguments.length?(r=+t,e):r},ia(e,n)},so.layout.tree=function(){function e(e,a){var c=o.call(this,e,a),f=c[0],d=t(f);if(la(d,n),d.parent.m=-d.z,oa(d,r),u)oa(f,i);else{var p=f,h=f,v=f;oa(f,function(e){e.xh.x&&(h=e),e.depth>v.depth&&(v=e)});var g=l(p,h)/2-p.x,m=s[0]/(h.x+l(h,p)/2+g),y=s[1]/(v.depth||1);oa(f,function(e){e.x=(e.x+g)*m,e.y=e.depth*y})}return c}function t(e){for(var t,n={A:null,children:[e]},r=[n];null!=(t=r.pop());)for(var a,i=t.children,o=0,l=i.length;o0&&(qa(Ba(o,e,n),e,r),u+=r,c+=r),f+=o.m,u+=a.m,d+=s.m,c+=i.m;o&&!Ta(i)&&(i.t=o,i.m+=f-c),a&&!Ca(s)&&(s.t=a,s.m+=u-d,n=e)}return n}function i(e){e.x*=s[0],e.y=e.depth*s[1]}var o=so.layout.hierarchy().sort(null).value(null),l=Fa,s=[1,1],u=null;return e.separation=function(t){return arguments.length?(l=t,e):l},e.size=function(t){return arguments.length?(u=null==(s=t)?i:null,e):u?null:s},e.nodeSize=function(t){return arguments.length?(u=null==(s=t)?null:i,e):u?s:null},ia(e,o)},so.layout.cluster=function(){function e(e,i){var o,l=t.call(this,e,i),s=l[0],u=0;la(s,function(e){var t=e.children;t&&t.length?(e.x=Ra(t),e.y=Da(t)):(e.x=o?u+=n(e,o):0,e.y=0,o=e)});var c=Ia(s),f=La(s),d=c.x-n(c,f)/2,p=f.x+n(f,c)/2;return la(s,a?function(e){e.x=(e.x-s.x)*r[0],e.y=(s.y-e.y)*r[1]}:function(e){e.x=(e.x-d)/(p-d)*r[0],e.y=(1-(s.y?e.y/s.y:1))*r[1]}),l}var t=so.layout.hierarchy().sort(null).value(null),n=Fa,r=[1,1],a=!1;return e.separation=function(t){return arguments.length?(n=t,e):n},e.size=function(t){return arguments.length?(a=null==(r=t),e):a?null:r},e.nodeSize=function(t){return arguments.length?(a=null!=(r=t),e):a?r:null},ia(e,t)},so.layout.treemap=function(){function e(e,t){for(var n,r,a=-1,i=e.length;++a0;)c.push(o=d[s-1]),c.area+=o.area,"squarify"!==p||(l=r(c,v))<=h?(d.pop(),h=l):(c.area-=c.pop().area,a(c,v,u,!1),v=Math.min(u.dx,u.dy),c.length=c.area=0,h=1/0);c.length&&(a(c,v,u,!0),c.length=c.area=0),i.forEach(t)}}function n(t){var r=t.children;if(r&&r.length){var i,o=f(t),l=r.slice(),s=[];for(e(l,o.dx*o.dy/t.value),s.area=0;i=l.pop();)s.push(i),s.area+=i.area,null!=i.z&&(a(s,i.z?o.dx:o.dy,o,!l.length),s.length=s.area=0);r.forEach(n)}}function r(e,t){for(var n,r=e.area,a=0,i=1/0,o=-1,l=e.length;++oa&&(a=n));return r*=r,t*=t,r?Math.max(t*a*h/r,r/(t*i*h)):1/0}function a(e,t,n,r){var a,i=-1,o=e.length,l=n.x,u=n.y,c=t?s(e.area/t):0;if(t==n.dx){for((r||c>n.dy)&&(c=n.dy);++in.dx)&&(c=n.dx);++i1);return e+t*n*Math.sqrt(-2*Math.log(a)/a)}},logNormal:function(){var e=so.random.normal.apply(so,arguments);return function(){return Math.exp(e())}},bates:function(e){var t=so.random.irwinHall(e);return function(){return t()/e}},irwinHall:function(e){return function(){for(var t=0,n=0;nf?0:1;if(u=Ro)return t(u,p)+(e?t(e,1-p):"")+"Z";var h,v,g,m,y,x,b,w,_,k,z,M,A=0,j=0,E=[];if((m=(+s.apply(this,arguments)||0)/2)&&(g=i===Os?Math.sqrt(e*e+u*u):+i.apply(this,arguments),p||(j*=-1),u&&(j=ne(g/u*Math.sin(m))),e&&(A=ne(g/e*Math.sin(m)))),u){y=u*Math.cos(c+j),x=u*Math.sin(c+j),b=u*Math.cos(f-j),w=u*Math.sin(f-j);var S=Math.abs(f-c-2*j)<=Bo?0:1;if(j&&yi(y,x,b,w)===p^S){var O=(c+f)/2;y=u*Math.cos(O),x=u*Math.sin(O),b=w=null}}else y=x=0;if(e){_=e*Math.cos(f-A),k=e*Math.sin(f-A),z=e*Math.cos(c+A),M=e*Math.sin(c+A);var N=Math.abs(c-f+2*A)<=Bo?0:1;if(A&&yi(_,k,z,M)===1-p^N){var F=(c+f)/2;_=e*Math.cos(F),k=e*Math.sin(F),z=M=null}}else _=k=0;if(d>qo&&(h=Math.min(Math.abs(u-e)/2,+a.apply(this,arguments)))>.001){v=eBo)+",1 "+t}function a(e,t,n,r){return"Q 0,0 "+r}var i=bn,o=wn,l=Ui,s=vi,u=gi;return e.radius=function(t){return arguments.length?(l=je(t),e):l},e.source=function(t){return arguments.length?(i=je(t),e):i},e.target=function(t){return arguments.length?(o=je(t),e):o},e.startAngle=function(t){return arguments.length?(s=je(t),e):s},e.endAngle=function(t){return arguments.length?(u=je(t),e):u},e},so.svg.diagonal=function(){function e(e,a){var i=t.call(this,e,a),o=n.call(this,e,a),l=(i.y+o.y)/2,s=[i,{x:i.x,y:l},{x:o.x,y:l},o];return s=s.map(r),"M"+s[0]+"C"+s[1]+" "+s[2]+" "+s[3]}var t=bn,n=wn,r=Yi;return e.source=function(n){return arguments.length?(t=je(n),e):t},e.target=function(t){return arguments.length?(n=je(t),e):n},e.projection=function(t){return arguments.length?(r=t,e):r},e},so.svg.diagonal.radial=function(){var e=so.svg.diagonal(),t=Yi,n=e.projection;return e.projection=function(e){return arguments.length?n(Hi(t=e)):t},e},so.svg.symbol=function(){function e(e,r){return(qs.get(t.call(this,e,r))||Zi)(n.call(this,e,r))}var t=Gi,n=Xi;return e.type=function(n){return arguments.length?(t=je(n),e):t},e.size=function(t){return arguments.length?(n=je(t),e):n},e};var qs=so.map({circle:Zi,cross:function(e){var t=Math.sqrt(e/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(e){var t=Math.sqrt(e/(2*Bs)),n=t*Bs;return"M0,"+-t+"L"+n+",0 0,"+t+" "+-n+",0Z"},square:function(e){var t=Math.sqrt(e)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(e){var t=Math.sqrt(e/Ps),n=t*Ps/2;return"M0,"+n+"L"+t+","+-n+" "+-t+","+-n+"Z"},"triangle-up":function(e){var t=Math.sqrt(e/Ps),n=t*Ps/2;return"M0,"+-n+"L"+t+","+n+" "+-t+","+n+"Z"}});so.svg.symbolTypes=qs.keys();var Ps=Math.sqrt(3),Bs=Math.tan(30*Lo);Eo.transition=function(e){for(var t,n,r=Ds||++Vs,a=$i(e),i=[],o=Rs||{time:Date.now(),ease:jr,delay:0,duration:250},l=-1,s=this.length;++lrect,.s>rect").attr("width",f[1]-f[0])}function a(e){e.select(".extent").attr("y",d[0]),e.selectAll(".extent,.e>rect,.w>rect").attr("height",d[1]-d[0])}function i(){function i(){32==so.event.keyCode&&(S||(x=null,N[0]-=f[1],N[1]-=d[1],S=2),M())}function v(){32==so.event.keyCode&&2==S&&(N[0]+=f[1],N[1]+=d[1],S=0,M())}function g(){var e=so.mouse(w),n=!1;b&&(e[0]+=b[0],e[1]+=b[1]),S||(so.event.altKey?(x||(x=[(f[0]+f[1])/2,(d[0]+d[1])/2]),N[0]=f[+(e[0]t?1:0},c=function(e,t,n,i,o){var l;if(null==n&&(n=0),null==o&&(o=r),n<0)throw new Error("lo must be non-negative");for(null==i&&(i=e.length);nn;0<=n?t++:t--)u.push(t);return u}.apply(this).reverse(),s=[],i=0,o=l.length;ig;l=0<=g?++p:--p)m.push(o(e,n));return m},v=function(e,t,n,a){var i,o,l;for(null==a&&(a=r),i=e[n];n>t&&(l=n-1>>1,o=e[l],a(i,o)<0);)e[n]=o,n=l;return e[n]=i},g=function(e,t,n){var a,i,o,l,s;for(null==n&&(n=r),i=e.length,s=t,o=e[t],a=2*t+1;a>1,c=-7,f=n?a-1:0,d=n?-1:1,p=e[t+f];for(f+=d,i=p&(1<<-c)-1,p>>=-c,c+=l;c>0;i=256*i+e[t+f],f+=d,c-=8);for(o=i&(1<<-c)-1,i>>=-c,c+=r;c>0;o=256*o+e[t+f],f+=d,c-=8);if(0===i)i=1-u;else{if(i===s)return o?NaN:(p?-1:1)*(1/0);o+=Math.pow(2,r),i-=u}return(p?-1:1)*o*Math.pow(2,i-r)},n.write=function(e,t,n,r,a,i){var o,l,s,u=8*i-a-1,c=(1<>1,d=23===a?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:i-1,h=r?1:-1,v=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(l=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(s=Math.pow(2,-o))<1&&(o--,s*=2),t+=o+f>=1?d/s:d*Math.pow(2,1-f),t*s>=2&&(o++,s/=2),o+f>=c?(l=0,o=c):o+f>=1?(l=(t*s-1)*Math.pow(2,a),o+=f):(l=t*Math.pow(2,f-1)*Math.pow(2,a),o=0));a>=8;e[n+p]=255&l,p+=h,l/=256,a-=8);for(o=o<0;e[n+p]=255&o,p+=h,o/=256,u-=8);e[n+p-h]|=128*v}},{}],7:[function(e,t,n){var r={}.toString;t.exports=Array.isArray||function(e){return"[object Array]"==r.call(e)}},{}],8:[function(require,module,exports){(function(global){"use strict";var numeric="undefined"==typeof exports?function(){}:exports;"undefined"!=typeof global&&(global.numeric=numeric),numeric.version="1.2.6",numeric.bench=function(e,t){var n,r,a,i;for("undefined"==typeof t&&(t=15),a=.5,n=new Date;;){for(a*=2,i=a;i>3;i-=4)e(),e(),e(),e();for(;i>0;)e(),i--;if(r=new Date,r-n>t)break}for(i=a;i>3;i-=4)e(),e(),e(),e();for(;i>0;)e(),i--;return r=new Date,1e3*(3*a-1)/(r-n)},numeric._myIndexOf=function(e){var t,n=this.length;for(t=0;tnumeric.largeArray)return r.push("...Large Array..."),!0;var u=!1;for(r.push("["),a=0;a0&&(r.push(","),u&&r.push("\n ")),u=n(e[a]);return r.push("]"),!0}r.push("{");var u=!1;for(a in e)e.hasOwnProperty(a)&&(u&&r.push(",\n"),u=!0,r.push(a),r.push(": \n"),n(e[a]));return r.push("}"),!0}var r=[];return n(e),r.join("")},numeric.parseDate=function(e){function t(e){if("string"==typeof e)return Date.parse(e.replace(/-/g,"/"));if(!(e instanceof Array))throw new Error("parseDate: parameter must be arrays of strings");var n,r=[];for(n=0;n0){for(a[s]=[],t=0;t>2,o=((3&n)<<4)+(r>>4),l=((15&r)<<2)+(a>>6),s=63&a,t+1>=u?l=s=64:t+2>=u&&(s=64),f+=c.charAt(i)+c.charAt(o)+c.charAt(l)+c.charAt(s);return f}function n(e,t,n){"undefined"==typeof t&&(t=0),"undefined"==typeof n&&(n=e.length);var r,a=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117],i=-1,o=0;e.length;for(r=t;r>>8^a[o];return i^-1}var r,a,i,o,l,s,u,c,f,d,p=e[0].length,h=e[0][0].length,v=[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,h>>24&255,h>>16&255,h>>8&255,255&h,p>>24&255,p>>16&255,p>>8&255,255&p,8,2,0,0,0,-1,-2,-3,-4,-5,-6,-7,-8,73,68,65,84,8,29];for(d=n(v,12,29),v[29]=d>>24&255,v[30]=d>>16&255,v[31]=d>>8&255,v[32]=255&d,r=1,a=0,u=0;u>8&255,v.push(l),v.push(s),v.push(255&~l),v.push(255&~s),0===u&&v.push(0),c=0;c255?255:l<0?0:Math.round(l),r=(r+l)%65521,a=(a+r)%65521,v.push(l);v.push(0)}return f=(a<<16)+r,v.push(f>>24&255),v.push(f>>16&255),v.push(f>>8&255),v.push(255&f),o=v.length-41,v[33]=o>>24&255,v[34]=o>>16&255,v[35]=o>>8&255,v[36]=255&o,d=n(v,37),v.push(d>>24&255),v.push(d>>16&255),v.push(d>>8&255),v.push(255&d),v.push(0),v.push(0),v.push(0),v.push(0),v.push(73),v.push(69),v.push(78),v.push(68),v.push(174),v.push(66),v.push(96),v.push(130),"data:image/png;base64,"+t(v)},numeric._dim=function(e){for(var t=[];"object"==typeof e;)t.push(e.length),e=e[0];return t},numeric.dim=function(e){var t,n;return"object"==typeof e?(t=e[0],"object"==typeof t?(n=t[0],"object"==typeof n?numeric._dim(e):[e.length,t.length]):[e.length]):[]},numeric.mapreduce=function(e,t){return Function("x","accum","_s","_k",'if(typeof accum === "undefined") accum = '+t+';\nif(typeof x === "number") { var xi = x; '+e+'; return accum; }\nif(typeof _s === "undefined") _s = numeric.dim(x);\nif(typeof _k === "undefined") _k = 0;\nvar _n = _s[_k];\nvar i,xi;\nif(_k < _s.length-1) {\n for(i=_n-1;i>=0;i--) {\n accum = arguments.callee(x[i],accum,_s,_k+1);\n } return accum;\n}\nfor(i=_n-1;i>=1;i-=2) { \n xi = x[i];\n '+e+";\n xi = x[i-1];\n "+e+";\n}\nif(i === 0) {\n xi = x[i];\n "+e+"\n}\nreturn accum;")},numeric.mapreduce2=function(e,t){return Function("x","var n = x.length;\nvar i,xi;\n"+t+";\nfor(i=n-1;i!==-1;--i) { \n xi = x[i];\n "+e+";\n}\nreturn accum;")},numeric.same=function e(t,n){var r,a;if(!(t instanceof Array&&n instanceof Array))return!1;if(a=t.length,a!==n.length)return!1;for(r=0;r=0;r-=2)i[r+1]=t,i[r]=t;return r===-1&&(i[0]=t),i}for(r=a-1;r>=0;r--)i[r]=numeric.rep(e,t,n+1);return i},numeric.dotMMsmall=function(e,t){var n,r,a,i,o,l,s,u,c,f,d;for(i=e.length,o=t.length,l=t[0].length,s=Array(i),n=i-1;n>=0;n--){for(u=Array(l),c=e[n],a=l-1;a>=0;a--){for(f=c[o-1]*t[o-1][a],r=o-2;r>=1;r-=2)d=r-1,f+=c[r]*t[r][a]+c[d]*t[d][a];0===r&&(f+=c[0]*t[0][a]),u[a]=f}s[n]=u}return s},numeric._getCol=function(e,t,n){var r,a=e.length;for(r=a-1;r>0;--r)n[r]=e[r][t],--r,n[r]=e[r][t];0===r&&(n[0]=e[0][t])},numeric.dotMMbig=function(e,t){var n,r,a,i,o=numeric._getCol,l=t.length,s=Array(l),u=e.length,c=t[0].length,f=new Array(u),d=numeric.dotVV;for(--l,--u,r=u;r!==-1;--r)f[r]=Array(c);for(--c,r=c;r!==-1;--r)for(o(t,r,s),a=u;a!==-1;--a)i=0,n=e[a],f[a][r]=d(n,s);return f},numeric.dotMV=function(e,t){var n,r=e.length,a=(t.length,Array(r)),i=numeric.dotVV;for(n=r-1;n>=0;n--)a[n]=i(e[n],t);return a},numeric.dotVM=function(e,t){var n,r,a,i,o,l,s;for(a=e.length,i=t[0].length,o=Array(i),r=i-1;r>=0;r--){for(l=e[a-1]*t[a-1][r],n=a-2;n>=1;n-=2)s=n-1,l+=e[n]*t[n][r]+e[s]*t[s][r];0===n&&(l+=e[0]*t[0][r]),o[r]=l}return o},numeric.dotVV=function(e,t){var n,r,a=e.length,i=e[a-1]*t[a-1];for(n=a-2;n>=1;n-=2)r=n-1,i+=e[n]*t[n]+e[r]*t[r];return 0===n&&(i+=e[0]*t[0]),i},numeric.dot=function(e,t){var n=numeric.dim;switch(1e3*n(e).length+n(t).length){case 2002:return t.length<10?numeric.dotMMsmall(e,t):numeric.dotMMbig(e,t);case 2001:return numeric.dotMV(e,t);case 1002:return numeric.dotVM(e,t);case 1001:return numeric.dotVV(e,t);case 1e3:return numeric.mulVS(e,t);case 1:return numeric.mulSV(e,t);case 0:return e*t;default:throw new Error("numeric.dot only works on vectors and matrices")}},numeric.diag=function(e){var t,n,r,a,i=e.length,o=Array(i);for(t=i-1;t>=0;t--){for(a=Array(i),n=t+2,r=i-1;r>=n;r-=2)a[r]=0,a[r-1]=0;for(r>t&&(a[r]=0),a[t]=e[t],r=t-1;r>=1;r-=2)a[r]=0,a[r-1]=0;0===r&&(a[0]=0),o[t]=a}return o},numeric.getDiag=function(e){var t,n=Math.min(e.length,e[0].length),r=Array(n);for(t=n-1;t>=1;--t)r[t]=e[t][t],--t,r[t]=e[t][t];return 0===t&&(r[0]=e[0][0]),r},numeric.identity=function(e){return numeric.diag(numeric.rep([e],1))},numeric.pointwise=function(e,t,n){"undefined"==typeof n&&(n="");var r,a,i=[],o=/\[i\]$/,l="",s=!1;for(r=0;r=0;i--) ret[i] = arguments.callee("+e.join(",")+",_s,_k+1);\n return ret;\n}\n"+n+"\nfor(i=_n-1;i!==-1;--i) {\n "+t+"\n}\nreturn ret;",Function.apply(null,i)},numeric.pointwise2=function(e,t,n){"undefined"==typeof n&&(n="");var r,a,i=[],o=/\[i\]$/,l="",s=!1;for(r=0;r=0;o--)e("object"==typeof t?t[o]:t,"object"==typeof n?n[o]:n,r,a+1,i)},numeric._biforeach2=function e(t,n,r,a,i){if(a===r.length-1)return i(t,n);var o,l=r[a],s=Array(l);for(o=l-1;o>=0;--o)s[o]=e("object"==typeof t?t[o]:t,"object"==typeof n?n[o]:n,r,a+1,i);return s},numeric._foreach=function e(t,n,r,a){if(r===n.length-1)return void a(t);var i,o=n[r];for(i=o-1;i>=0;i--)e(t[i],n,r+1,a)},numeric._foreach2=function e(t,n,r,a){if(r===n.length-1)return a(t);var i,o=n[r],l=Array(o);for(i=o-1;i>=0;i--)l[i]=e(t[i],n,r+1,a);return l},numeric.ops2={add:"+",sub:"-",mul:"*",div:"/",mod:"%",and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">=",band:"&",bor:"|",bxor:"^",lshift:"<<",rshift:">>",rrshift:">>>"},numeric.opseq={addeq:"+=",subeq:"-=",muleq:"*=",diveq:"/=",modeq:"%=",lshifteq:"<<=",rshifteq:">>=",rrshifteq:">>>=",bandeq:"&=",boreq:"|=",bxoreq:"^="},numeric.mathfuns=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan","isNaN","isFinite"],numeric.mathfuns2=["atan2","pow","max","min"],numeric.ops1={neg:"-",not:"!",bnot:"~",clone:""},numeric.mapreducers={any:["if(xi) return true;","var accum = false;"],all:["if(!xi) return false;","var accum = true;"],sum:["accum += xi;","var accum = 0;"],prod:["accum *= xi;","var accum = 1;"],norm2Squared:["accum += xi*xi;","var accum = 0;"],norminf:["accum = max(accum,abs(xi));","var accum = 0, max = Math.max, abs = Math.abs;"],norm1:["accum += abs(xi)","var accum = 0, abs = Math.abs;"],sup:["accum = max(accum,xi);","var accum = -Infinity, max = Math.max;"],inf:["accum = min(accum,xi);","var accum = Infinity, min = Math.min;"]},function(){var e,t;for(e=0;ev&&(h=i,v=l);for(n=d[h],d[h]=d[o],d[o]=n,a=p[h],p[h]=p[o],p[o]=a,e=n[o],l=o;l!==f;++l)n[l]/=e;for(l=f-1;l!==-1;--l)a[l]/=e;for(i=c-1;i!==-1;--i)if(i!==o){for(t=d[i],r=p[i],e=t[o],l=o+1;l!==f;++l)t[l]-=n[l]*e;for(l=f-1;l>0;--l)r[l]-=a[l]*e,--l,r[l]-=a[l]*e;0===l&&(r[0]-=a[0]*e)}}return p},numeric.det=function(e){var t=numeric.dim(e);if(2!==t.length||t[0]!==t[1])throw new Error("numeric: det() only works on square matrices");var n,r,a,i,o,l,s,u,c=t[0],f=1,d=numeric.clone(e);for(r=0;rMath.abs(d[a][r])&&(a=n);for(a!==r&&(s=d[a],d[a]=d[r],d[r]=s,f*=-1),i=d[r],n=r+1;n=1;t-=2){for(a=e[t],r=e[t-1],n=l-1;n>=1;--n)i=s[n],i[t]=a[n],i[t-1]=r[n],--n,i=s[n],i[t]=a[n],i[t-1]=r[n];0===n&&(i=s[0],i[t]=a[0],i[t-1]=r[0])}if(0===t){for(r=e[0],n=l-1;n>=1;--n)s[n][0]=r[n],--n,s[n][0]=r[n];0===n&&(s[0][0]=r[0])}return s},numeric.negtranspose=function(e){var t,n,r,a,i,o=e.length,l=e[0].length,s=Array(l);for(n=0;n=1;t-=2){for(a=e[t],r=e[t-1],n=l-1;n>=1;--n)i=s[n],i[t]=-a[n],i[t-1]=-r[n],--n,i=s[n],i[t]=-a[n],i[t-1]=-r[n];0===n&&(i=s[0],i[t]=-a[0],i[t-1]=-r[0])}if(0===t){for(r=e[0],n=l-1;n>=1;--n)s[n][0]=-r[n],--n,s[n][0]=-r[n];0===n&&(s[0][0]=-r[0])}return s},numeric._random=function e(t,n){var r,a,i=t[n],o=Array(i);if(n===t.length-1){for(a=Math.random,r=i-1;r>=1;r-=2)o[r]=a(),o[r-1]=a();return 0===r&&(o[0]=a()),o}for(r=i-1;r>=0;r--)o[r]=e(t,n+1);return o},numeric.random=function(e){return numeric._random(e,0)},numeric.norm2=function(e){return Math.sqrt(numeric.norm2Squared(e))},numeric.linspace=function(e,t,n){if("undefined"==typeof n&&(n=Math.max(Math.round(t-e)+1,1)),n<2)return 1===n?[e]:[];var r,a=Array(n);for(n--,r=n;r>=0;r--)a[r]=(r*t+(n-r)*e)/n;return a},numeric.getBlock=function(e,t,n){function r(e,i){var o,l=t[i],s=n[i]-l,u=Array(s);if(i===a.length-1){for(o=s;o>=0;o--)u[o]=e[o+l];return u}for(o=s;o>=0;o--)u[o]=r(e[o+l],i+1);return u}var a=numeric.dim(e);return r(e,0)},numeric.setBlock=function(e,t,n,r){function a(e,r,o){var l,s=t[o],u=n[o]-s;if(o===i.length-1)for(l=u;l>=0;l--)e[l+s]=r[l];for(l=u;l>=0;l--)a(e[l+s],r[l],o+1)}var i=numeric.dim(e);return a(e,r,0),e},numeric.getRange=function(e,t,n){var r,a,i,o,l=t.length,s=n.length,u=Array(l);for(r=l-1;r!==-1;--r)for(u[r]=Array(s),i=u[r],o=e[t[r]],a=s-1;a!==-1;--a)i[a]=o[n[a]];return u},numeric.blockMatrix=function(e){var t=numeric.dim(e);if(t.length<4)return numeric.blockMatrix([e]);var n,r,a,i,o,l=t[0],s=t[1];for(n=0,r=0,a=0;a=0;i--){for(a=Array(u),l=e[i],o=u-1;o>=3;--o)a[o]=l*t[o],--o,a[o]=l*t[o],--o,a[o]=l*t[o],--o,a[o]=l*t[o];for(;o>=0;)a[o]=l*t[o],--o;c[i]=a}return c},numeric.T=function(e,t){this.x=e,this.y=t},numeric.t=function(e,t){return new numeric.T(e,t)},numeric.Tbinop=function(e,t,n,r,a){numeric.indexOf;if("string"!=typeof a){var i;a="";for(i in numeric)numeric.hasOwnProperty(i)&&(e.indexOf(i)>=0||t.indexOf(i)>=0||n.indexOf(i)>=0||r.indexOf(i)>=0)&&i.length>1&&(a+="var "+i+" = numeric."+i+";\n")}return Function(["y"],"var x = this;\nif(!(y instanceof numeric.T)) { y = new numeric.T(y); }\n"+a+"\nif(x.y) { if(y.y) { return new numeric.T("+r+");\n }\n return new numeric.T("+n+");\n}\nif(y.y) {\n return new numeric.T("+t+");\n}\nreturn new numeric.T("+e+");\n")},numeric.T.prototype.add=numeric.Tbinop("add(x.x,y.x)","add(x.x,y.x),y.y","add(x.x,y.x),x.y","add(x.x,y.x),add(x.y,y.y)"),numeric.T.prototype.sub=numeric.Tbinop("sub(x.x,y.x)","sub(x.x,y.x),neg(y.y)","sub(x.x,y.x),x.y","sub(x.x,y.x),sub(x.y,y.y)"),numeric.T.prototype.mul=numeric.Tbinop("mul(x.x,y.x)","mul(x.x,y.x),mul(x.x,y.y)","mul(x.x,y.x),mul(x.y,y.x)","sub(mul(x.x,y.x),mul(x.y,y.y)),add(mul(x.x,y.y),mul(x.y,y.x))"),numeric.T.prototype.reciprocal=function(){var e=numeric.mul,t=numeric.div;if(this.y){var n=numeric.add(e(this.x,this.x),e(this.y,this.y));return new numeric.T(t(this.x,n),t(numeric.neg(this.y),n))}return new T(t(1,this.x))},numeric.T.prototype.div=function e(t){if(t instanceof numeric.T||(t=new numeric.T(t)),t.y)return this.mul(t.reciprocal());var e=numeric.div;return this.y?new numeric.T(e(this.x,t.x),e(this.y,t.x)):new numeric.T(e(this.x,t.x))},numeric.T.prototype.dot=numeric.Tbinop("dot(x.x,y.x)","dot(x.x,y.x),dot(x.x,y.y)","dot(x.x,y.x),dot(x.y,y.x)","sub(dot(x.x,y.x),dot(x.y,y.y)),add(dot(x.x,y.y),dot(x.y,y.x))"),numeric.T.prototype.transpose=function(){var e=numeric.transpose,t=this.x,n=this.y;return n?new numeric.T(e(t),e(n)):new numeric.T(e(t))},numeric.T.prototype.transjugate=function(){var e=numeric.transpose,t=this.x,n=this.y;return n?new numeric.T(e(t),numeric.negtranspose(n)):new numeric.T(e(t))},numeric.Tunop=function(e,t,n){return"string"!=typeof n&&(n=""),Function("var x = this;\n"+n+"\nif(x.y) { "+t+";\n}\n"+e+";\n")},numeric.T.prototype.exp=numeric.Tunop("return new numeric.T(ex)","return new numeric.T(mul(cos(x.y),ex),mul(sin(x.y),ex))","var ex = numeric.exp(x.x), cos = numeric.cos, sin = numeric.sin, mul = numeric.mul;"),numeric.T.prototype.conj=numeric.Tunop("return new numeric.T(x.x);","return new numeric.T(x.x,numeric.neg(x.y));"),numeric.T.prototype.neg=numeric.Tunop("return new numeric.T(neg(x.x));","return new numeric.T(neg(x.x),neg(x.y));","var neg = numeric.neg;"),numeric.T.prototype.sin=numeric.Tunop("return new numeric.T(numeric.sin(x.x))","return x.exp().sub(x.neg().exp()).div(new numeric.T(0,2));"),numeric.T.prototype.cos=numeric.Tunop("return new numeric.T(numeric.cos(x.x))","return x.exp().add(x.neg().exp()).div(2);"),numeric.T.prototype.abs=numeric.Tunop("return new numeric.T(numeric.abs(x.x));","return new numeric.T(numeric.sqrt(numeric.add(mul(x.x,x.x),mul(x.y,x.y))));","var mul = numeric.mul;"),numeric.T.prototype.log=numeric.Tunop("return new numeric.T(numeric.log(x.x));","var theta = new numeric.T(numeric.atan2(x.y,x.x)), r = x.abs();\nreturn new numeric.T(numeric.log(r.x),theta.x);"),numeric.T.prototype.norm2=numeric.Tunop("return numeric.norm2(x.x);","var f = numeric.norm2Squared;\nreturn Math.sqrt(f(x.x)+f(x.y));"),numeric.T.prototype.inv=function(){var e=this;if("undefined"==typeof e.y)return new numeric.T(numeric.inv(e.x));var t,n,r,a,i,o,l,s,u,c,f,t,n,r,d,p,h,v,g,m,y,x=e.x.length,b=numeric.identity(x),w=numeric.rep([x,x],0),_=numeric.clone(e.x),k=numeric.clone(e.y);for(t=0;td&&(r=n,d=p);for(r!==t&&(y=_[t],_[t]=_[r],_[r]=y,y=k[t],k[t]=k[r],k[r]=y,y=b[t],b[t]=b[r],b[r]=y,y=w[t],w[t]=w[r],w[r]=y),a=_[t],i=k[t],s=b[t],u=w[t],h=a[t],v=i[t],n=t+1;n0;t--)for(s=b[t],u=w[t],n=t-1;n>=0;n--)for(c=b[n],f=w[n],h=_[n][t],v=k[n][t],r=x-1;r>=0;r--)g=s[r],m=u[r],c[r]-=h*g-v*m,f[r]-=h*m+v*g;return new numeric.T(b,w)},numeric.T.prototype.get=function(e){var t,n=this.x,r=this.y,a=0,i=e.length;if(r){for(;a=0?1:-1,r=n*numeric.norm2(e);t[0]+=r;var a=numeric.norm2(t);if(0===a)throw new Error("eig: internal error");return numeric.div(t,a)},numeric.toUpperHessenberg=function(e){var t=numeric.dim(e);if(2!==t.length||t[0]!==t[1])throw new Error("numeric: toUpperHessenberg() only works on square matrices");var n,r,a,i,o,l,s,u,c,f,d=t[0],p=numeric.clone(e),h=numeric.identity(d);for(r=0;r0){for(o=numeric.house(i),l=numeric.getBlock(p,[r+1,r],[d-1,d-1]),s=numeric.tensor(o,numeric.dot(o,l)),n=r+1;n=4*s){var A,j;A=.5*(u+Math.sqrt(u*u-4*s)),j=.5*(u-Math.sqrt(u*u-4*s)),c=numeric.add(numeric.sub(numeric.dot(c,c),numeric.mul(c,A+j)),numeric.diag(numeric.rep([3],A*j)))}else c=numeric.add(numeric.sub(numeric.dot(c,c),numeric.mul(c,u)),numeric.diag(numeric.rep([3],s)));for(n=[c[0][0],c[1][0],c[2][0]],r=numeric.house(n),p=[e[0],e[1],e[2]],h=numeric.tensor(r,numeric.dot(r,p)),g=0;g<3;g++)for(d=e[g],v=h[g],y=0;y=0?(p=c<0?-.5*(c-j(d)):-.5*(c+j(d)),m=(o-p)*(o-p)+l*l,y=s*s+(u-p)*(u-p),m>y?(m=j(m),v=(o-p)/m,g=l/m):(y=j(y),v=s/y,g=(u-p)/y),a=new w([[g,-v],[v,g]]),M.setRows(n,i,a.dot(M.getRows(n,i)))):(p=-.5*c,h=.5*j(-d),m=(o-p)*(o-p)+l*l,y=s*s+(u-p)*(u-p),m>y?(m=j(m+h*h),v=(o-p)/m,g=l/m,p=0,h/=m):(y=j(y+h*h),v=s/y,g=(u-p)/y,p=h/y,h=0),a=new w([[g,-v],[v,g]],[[p,h],[h,-p]]),M.setRows(n,i,a.dot(M.getRows(n,i))))}var E=M.dot(e).dot(M.transjugate()),_=e.length,S=numeric.T.identity(_);for(i=0;i<_;i++)if(i>0)for(r=i-1;r>=0;r--){var O=E.get([r,r]),N=E.get([i,i]);numeric.neq(O.x,N.x)||numeric.neq(O.y,N.y)?(p=E.getRow(r).getBlock([r],[i-1]),h=S.getRow(i).getBlock([r],[i-1]),S.set([i,r],E.get([r,i]).neg().sub(p.dot(h)).div(O.sub(N)))):S.setRow(i,S.getRow(r))}for(i=0;i<_;i++)p=S.getRow(i),S.setRow(i,p.div(p.norm2()));return S=S.transpose(),S=M.transjugate().dot(S),{lambda:E.getDiag(),E:S}},numeric.ccsSparse=function(e){var t,n,r,a,i=e.length,o=[];for(r=i-1;r!==-1;--r){n=e[r];for(a in n){for(a=parseInt(a);a>=o.length;)o[o.length]=0;0!==n[a]&&o[a]++}}var t=o.length,l=Array(t+1);for(l[0]=0,r=0;r=s){if(a[c]=p[u],0===u)return;++c,--u,l=f[u],s=d[u]}else o=i[n[l]],0===r[o]?(r[o]=1,f[u]=l,++u,p[u]=o,l=t[o],d[u]=s=t[o+1]):++l},numeric.ccsLPSolve=function(e,t,n,r,a,i,o){var l,s,u,c,f,d,p,h,v,g=e[0],m=e[1],y=e[2],x=(g.length-1,t[0]),b=t[1],w=t[2];for(s=x[a],u=x[a+1],r.length=0,l=s;li&&(o=a,i=l));for(w(y[n])=u){if(a[f]=i[h[c]],0===c)return;++f,--c,s=d[c],u=p[c]}else l=n[s],0===r[l]?(r[l]=1,d[c]=s,++c,h[c]=l,l=i[l],s=t[l],p[c]=u=t[l+1]):++s}},numeric.ccsLPSolve0=function(e,t,n,r,a,i,o,l){var s,u,c,f,d,p,h,v,g,m=e[0],y=e[1],x=e[2],b=(m.length-1,t[0]),w=t[1],_=t[2];for(u=b[a],c=b[a+1],r.length=0,s=u;si&&(o=a,i=l));for(w(y[_[n]])n[r]&&(n[r]=t.length);var a;for(a in t)t.hasOwnProperty(a)&&e(t[a],n,r+1);return n},numeric.sclone=function e(t,n,r){"undefined"==typeof n&&(n=0),"undefined"==typeof r&&(r=numeric.sdim(t).length);var a,i=Array(t.length);if(n===r-1){for(a in t)t.hasOwnProperty(a)&&(i[a]=t[a]);return i}for(a in t)t.hasOwnProperty(a)&&(i[a]=e(t[a],n+1,r));return i},numeric.sdiag=function(e){var t,n,r=e.length,a=Array(r);for(t=r-1;t>=1;t-=2)n=t-1,a[t]=[],a[t][t]=e[t],a[n]=[],a[n][n]=e[n];return 0===t&&(a[0]=[],a[0][0]=e[t]),a},numeric.sidentity=function(e){return numeric.sdiag(numeric.rep([e],1))},numeric.stranspose=function(e){var t,n,r,a=[];e.length;for(t in e)if(e.hasOwnProperty(t)){r=e[t];for(n in r)r.hasOwnProperty(n)&&("object"!=typeof a[n]&&(a[n]=[]),a[n][t]=r[n])}return a},numeric.sLUP=function(e,t){throw new Error("The function numeric.sLUP had a bug in it and has been removed. Please use the new numeric.ccsLUP function instead.")},numeric.sdotMM=function(e,t){var n,r,a,i,o,l,s,u=e.length,c=(t.length,numeric.stranspose(t)),f=c.length,d=Array(u);for(a=u-1;a>=0;a--){for(s=[],n=e[a],o=f-1;o>=0;o--){l=0,r=c[o];for(i in n)n.hasOwnProperty(i)&&i in r&&(l+=n[i]*r[i]);l&&(s[o]=l)}d[a]=s}return d},numeric.sdotMV=function(e,t){var n,r,a,i,o=e.length,l=Array(o);for(r=o-1;r>=0;r--){n=e[r],i=0;for(a in n)n.hasOwnProperty(a)&&t[a]&&(i+=n[a]*t[a]);i&&(l[r]=i)}return l},numeric.sdotVM=function(e,t){var n,r,a,i,o=[];for(n in e)if(e.hasOwnProperty(n)){a=t[n],i=e[n];for(r in a)a.hasOwnProperty(r)&&(o[r]||(o[r]=0),o[r]+=i*a[r])}return o},numeric.sdotVV=function(e,t){var n,r=0;for(n in e)e[n]&&t[n]&&(r+=e[n]*t[n]);return r},numeric.sdot=function(e,t){var n=numeric.sdim(e).length,r=numeric.sdim(t).length,a=1e3*n+r;switch(a){case 0:return e*t;case 1001:return numeric.sdotVV(e,t);case 2001:return numeric.sdotMV(e,t);case 1002:return numeric.sdotVM(e,t);case 2002:return numeric.sdotMM(e,t);default:throw new Error("numeric.sdot not implemented for tensors of order "+n+" and "+r)}},numeric.sscatter=function(e){var t,n,r,a,i=e[0].length,o=e.length,l=[];for(n=i-1;n>=0;--n)if(e[o-1][n]){for(a=l,r=0;r=0;--i)n[i]=[];for(i=a;i>=0;--i)n[i].push(r[i]);n[a+1].push(o)}}else e(o,n,r);return r.length>a&&r.pop(),n},numeric.cLU=function(e){var t,n,r,a,i,o,l=e[0],s=e[1],u=e[2],c=l.length,f=0;for(t=0;tf&&(f=l[t]);f++;var d,p,h,v=Array(f),g=Array(f),m=numeric.rep([f],1/0),y=numeric.rep([f],-(1/0));for(r=0;ry[t]&&(y[t]=n);for(t=0;ty[t+1]&&(y[t+1]=y[t]);for(t=f-1;t>=1;t--)m[t]=0;n--){for(;f[r]>n;)o[n]-=d[r]*o[f[r]],r--;o[n]/=d[r],r--}return o},numeric.cgrid=function(e,t){"number"==typeof e&&(e=[e,e]);var n,r,a,i=numeric.rep(e,-1);if("function"!=typeof t)switch(t){case"L":t=function(t,n){return t>=e[0]/2||na&&(a=i[r]);for(a++,n=numeric.rep([a],0),r=0;r1;)r=o((t+n)/2),a[r]<=e?t=r:n=r;return this._at(e,t)}var l,i=e.length,s=Array(i); +for(l=i-1;l!==-1;--l)s[l]=this.at(e[l]);return s},numeric.Spline.prototype.diff=function(){var e,t,n,r=this.x,a=this.yl,i=this.yr,o=this.kl,l=this.kr,s=a.length,u=o,c=l,f=Array(s),d=Array(s),p=numeric.add,h=numeric.mul,v=numeric.div,g=numeric.sub;for(e=s-1;e!==-1;--e)t=r[e+1]-r[e],n=g(i[e+1],a[e]),f[e]=v(p(h(n,6),h(o[e],-4*t),h(l[e+1],-2*t)),t*t),d[e+1]=v(p(h(n,-6),h(o[e],2*t),h(l[e+1],4*t)),t*t);return new numeric.Spline(r,u,c,f,d)},numeric.Spline.prototype.roots=function(){function e(e){return e*e}var t=[],n=this.x,r=this.yl,a=this.yr,i=this.kl,o=this.kr;"number"==typeof r[0]&&(r=[r],a=[a],i=[i],o=[o]);var l,s,u,c,f,d,p,h,v,g,m,y,x,b,w,_,k,z,M,A,j,E,S,O,N=r.length,F=n.length-1,t=Array(N),C=Math.sqrt;for(l=0;l!==N;++l){for(c=r[l],f=a[l],d=i[l],p=o[l],h=[],s=0;s!==F;s++){for(s>0&&f[s]*c[s]<0&&h.push(n[s]),_=n[s+1]-n[s],k=n[s],m=c[s],y=f[s+1],v=d[s]/_,g=p[s+1]/_,w=e(v-g+3*(m-y))+12*g*m,x=g+3*m+2*v-3*y,b=3*(g+v+2*(m-y)),w<=0?(M=x/b,z=M>n[s]&&Mn[s]&&Mn[s]&&A0)E=S,M=A;else{for(var T=0;;){if(O=(M*S-A*E)/(M-A),O<=E||O>=S)break;if(j=this._at(O,s),j*A>0)S=O,A=j,T===-1&&(M*=.5),T=-1;else{if(!(j*M>0))break;E=O,M=j,1===T&&(A*=.5),T=1}}h.push(O),E=z[u+1],M=this._at(E,s)}else h.push(E),E=S,M=A;0===A&&h.push(S)}t[l]=h}return"number"==typeof this.yl[0]?t[0]:t},numeric.spline=function(e,t,n,r){var a,i=e.length,o=[],l=[],s=[],u=numeric.sub,c=numeric.mul,f=numeric.add;for(a=i-2;a>=0;a--)l[a]=e[a+1]-e[a],s[a]=u(t[a+1],t[a]);"string"!=typeof n&&"string"!=typeof r||(n=r="periodic");var d=[[],[],[]];switch(typeof n){case"undefined":o[0]=c(3/(l[0]*l[0]),s[0]),d[0].push(0,0),d[1].push(0,1),d[2].push(2/l[0],1/l[0]);break;case"string":o[0]=f(c(3/(l[i-2]*l[i-2]),s[i-2]),c(3/(l[0]*l[0]),s[0])),d[0].push(0,0,0),d[1].push(i-2,0,1),d[2].push(1/l[i-2],2/l[i-2]+2/l[0],1/l[0]);break;default:o[0]=n,d[0].push(0),d[1].push(0),d[2].push(1)}for(a=1;a20)throw new Error("Numerical gradient fails");if(v[a]=t[a]+w,i=e(v),v[a]=t[a]-w,o=e(v),v[a]=t[a],isNaN(i)||isNaN(o))w/=16;else{if(g[a]=(i-o)/(2*w),s=t[a]-w,u=t[a],c=t[a]+w,f=(i-r)/w,d=(r-o)/w,p=h(y(g[a]),y(r),y(i),y(o),y(s),y(u),y(c),1e-8),l=x(h(y(f-g[a]),y(d-g[a]),y(f-d))/p,w/p),!(l>m))break;w/=16}}return g},numeric.uncmin=function(e,t,n,r,a,i,o){var l=numeric.gradient;"undefined"==typeof o&&(o={}),"undefined"==typeof n&&(n=1e-8),"undefined"==typeof r&&(r=function(t){return l(e,t)}),"undefined"==typeof a&&(a=1e3),t=numeric.clone(t);var s,u,c=t.length,f=e(t);if(isNaN(f))throw new Error("uncmin: f(x0) is a NaN!");var d=Math.max,p=numeric.norm2;n=d(n,numeric.epsilon);var h,v,g,m,y,x,b,w,_,k,z=o.Hinv||numeric.identity(c),M=numeric.dot,A=(numeric.inv,numeric.sub),j=numeric.add,E=numeric.tensor,S=numeric.div,O=numeric.mul,N=numeric.all,F=numeric.isFinite,C=numeric.neg,T=0,q="";for(v=r(t);T=.1*_*u||isNaN(s));)_*=.5,++T;if(_*k1;)r=a(.5*(t+n)),l[r]<=e?t=r:n=r;return this._at(e,t)},numeric.dopri=function(e,t,n,r,a,i,o){"undefined"==typeof a&&(a=1e-6),"undefined"==typeof i&&(i=1e3);var l,s,u,c,f,d,p,h,v,g,m,y,x,b=[e],w=[n],_=[r(e,n)],k=[],z=.2,M=[.075,.225],A=[44/45,-56/15,32/9],j=[19372/6561,-25360/2187,64448/6561,-212/729],E=[9017/3168,-355/33,46732/5247,49/176,-5103/18656],S=[35/384,0,500/1113,125/192,-2187/6784,11/84],O=[.10013431883002395,0,.3918321794184259,-.02982460176594817,.05893268337240795,-.04497888809104361,.023904308236133973],N=[.2,.3,.8,8/9,1,1],F=[-71/57600,0,71/16695,-71/1920,17253/339200,-22/525,.025],C=0,T=(t-e)/10,q=0,P=numeric.add,B=numeric.mul,D=(Math.max,Math.min),R=Math.abs,I=numeric.norminf,L=Math.pow,V=numeric.any,U=numeric.lt,Y=numeric.and,H=(numeric.sub,new numeric.Dopri(b,w,_,k,(-1),""));for("function"==typeof o&&(m=o(e,n));et&&(T=t-e),l=r(e+N[0]*T,P(n,B(z*T,_[C]))),s=r(e+N[1]*T,P(P(n,B(M[0]*T,_[C])),B(M[1]*T,l))),u=r(e+N[2]*T,P(P(P(n,B(A[0]*T,_[C])),B(A[1]*T,l)),B(A[2]*T,s))),c=r(e+N[3]*T,P(P(P(P(n,B(j[0]*T,_[C])),B(j[1]*T,l)),B(j[2]*T,s)),B(j[3]*T,u))),f=r(e+N[4]*T,P(P(P(P(P(n,B(E[0]*T,_[C])),B(E[1]*T,l)),B(E[2]*T,s)),B(E[3]*T,u)),B(E[4]*T,c))),v=P(P(P(P(P(n,B(_[C],T*S[0])),B(s,T*S[2])),B(u,T*S[3])),B(c,T*S[4])),B(f,T*S[5])),d=r(e+T,v),p=P(P(P(P(P(B(_[C],T*F[0]),B(s,T*F[2])),B(u,T*F[3])),B(c,T*F[4])),B(f,T*F[5])),B(d,T*F[6])),g="number"==typeof p?R(p):I(p),g>a){if(T=.2*T*L(a/g,.25),e+T===e){H.msg="Step size became too small";break}}else{if(k[C]=P(P(P(P(P(P(n,B(_[C],T*O[0])),B(s,T*O[2])),B(u,T*O[3])),B(c,T*O[4])),B(f,T*O[5])),B(d,T*O[6])),++C,b[C]=e+T,w[C]=v,_[C]=d,"function"==typeof o){var X,G,Z=e,W=e+.5*T;if(y=o(W,k[C-1]),x=Y(U(m,0),U(0,y)),V(x)||(Z=W,W=e+T,m=y,y=o(W,v),x=Y(U(m,0),U(0,y))),V(x)){for(var J,Q,K=0,$=1,ee=1;;){if("number"==typeof m)G=(ee*y*Z-$*m*W)/(ee*y-$*m);else for(G=W,h=m.length-1;h!==-1;--h)m[h]<0&&y[h]>0&&(G=D(G,(ee*y[h]*Z-$*m[h]*W)/(ee*y[h]-$*m[h])));if(G<=Z||G>=W)break;X=H._at(G,C-1),Q=o(G,X),J=Y(U(m,0),U(0,Q)),V(J)?(W=G,y=Q,x=J,ee=1,K===-1?$*=.5:$=1,K=-1):(Z=G,m=Q,$=1,1===K?ee*=.5:ee=1,K=1)}return v=H._at(.5*(e+G),C-1),H.f[C]=r(G,X),H.x[C]=G,H.y[C]=X,H.ymid[C-1]=v,H.events=x,H.iterations=q,H}}e+=T,n=v,m=y,T=D(.8*T*L(a/g,.25),4*T)}return H.iterations=q,H},numeric.LU=function(e,t){t=t||!1;var n,r,a,i,o,l,s,u,c,f=Math.abs,d=e.length,p=d-1,h=new Array(d);for(t||(e=numeric.clone(e)),a=0;a=0;--n){for(i=l[n],r=n+1;rP)&&(w=P),c=g(e,d(w,E)),s=h(q,S),C=m-1;C!==-1;--C)s[C][C]+=1;T=O(s,v(c,w),!0);var B=v(N,h(t,T)),D=1;for(C=y-1;C!==-1;--C)B[C]<0&&(D=M(D,-.999*B[C]));if(l=p(i,d(T,D)),N=p(n,h(t,l)),!A(j(N,0)))return{solution:i,message:"",iterations:u};if(i=l,w=0);if(x)return{solution:l,message:"Unbounded",iterations:u}}return{solution:i,message:"maximum iteration count exceeded",iterations:u}},numeric._solveLP=function(e,t,n,r,a){var i,o=e.length,l=n.length,s=(numeric.sum,numeric.log,numeric.mul,numeric.sub),u=numeric.dot,c=(numeric.div,numeric.add,numeric.rep([o],0).concat([1])),f=numeric.rep([l,1],-1),d=numeric.blockMatrix([[t,f]]),p=n,i=numeric.rep([o],0).concat(Math.max(0,numeric.sup(numeric.neg(n)))+1),h=numeric.__solveLP(c,d,p,r,a,i,!1),v=numeric.clone(h.solution);v.length=o;var g=numeric.inf(s(n,u(t,v)));if(g<0)return{solution:NaN,message:"Infeasible",iterations:h.iterations};var m=numeric.__solveLP(e,t,n,r,a-h.iterations,v,!0);return m.iterations+=h.iterations,m},numeric.solveLP=function(e,t,n,r,a,i,o){if("undefined"==typeof o&&(o=1e3),"undefined"==typeof i&&(i=numeric.epsilon),"undefined"==typeof r)return numeric._solveLP(e,t,n,i,o);var l,s=r.length,u=r[0].length,c=t.length,f=numeric.echelonize(r),d=numeric.rep([u],0),p=f.P,h=[];for(l=p.length-1;l!==-1;--l)d[p[l]]=1;for(l=u-1;l!==-1;--l)0===d[l]&&h.push(l);var v=numeric.getRange,g=numeric.linspace(0,s-1),m=numeric.linspace(0,c-1),y=v(r,g,h),x=v(t,m,p),b=v(t,m,h),w=numeric.dot,_=numeric.sub,k=w(x,f.I),z=_(b,w(k,y)),M=_(n,w(k,a)),A=Array(p.length),j=Array(h.length);for(l=p.length-1;l!==-1;--l)A[l]=e[p[l]];for(l=h.length-1;l!==-1;--l)j[l]=e[h[l]];var E=_(j,w(A,w(f.I,y))),S=numeric._solveLP(E,z,M,i,o),O=S.solution;if(O!==O)return S;var N=w(f.I,_(a,w(y,O))),F=Array(e.length);for(l=p.length-1;l!==-1;--l)F[p[l]]=N[l];for(l=h.length-1;l!==-1;--l)F[h[l]]=O[l];return{solution:F,message:S.message,iterations:S.iterations}},numeric.MPStoLP=function(e){function t(t){throw new Error("MPStoLP: "+t+"\nLine "+n+": "+e[n]+"\nCurrent state: "+l[o]+"\n")}e instanceof String&&e.split("\n");var n,r,a,i,o=0,l=["Initial state","NAME","ROWS","COLUMNS","RHS","BOUNDS","ENDATA"],s=e.length,u=0,c={},f=[],d=0,p={},h=0,v=[],g=[],m=[];for(n=0;n=i;)e/=2,t/=2,l>>>=1;return(e+l)/t},c},o=t.pow(n,r),a=t.pow(2,a),i=2*a,u(t.random(),e)}([],numeric.seedrandom,256,6,52),function(e){function t(e){if("object"!=typeof e)return e;var n,r=[],a=e.length;for(n=0;np)m[A]=R;else if(m[A]=-Math.abs(R),R>0){for(M=1;M<=o;M+=1)u[M][z]=-u[M][z];c[z]=-c[z]}}for(z=1;z<=v;z+=1)m[C+h[z]]=0;for(q=0,D=0,z=1;z<=d;z+=1)m[C+z]=1;z-=1){for(R=m[z],A=F+z*(z+3)/2,j=A-z,M=z+1;M<=v;M+=1)R-=m[A]*m[N+M],A+=M;if(R/=m[j],m[N+z]=R,h[z]p)m[C+q]=R;else if(m[C+q]=-Math.abs(R),R>0){for(M=1;M<=o;M+=1)u[M][q]=-u[M][q];c[q]=-c[q]}return 700}for(v+=1,h[v]=q,A=F+(v-1)*v/2+1,z=1;z<=v-1;z+=1)m[A]=m[z],A+=1;if(v===o)m[A]=m[o];else{for(z=o;z>=v+1&&0!==m[z]&&(V=Math.max(Math.abs(m[z-1]),Math.abs(m[z])),U=Math.min(Math.abs(m[z-1]),Math.abs(m[z])),D=m[z-1]>=0?Math.abs(V*Math.sqrt(1+U*U/(V*V))):-Math.abs(V*Math.sqrt(1+U*U/(V*V))),V=m[z-1]/D,U=m[z]/D,1!==V);z-=1)if(0===V)for(m[z-1]=U*D,M=1;M<=o;M+=1)D=e[M][z-1],e[M][z-1]=e[M][z],e[M][z]=D;else for(m[z-1]=D,Y=U/(1+V),M=1;M<=o;M+=1)D=V*e[M][z-1]+U*e[M][z],e[M][z]=Y*(e[M][z-1]+D)-e[M][z],e[M][z-1]=D;m[A]=m[v]}return 0}function w(){if(A=F+S*(S+1)/2+1,j=A+S,0===m[j])return 798;if(V=Math.max(Math.abs(m[j-1]),Math.abs(m[j])),U=Math.min(Math.abs(m[j-1]),Math.abs(m[j])),D=m[j-1]>=0?Math.abs(V*Math.sqrt(1+U*U/(V*V))):-Math.abs(V*Math.sqrt(1+U*U/(V*V))),V=m[j-1]/D,U=m[j]/D,1===V)return 798;if(0===V){for(z=S+1;z<=v;z+=1)D=m[j-1],m[j-1]=m[j],m[j]=D,j+=z;for(z=1;z<=o;z+=1)D=e[z][S],e[z][S]=e[z][S+1],e[z][S+1]=D}else{for(Y=U/(1+V),z=S+1;z<=v;z+=1)D=V*m[j-1]+U*m[j],m[j]=Y*(m[j-1]+D)-m[j],m[j-1]=D,j+=z;for(z=1;z<=o;z+=1)D=V*e[z][S]+U*e[z][S+1],e[z][S+1]=Y*(e[z][S]+D)-e[z][S+1],e[z][S]=D}return 0}function _(){for(j=A-S,z=1;z<=S;z+=1)m[j]=m[A],A+=1,j+=1;return m[T+S]=m[T+S+1],h[S]=h[S+1],S+=1,St?e*Math.sqrt(1+t*t/e/e):0==t?e:t*Math.sqrt(1+e*e/t/t)}var n,r=numeric.epsilon,a=1e-64/r,i=50,o=0,l=0,s=0,u=0,c=0,f=numeric.clone(e),d=f.length,p=f[0].length;if(d=0&&(y=-y),x=m*y-k,f[l][l]=m-y,s=c;s=0&&(y=-y),x=m*y-k,f[l][l+1]=m-y,s=c;sb&&(b=w)}for(l=p-1;l!=-1;l+=-1){if(0!=y){for(x=y*f[l][l+1],s=c;s=i-1)throw"Error: no convergence.";for(b=v[c],w=v[u-1],y=h[u-1],x=h[u],m=((w-_)*(w+_)+(y-x)*(y+x))/(2*x*w),y=t(m,1),m=m<0?((b-_)*(b+_)+x*(w/(m-y)-x))/b:((b-_)*(b+_)+x*(w/(m+y)-x))/b,o=1,k=1,l=c+1;l=0;s--)if(v[s]1?(r=n.x,a=n.y):l>0&&(r+=i*l,a+=o*l)}return i=e.x-r,o=e.y-a,i*i+o*o}function r(t,n){for(var r,a=t[0],i=[a],o=1,l=t.length;on&&(i.push(r),a=r);return a!==r&&i.push(r),i}function a(e,t){var r,a,i,o,l=e.length,s="undefined"!=typeof Uint8Array?Uint8Array:Array,u=new s(l),c=0,f=l-1,d=[],p=[];for(u[c]=u[f]=1;f;){for(a=0,r=c+1;ra&&(o=r,a=i);a>t&&(u[o]=1,d.push(c,o,o,f)),f=d.pop(),c=d.pop()}for(r=0;r1){var M,A=p.log2(m+1)%n,j=d.root(z);M=b(k,j,function(e,t){return e.get(A)-t.get(A)});for(var E=v.index(m,0),S=M.offset,h=0;h2&&w.push(k.lo(j+1))}else{for(var S=k.offset,E=v.index(m,0),h=0;h0?{p:Array.prototype.slice.call(this.points.data,0,this.length*this.dimension),i:Array.prototype.slice.call(this.ids,0,this.length)}:{d:this.dimension}},v.range=function(e,t,n){var r=this.length;if(!(r<1)){for(var a=this.dimension,i=0;i0&&!(u[0]>=v);){for(var g=s[0],m=a.index(g,0),y=0,c=0;c0&&!(m[0]>=x);){for(var b=g[0],w=o.index(b,0),_=0,y=0;y=t&&u.pop();var k=u.count;c[k]=b,d[k]=-_,u.push(),u.count>=t&&(x=-d[0])}for(var z=p.log2(b+1)%i,M=0,y=0;y=0;--y)D[y]=a[c[0]],u.pop();return u.dispose(),D},v.dispose=function(){f.free(this.points.data),f.freeInt32(this.ids),this.points=null,this.ids=null,this.length=0}},{"./lib/heap.js":11,"bit-twiddle":12,"inorder-tree-layout":13,ndarray:28,"ndarray-ops":15,"ndarray-pack":20,"ndarray-scratch":26,"ndarray-select":27,"typedarray-pool":32}],11:[function(e,t,n){"use strict";function r(e){return 1&e?e-1>>1:(e>>1)-1}function a(e,t){this.count=0,this.dataSize=t,this.index=i.mallocInt32(e),this.data=i.mallocFloat64(e*t)}t.exports=a;var i=e("typedarray-pool"),o=a.prototype;o.heapSwap=function(e,t){var n=this.data,r=this.index,a=this.dataSize,i=r[e];r[e]=r[t],r[t]=i;for(var o=a*e,l=a*t,s=0;s0;){var i=r(e);if(i>=0){var o=n[t*i];if(a0)-(e<0)},n.abs=function(e){var t=e>>a-1;return(e^t)-t},n.min=function(e,t){return t^(e^t)&-(e65535)<<4,e>>>=t,n=(e>255)<<3,e>>>=n,t|=n,n=(e>15)<<2,e>>>=n,t|=n,n=(e>3)<<1,e>>>=n,t|=n,t|e>>1},n.log10=function(e){return e>=1e9?9:e>=1e8?8:e>=1e7?7:e>=1e6?6:e>=1e5?5:e>=1e4?4:e>=1e3?3:e>=100?2:e>=10?1:0},n.popCount=function(e){return e-=e>>>1&1431655765,e=(858993459&e)+(e>>>2&858993459),16843009*(e+(e>>>4)&252645135)>>>24},n.countTrailingZeros=r,n.nextPow2=function(e){return e+=0===e,--e,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e+1},n.prevPow2=function(e){return e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e-(e>>>1)},n.parity=function(e){return e^=e>>>16,e^=e>>>8,e^=e>>>4,e&=15,27030>>>e&1};var i=new Array(256);!function(e){for(var t=0;t<256;++t){var n=t,r=t,a=7;for(n>>>=1;n;n>>>=1)r<<=1,r|=1&n,--a;e[t]=r<>>8&255]<<16|i[e>>>16&255]<<8|i[e>>>24&255]},n.interleave2=function(e,t){return e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e|t<<1},n.deinterleave2=function(e,t){return e=e>>>t&1431655765,e=858993459&(e|e>>>1),e=252645135&(e|e>>>2),e=16711935&(e|e>>>4),e=65535&(e|e>>>16),e<<16>>16},n.interleave3=function(e,t,n){return e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e|=t<<1,n&=1023,n=4278190335&(n|n<<16),n=251719695&(n|n<<8),n=3272356035&(n|n<<4),n=1227133513&(n|n<<2),e|n<<2},n.deinterleave3=function(e,t){return e=e>>>t&1227133513,e=3272356035&(e|e>>>2),e=251719695&(e|e>>>4),e=4278190335&(e|e>>>8),e=1023&(e|e>>>16),e<<22>>22},n.nextCombination=function(e){var t=e|e-1;return t+1|(~t&-~t)-1>>>r(e)+1}},{}],13:[function(e,t,n){"use strict";function r(e){var t=(v.nextPow2(e+1)>>>1)-1,n=e-t;return v.nextPow2(n)-1>=t?t:(t>>>1)+n}function a(e){return 0}function i(e){return e-1}function o(e,t){if(e<=0)return 0;var n=r(e);return t>n?o(e-n-1,t-n-1):t===n?v.log2(e):o(n,t)}function l(e,t){return Math.max(t-1,0)}function s(e,t){return Math.min(t+1,e-1)}function u(e,t){if(e<=0)return-1;var n=r(e);if(t>n){var a=u(e-n-1,t-n-1);return a<0?n:a+n+1}if(t===n)return-1;var a=u(n,t);return a<0?n:a}function c(e,t){if(e<=0)return 0;var n=r(e);return t>n?c(e-n-1,t-n-1)+n+1:t===n?r(t):c(n,t)}function f(e,t){if(e<=0)return 0;var n=r(e);return t>n?f(e-n-1,t-n-1)+n+1:t===n?r(e-n-1)+n+1:f(n,t)}function d(e,t){return 0===o(e,t)}function p(e,t){e|=0,t|=0;for(var n=0;e>1;){var a=r(e);if(t>a)n+=a+1,e-=a+1,t-=a+1;else{if(t===a)break;e=a}}return n}function h(e,t){e|=0,t|=0;for(var n=0;e>1;){var a=r(e);if(t>a)n+=a+1,e-=a+1,t-=a+1;else{if(t===a){n+=e-1;break}e=a}}return n}var v=e("bit-twiddle");n.root=r,n.begin=a,n.end=i,n.height=o,n.prev=l,n.next=s,n.parent=u,n.left=c,n.right=f,n.leaf=d,n.lo=p,n.hi=h},{"bit-twiddle":14}],14:[function(e,t,n){arguments[4][12][0].apply(n,arguments)},{dup:12}],15:[function(e,t,n){"use strict";function r(e){if(!e)return l;for(var t=0;t>",rrshift:">>>"};!function(){for(var e in s){var t=s[e];n[e]=i({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+t+"c"},funcName:e}),n[e+"eq"]=i({args:["array","array"],body:{args:["a","b"],body:"a"+t+"=b"},rvalue:!0,funcName:e+"eq"}),n[e+"s"]=i({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+t+"s"},funcName:e+"s"}),n[e+"seq"]=i({args:["array","scalar"],body:{args:["a","s"],body:"a"+t+"=s"},rvalue:!0,funcName:e+"seq"})}}();var u={not:"!",bnot:"~",neg:"-",recip:"1.0/"};!function(){for(var e in u){var t=u[e];n[e]=i({args:["array","array"],body:{args:["a","b"],body:"a="+t+"b"},funcName:e}),n[e+"eq"]=i({args:["array"],body:{args:["a"],body:"a="+t+"a"},rvalue:!0,count:2,funcName:e+"eq"})}}();var c={and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">="};!function(){for(var e in c){var t=c[e];n[e]=i({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+t+"c"},funcName:e}),n[e+"s"]=i({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+t+"s"},funcName:e+"s"}),n[e+"eq"]=i({args:["array","array"],body:{args:["a","b"],body:"a=a"+t+"b"},rvalue:!0,count:2,funcName:e+"eq"}),n[e+"seq"]=i({args:["array","scalar"],body:{args:["a","s"],body:"a=a"+t+"s"},rvalue:!0,count:2,funcName:e+"seq"})}}();var f=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan"];!function(){for(var e=0;ethis_s){this_s=-a}else if(a>this_s){this_s=a}",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norminf"}),n.norm1=o({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:3}],body:"this_s+=a<0?-a:a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norm1"}),n.sup=o({args:["array"],pre:{body:"this_h=-Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),n.inf=o({args:["array"],pre:{body:"this_h=Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),n.random=i({args:["array"],pre:{args:[],body:"this_f=Math.random",thisVars:["this_f"]},body:{args:["a"],body:"a=this_f()",thisVars:["this_f"]},funcName:"random"}),n.assign=i({args:["array","array"],body:{args:["a","b"],body:"a=b"},funcName:"assign"}),n.assigns=i({args:["array","scalar"],body:{args:["a","b"],body:"a=b"},funcName:"assigns"}),n.equals=o({args:["array","array"],pre:l,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1},{name:"y",lvalue:!1,rvalue:!0,count:1}],body:"if(x!==y){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"equals"})},{"cwise-compiler":16}],16:[function(e,t,n){"use strict";function r(){this.argTypes=[],this.shimArgs=[],this.arrayArgs=[],this.arrayBlockIndices=[],this.scalarArgs=[],this.offsetArgs=[],this.offsetArgIndex=[],this.indexArgs=[],this.shapeArgs=[],this.funcName="",this.pre=null,this.body=null,this.post=null,this.debug=!1}function a(e){var t=new r;t.pre=e.pre,t.body=e.body,t.post=e.post;var n=e.args.slice(0);t.argTypes=n;for(var a=0;a0)throw new Error("cwise: pre() block may not reference array args");if(a0)throw new Error("cwise: post() block may not reference array args")}else if("scalar"===o)t.scalarArgs.push(a),t.shimArgs.push("scalar"+a);else if("index"===o){if(t.indexArgs.push(a),a0)throw new Error("cwise: pre() block may not reference array index");if(a0)throw new Error("cwise: post() block may not reference array index")}else if("shape"===o){if(t.shapeArgs.push(a),an.length)throw new Error("cwise: Too many arguments in pre() block");if(t.body.args.length>n.length)throw new Error("cwise: Too many arguments in body() block");if(t.post.args.length>n.length)throw new Error("cwise: Too many arguments in post() block");return t.debug=!!e.printCode||!!e.debug,t.funcName=e.funcName||"cwise",t.blockSize=e.blockSize||64,i(t)}var i=e("./lib/thunk.js");t.exports=a},{"./lib/thunk.js":18}],17:[function(e,t,n){"use strict";function r(e,t,n){var r,a,i=e.length,o=t.arrayArgs.length,l=t.indexArgs.length>0,s=[],u=[],c=0,f=0;for(r=0;r=0;--r)c=e[r],s.push(["for(i",r,"=0;i",r,"0&&s.push(["index[",f,"]-=s",f].join("")),s.push(["++index[",c,"]"].join(""))),s.push("}")}return s.join("\n")}function a(e,t,n,a){for(var i=t.length,o=n.arrayArgs.length,l=n.blockSize,s=n.indexArgs.length>0,u=[],c=0;c0;){"].join("")),u.push(["if(j",c,"<",l,"){"].join("")),u.push(["s",t[c],"=j",c].join("")),u.push(["j",c,"=0"].join("")),u.push(["}else{s",t[c],"=",l].join("")),u.push(["j",c,"-=",l,"}"].join("")),s&&u.push(["index[",t[c],"]=j",c].join(""));for(var c=0;c0&&(n=n&&t[r]===t[r-1])}return n?t[0]:t.join("")}function s(e,t){for(var n=t[1].length-Math.abs(e.arrayBlockIndices[0])|0,s=new Array(e.arrayArgs.length),c=new Array(e.arrayArgs.length),f=0;f0&&w.push("shape=SS.slice(0)"),e.indexArgs.length>0){for(var _=new Array(n),f=0;f3&&b.push(o(e.pre,e,c));var A=o(e.body,e,c),j=i(g);j3&&b.push(o(e.post,e,c)),e.debug&&console.log("-----Generated cwise routine for ",t,":\n"+b.join("\n")+"\n----------");var E=[e.funcName||"unnamed","_cwise_loop_",s[0].join("s"),"m",j,l(c)].join(""),S=new Function(["function ",E,"(",x.join(","),"){",b.join("\n"),"} return ",E].join(""));return S()}var u=e("uniq");t.exports=s},{uniq:19}],18:[function(e,t,n){"use strict";function r(e){var t=["'use strict'","var CACHED={}"],n=[],r=e.funcName+"_cwise_thunk";t.push(["return function ",r,"(",e.shimArgs.join(","),"){"].join(""));for(var i=[],o=[],l=[["array",e.arrayArgs[0],".shape.slice(",Math.max(0,e.arrayBlockIndices[0]),e.arrayBlockIndices[0]<0?","+e.arrayBlockIndices[0]+")":")"].join("")],s=[],u=[],c=0;c0&&(s.push("array"+e.arrayArgs[0]+".shape.length===array"+f+".shape.length+"+(Math.abs(e.arrayBlockIndices[0])-Math.abs(e.arrayBlockIndices[c]))),u.push("array"+e.arrayArgs[0]+".shape[shapeIndex+"+Math.max(0,e.arrayBlockIndices[0])+"]===array"+f+".shape[shapeIndex+"+Math.max(0,e.arrayBlockIndices[c])+"]"))}e.arrayArgs.length>1&&(t.push("if (!("+s.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same dimensionality!')"),t.push("for(var shapeIndex=array"+e.arrayArgs[0]+".shape.length-"+Math.abs(e.arrayBlockIndices[0])+"; shapeIndex-->0;) {"),t.push("if (!("+u.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same shape!')"),t.push("}"));for(var c=0;c=0;--a)r[a]=n,n*=e[a];return u(f.malloc(n,t),e,r,0)}function i(e){"generic"!==e.dtype&&"array"!==e.dtype&&f.free(e.data)}function o(e,t){t||(t="double");for(var n=1,r=new Array(e.length),a=e.length-1;a>=0;--a)r[a]=n,n*=e[a];for(var i=f.malloc(n,t),a=0;a=0;--a)r[a]=n,n*=e[a];for(var i=f.malloc(n,t),a=0;a=0;--n)i[n]=a,a*=e[n];var o=f.malloc(a,t);for(n=0;n=0;n--)s+=i[n],l=Math.min(l,e[n]);for(n=0,r=0;n1&&A.push("_cmp:");for(var f=p-1;f>0;--f)A.push("for(",l(f),"=0;",l(f),"<",r(f),";",l(f),"++){");z?A.push(n,"=",m,".get(",u(0),")-",m,".get(",u(1),");"):A.push(n,"=",m,"[",u(0),"]-",m,"[",u(1),"];"),p>1&&A.push("if(",n,")break _cmp;");for(var f=1;f0;--o)A.push("for(",l(e[o]),"=0;",l(e[o]),"<",r(e[o]),";",l(e[o]),"++){");z?A.push(b,"=",m,".get(",u(0),");",m,".set(",u(0),",",m,".get(",u(1),"));",m,".set(",u(1),",",b,");"):A.push(b,"=",m,"[",u(0),"];",m,"[",u(0),"]=",m,"[",u(1),"];",m,"[",u(1),"]=",b,";");for(var o=1;o1?E.push(o(S)+"=("+a(S)+"-"+r(S-1)+"*"+a(S-1)+")|0",i(e[S])+"=("+a(e[S])+"-"+r(e[S-1])+"*"+a(e[S-1])+")|0"):E.push(o(S)+"="+a(S),i(e[S])+"="+a(e[S]));if(t)for(var S=0;S<2;++S)E.push(s(S)+"="+h+".pick(0)");E.push(k+"=0",w+"=0",_+"="+r(e[0])+"-1"),A.push("while(",w,"<",_,"){",k,"=(",x,"()*(",_,"-",w,"+1)+",w,")|0;"),d(k,_),A.push(k,"=",w,";","for(",l(0),"=",w,";",l(0),"<",_,";",l(0),"++){"),f(b,l(0),_),A.push("if(",b,"<0){"),d(k,l(0)),A.push(k,"++;"),A.push("}}"),d(k,_),A.push("if(",k,"===",v,"){",w,"=",k,";","break;","}else if(",v,"<",k,"){",_,"=",k,"-1;","}else{",w,"=",k,"+1;","}","}"),t?A.push(s(0),".offset=",y,"+",w,"*",a(0),";","return ",s(0),";"):A.push("return ",h,".pick(",w,");");var O=["'use strict';function ",M,"(",j,"){","var ",E.join(),";",A.join(""),"};return ",M].join(""),N=new Function(O);return N()}function d(e,t,n){var r=e.join()+t+n,a=z[r];return a?a:z[r]=f(e,t,n)}function p(e,t,n){if(t|=0,0===e.dimension||e.shape[0]<=t||t<0)return null;var r=!!n,a=d(e.order,r,e.dtype);return r?a(e,t,n):a(e,t)}t.exports=p,t.exports.compile=d;var h="a",v="K",g="C",m="d",y="o",x="R",b="T",w="L",_="H",k="X",z={}},{}],28:[function(e,t,n){function r(e,t){return e[0]-t[0]}function a(){var e,t=this.stride,n=new Array(t.length);for(e=0;eMath.abs(this.stride[1]))?[1,0]:[0,1]}})"):3===t&&i.push("var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);if(s0>s1){if(s1>s2){return [2,1,0];}else if(s0>s2){return [1,2,0];}else{return [1,0,2];}}else if(s0>s2){return [2,0,1];}else if(s2>s1){return [0,1,2];}else{return [0,2,1];}}})")):i.push("ORDER})")),i.push("proto.set=function "+n+"_set("+u.join(",")+",v){"),r?i.push("return this.data.set("+c+",v)}"):i.push("return this.data["+c+"]=v}"),i.push("proto.get=function "+n+"_get("+u.join(",")+"){"),r?i.push("return this.data.get("+c+")}"):i.push("return this.data["+c+"]}"),i.push("proto.index=function "+n+"_index(",u.join(),"){return "+c+"}"),i.push("proto.hi=function "+n+"_hi("+u.join(",")+"){return new "+n+"(this.data,"+l.map(function(e){return["(typeof i",e,"!=='number'||i",e,"<0)?this.shape[",e,"]:i",e,"|0"].join("")}).join(",")+","+l.map(function(e){return"this.stride["+e+"]"}).join(",")+",this.offset)}");var h=l.map(function(e){return"a"+e+"=this.shape["+e+"]"}),v=l.map(function(e){return"c"+e+"=this.stride["+e+"]"});i.push("proto.lo=function "+n+"_lo("+u.join(",")+"){var b=this.offset,d=0,"+h.join(",")+","+v.join(","));for(var g=0;g=0){d=i"+g+"|0;b+=c"+g+"*d;a"+g+"-=d}");i.push("return new "+n+"(this.data,"+l.map(function(e){return"a"+e}).join(",")+","+l.map(function(e){return"c"+e}).join(",")+",b)}"),i.push("proto.step=function "+n+"_step("+u.join(",")+"){var "+l.map(function(e){return"a"+e+"=this.shape["+e+"]"}).join(",")+","+l.map(function(e){return"b"+e+"=this.stride["+e+"]"}).join(",")+",c=this.offset,d=0,ceil=Math.ceil");for(var g=0;g=0){c=(c+this.stride["+g+"]*i"+g+")|0}else{a.push(this.shape["+g+"]);b.push(this.stride["+g+"])}");i.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}"),i.push("return function construct_"+n+"(data,shape,stride,offset){return new "+n+"(data,"+l.map(function(e){return"shape["+e+"]"}).join(",")+","+l.map(function(e){ +return"stride["+e+"]"}).join(",")+",offset)}");var o=new Function("CTOR_LIST","ORDER",i.join("\n"));return o(f[e],a)}function o(e){if(u(e))return"buffer";if(c)switch(Object.prototype.toString.call(e)){case"[object Float64Array]":return"float64";case"[object Float32Array]":return"float32";case"[object Int8Array]":return"int8";case"[object Int16Array]":return"int16";case"[object Int32Array]":return"int32";case"[object Uint8Array]":return"uint8";case"[object Uint16Array]":return"uint16";case"[object Uint32Array]":return"uint32";case"[object Uint8ClampedArray]":return"uint8_clamped"}return Array.isArray(e)?"array":"generic"}function l(e,t,n,r){if(void 0===e){var a=f.array[0];return a([])}"number"==typeof e&&(e=[e]),void 0===t&&(t=[e.length]);var l=t.length;if(void 0===n){n=new Array(l);for(var s=l-1,u=1;s>=0;--s)n[s]=u,u*=t[s]}if(void 0===r){r=0;for(var s=0;s0)return a(0|e,t);break;case"object":if("number"==typeof e.length)return r(e,t,0)}return[]}t.exports=i},{}],32:[function(e,t,n){(function(t,r){"use strict";function a(e){if(e){var t=e.length||e.byteLength,n=y.log2(t);_[n].push(e)}}function i(e){a(e.buffer)}function o(e){var e=y.nextPow2(e),t=y.log2(e),n=_[t];return n.length>0?n.pop():new ArrayBuffer(e)}function l(e){return new Uint8Array(o(e),0,e)}function s(e){return new Uint16Array(o(2*e),0,e)}function u(e){return new Uint32Array(o(4*e),0,e)}function c(e){return new Int8Array(o(e),0,e)}function f(e){return new Int16Array(o(2*e),0,e)}function d(e){return new Int32Array(o(4*e),0,e)}function p(e){return new Float32Array(o(4*e),0,e)}function h(e){return new Float64Array(o(8*e),0,e)}function v(e){return b?new Uint8ClampedArray(o(e),0,e):l(e)}function g(e){return new DataView(o(e),0,e)}function m(e){e=y.nextPow2(e);var t=y.log2(e),n=k[t];return n.length>0?n.pop():new r(e)}var y=e("bit-twiddle"),x=e("dup");t.__TYPEDARRAY_POOL||(t.__TYPEDARRAY_POOL={UINT8:x([32,0]),UINT16:x([32,0]),UINT32:x([32,0]),INT8:x([32,0]),INT16:x([32,0]),INT32:x([32,0]),FLOAT:x([32,0]),DOUBLE:x([32,0]),DATA:x([32,0]),UINT8C:x([32,0]),BUFFER:x([32,0])});var b="undefined"!=typeof Uint8ClampedArray,w=t.__TYPEDARRAY_POOL;w.UINT8C||(w.UINT8C=x([32,0])),w.BUFFER||(w.BUFFER=x([32,0]));var _=w.DATA,k=w.BUFFER;n.free=function(e){if(r.isBuffer(e))k[y.log2(e.length)].push(e);else{if("[object ArrayBuffer]"!==Object.prototype.toString.call(e)&&(e=e.buffer),!e)return;var t=e.length||e.byteLength,n=0|y.log2(t);_[n].push(e)}},n.freeUint8=n.freeUint16=n.freeUint32=n.freeInt8=n.freeInt16=n.freeInt32=n.freeFloat32=n.freeFloat=n.freeFloat64=n.freeDouble=n.freeUint8Clamped=n.freeDataView=i,n.freeArrayBuffer=a,n.freeBuffer=function(e){k[y.log2(e.length)].push(e)},n.malloc=function(e,t){if(void 0===t||"arraybuffer"===t)return o(e);switch(t){case"uint8":return l(e);case"uint16":return s(e);case"uint32":return u(e);case"int8":return c(e);case"int16":return f(e);case"int32":return d(e);case"float":case"float32":return p(e);case"double":case"float64":return h(e);case"uint8_clamped":return v(e);case"buffer":return m(e);case"data":case"dataview":return g(e);default:return null}return null},n.mallocArrayBuffer=o,n.mallocUint8=l,n.mallocUint16=s,n.mallocUint32=u,n.mallocInt8=c,n.mallocInt16=f,n.mallocInt32=d,n.mallocFloat32=n.mallocFloat=p,n.mallocFloat64=n.mallocDouble=h,n.mallocUint8Clamped=v,n.mallocDataView=g,n.mallocBuffer=m,n.clearCache=function(){for(var e=0;e<32;++e)w.UINT8[e].length=0,w.UINT16[e].length=0,w.UINT32[e].length=0,w.INT8[e].length=0,w.INT16[e].length=0,w.INT32[e].length=0,w.FLOAT[e].length=0,w.DOUBLE[e].length=0,w.UINT8C[e].length=0,_[e].length=0,k[e].length=0}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"bit-twiddle":12,buffer:2,dup:31}],33:[function(e,t,n){!function(e,r){"object"==typeof n&&"undefined"!=typeof t?r(n):"function"==typeof define&&define.amd?define(["exports"],r):r(e.topojson={})}(this,function(e){"use strict";function t(){}function n(e){if(!e)return t;var n,r,a=e.scale[0],i=e.scale[1],o=e.translate[0],l=e.translate[1];return function(e,t){t||(n=r=0),e[0]=(n+=e[0])*a+o,e[1]=(r+=e[1])*i+l}}function r(e){if(!e)return t;var n,r,a=e.scale[0],i=e.scale[1],o=e.translate[0],l=e.translate[1];return function(e,t){t||(n=r=0);var s=(e[0]-o)/a|0,u=(e[1]-l)/i|0;e[0]=s-n,e[1]=u-r,n=s,r=u}}function a(e,t){for(var n,r=e.length,a=r-t;a<--r;)n=e[a],e[a++]=e[r],e[r]=n}function i(e,t){for(var n=0,r=e.length;n>>1;e[a]1){var s,c=[],f={LineString:a,MultiLineString:i,Polygon:i,MultiPolygon:function(e){e.forEach(i)}};o(t),c.forEach(arguments.length<3?function(e){l.push(e[0].i)}:function(e){n(e[0].g,e[e.length-1].g)&&l.push(e[0].i)})}else for(var d=0,p=e.arcs.length;d0}var a={},i=[],o=[];return t.forEach(function(e){"Polygon"===e.type?n(e.arcs):"MultiPolygon"===e.type&&e.arcs.forEach(n)}),i.forEach(function(e){if(!e._){var t=[],n=[e];for(e._=1,o.push(t);e=n.pop();)t.push(e),e.forEach(function(e){e.forEach(function(e){a[e<0?~e:e].forEach(function(e){e._||(e._=1,n.push(e))})})})}}),i.forEach(function(e){delete e._}),{type:"MultiPolygon",arcs:o.map(function(t){var n,i=[];if(t.forEach(function(e){e.forEach(function(e){e.forEach(function(e){a[e<0?~e:e].length<2&&i.push(e)})})}),i=u(e,i),(n=i.length)>1)for(var o,l=r(t[0][0]),s=0;s0;){var n=(t+1>>1)-1,a=r[n];if(m(e,a)>=0)break;r[a._=t]=a,r[e._=t=n]=e}}function t(e,t){for(;;){var n=t+1<<1,i=n-1,o=t,l=r[o];if(i0&&(e=r[a],t(r[e._=0]=e,0)),n}},n.remove=function(n){var i,o=n._;if(r[o]===n)return o!==--a&&(i=r[a],(m(i,n)<0?e:t)(r[i._=o]=i,o)),o},n}function x(e,t){function a(e){l.remove(e),e[1][2]=t(e),l.push(e)}var i=n(e.transform),o=r(e.transform),l=y();return t||(t=d),e.arcs.forEach(function(e){var n,r,s,u,c=[],f=0;for(r=0,s=e.length;r=0?r(e,t):e=0||e.indexOf(n)>=0)}},{}],36:[function(e,t,n){var r,a;r=e("./comparator.coffee"),a=e("../core/fetch/sort.coffee"),t.exports=function(e,t,n,i,o,l){var s,u,c,f;if(!e||e.length<=1)return e||[];if(o)for(t||(t=o.order.value||o.size.value||o.id.value),n||(n=o.order.sort.value),i||(i=o.color.value||[]),c=0,f=e.length;c=0?e.splice(e.indexOf(t),1):e.push(t),e)}},{}],38:[function(e,t,n){var r;r=function(e){var t,n,a,i;if(i=r.tested,e in i)return i[e];for(n=0,a=!1;n=0){a=!0;break}n++}return a},r.tested={},t.exports=r},{}],39:[function(e,t,n){t.exports=/(MSIE|Trident\/|Edge\/)/i.test(navigator.userAgent)},{}],40:[function(e,t,n){var r,a;r=e("./ie.js"),a=e("./touch.coffee"),a?t.exports={click:"click",down:"touchstart",up:"touchend",over:r?"mouseenter":"mouseover",out:r?"mouseleave":"mouseout",move:"mousemove"}:t.exports={click:"click",down:"mousedown",up:"mouseup",over:r?"mouseenter":"mouseover",out:r?"mouseleave":"mouseout",move:"mousemove"}},{"./ie.js":39,"./touch.coffee":45}],41:[function(e,t,n){var r;r=function(){var e;return e="-webkit-transform"in document.body.style?"-webkit-":"-moz-transform"in document.body.style?"-moz-":"-ms-transform"in document.body.style?"-ms-":"-o-transform"in document.body.style?"-o-":"",r=function(){return e},e},t.exports=r},{}],42:[function(e,t,n){t.exports="rtl"===d3.select("html").attr("dir")},{}],43:[function(e,t,n){t.exports={y:function(){return void 0!==window.pageYOffset?window.pageYOffset:(document.documentElement||document.body.parentNode||document.body).scrollTop},x:function(){return void 0!==window.pageXOffset?window.pageXOffset:(document.documentElement||document.body.parentNode||document.body).scrollLeft}}},{}],44:[function(e,t,n){var r;r=function(){var e,t,n,a,i;return e=document.createElement("p"),e.style.width="100%",e.style.height="200px",t=document.createElement("div"),t.style.position="absolute",t.style.top="0px",t.style.left="0px",t.style.visibility="hidden",t.style.width="200px",t.style.height="150px",t.style.overflow="hidden",t.appendChild(e),document.body.appendChild(t),a=e.offsetWidth,t.style.overflow="scroll",i=e.offsetWidth,a===i&&(i=t.clientWidth),document.body.removeChild(t),n=a-i,r=function(){return n},n},t.exports=r},{}],45:[function(e,t,n){t.exports=!!("ontouchstart"in window||window.DocumentTouch&&document instanceof DocumentTouch)},{}],46:[function(e,t,n){t.exports=function(e){var t;return t=d3.hsl(e),t.l>.45&&(t.s>.8&&(t.s=.8),t.l=.45),t.toString()}},{}],47:[function(e,t,n){t.exports=function(e,t){var n;return void 0===t&&(t=.5),n=d3.hsl(e),t=(1-n.l)*t,n.l+=t,n.s-=t,n.toString()}},{}],48:[function(e,t,n){t.exports=function(e,t,n,r){var a,i,o;return n||(n=1),r||(r=1),e=d3.rgb(e),t=d3.rgb(t),o=(n*e.r+r*t.r-n*r*t.r)/(n+r-n*r),i=(n*e.g+r*t.g-n*r*t.g)/(n+r-n*r),a=(n*e.b+r*t.b-n*r*t.b)/(n+r-n*r),d3.rgb(o,i,a).toString()}},{}],49:[function(e,t,n){var r;r=e("./scale.coffee"),t.exports=function(e,t){var n;return n=e||Math.floor(20*Math.random()),(t=t||r)(n)}},{"./scale.coffee":50}],50:[function(e,t,n){t.exports=d3.scale.ordinal().range(["#b22200","#282F6B","#EACE3F","#B35C1E","#224F20","#5F487C","#759143","#419391","#993F88","#e89c89","#ffee8d","#afd5e8","#f7ba77","#a5c697","#c5b5e5","#d1d392","#bbefd0","#e099cf"])},{}],51:[function(e,t,n){t.exports=function(e,t){var n,r;return n=d3.hsl(e),r=d3.hsl(t),e=0===n.s?361:n.h,t=0===r.s?361:r.h,e===t?n.l-r.l:e-t}},{}],52:[function(e,t,n){t.exports=function(e){var t,n,r,a,i;return a=d3.rgb(e),r=a.r,n=a.g,t=a.b,i=(299*r+587*n+114*t)/1e3,i>=128?"#444444":"#f7f7f7"}},{}],53:[function(e,t,n){t.exports=function(e){var t,n,r;return e+="",e=e.replace(RegExp(" ","g"),""),0===e.indexOf("rgb")&&(e=e.split("(")[1].split(")")[0].split(",").slice(0,3).join(",")),0===e.indexOf("hsl")&&(e=e.split(",")[2].split(")")[0]),n=d3.rgb(e).toString(),t=["black","#000","#000000","0%","0,0,0"],r=t.indexOf(e)>=0,"#000000"!==n||r}},{}],54:[function(e,t,n){var r,a,i;r=e("../../client/ie.js"),i=e("./wiki.coffee"),a=function(e,t,n){n=n||"",r||"undefined"!=typeof InstallTrigger?console.log("[ D3plus ] "+t):0===e.indexOf("group")?console[e]("%c[ D3plus ]%c "+t,"font-weight: 800;color: #b35c1e;margin-left: 0px;","font-weight:200;"+n):console[e]("%c"+t,n+"font-weight:200;")},a.comment=function(e){this("log",e,"color:#aaa;")},a.error=function(e,t){this("groupCollapsed","ERROR: "+e,"font-weight:800;color:#D74B03;"),this.stack(),this.wiki(t),this.groupEnd()},a.group=function(e){this("group",e,"color:#888;")},a.groupCollapsed=function(e){this("groupCollapsed",e,"color:#888;")},a.groupEnd=function(){r||console.groupEnd()},a.log=function(e){this("log",e,"color:#444444;")},a.stack=function(){var e,t,n,a,i,o,l;r||(e=new Error,e.stack&&(o=e.stack.split("\n"),o=o.filter(function(e){return 0!==e.indexOf("Error")&&e.indexOf("d3plus.js:")<0&&e.indexOf("d3plus.min.js:")<0}),o.length&&o[0].length&&(i=window.chrome?"at ":"@",l=o[0],l.indexOf(i)>=0&&(l=l.split(i)[1]),o=l.split(":"),3===o.length&&o.pop(),t=o.pop(),a=o.join(":").split("/"),a=a[a.length-1],n="line "+t+" of "+a+": "+l,this("log",n,"color:#D74B03;"))))},a.time=function(e){r||console.time(e)},a.timeEnd=function(e){r||console.timeEnd(e)},a.warning=function(e,t){this("groupCollapsed",e,"color:#888;"),this.stack(),this.wiki(t),this.groupEnd()},a.wiki=function(e){e&&(e in i&&(e=d3plus.repo+"wiki/"+i[e]),this("log","documentation: "+e,"color:#aaa;"))},t.exports=a},{"../../client/ie.js":39,"./wiki.coffee":55}],55:[function(e,t,n){t.exports={active:"Visualizations#active",aggs:"Visualizations#aggs",alt:"Forms#alt",attrs:"Visualizations#attrs",axes:"Visualizations#axes",background:"Visualizations#background",color:"Visualizations#color",cols:"Visualizations#cols",config:"Visualizations#config",container:"Visualizations#container",coords:"Visualizations#coords",csv:"Visualizations#csv",data:"Visualizations#data",depth:"Visualizations#depth",descs:"Visualizations#descs",dev:"Visualizations#dev",draw:"Visualizations#draw",edges:"Visualizations#edges",error:"Visualizations#error",focus:"Visualizations#focus",font:"Visualizations#font",footer:"Visualizations#footer",format:"Visualizations#format",height:"Visualizations#height",history:"Visualizations#history",hover:"Forms#hover",icon:"Visualizations#icon",id:"Visualizations#id",keywords:"Forms#keywords",labels:"Visualizations#labels",legend:"Visualizations#legend",links:"Visualizations#links",margin:"Visualizations#margin",messages:"Visualizations#messages",method:"Methods",mouse:"Visualizations#mouse",nodes:"Visualizations#nodes",open:"Forms#open",order:"Visualizations#order",remove:"Forms#remove",search:"Forms#search",select:"Forms#select",selectAll:"Forms#selectAll",shape:"Visualizations#shape",size:"Visualizations#size",temp:"Visualizations#temp",text:"Visualizations#text",time:"Visualizations#time",timeline:"Visualizations#timeline",timing:"Visualizations#timing",title:"Visualizations#title",tooltip:"Visualizations#tooltip",total:"Visualizations#total",type:"Visualizations#type",ui:"Visualizations#ui",width:"Visualizations#width",x:"Visualizations#x",y:"Visualizations#y",zoom:"Visualizations#zoom"}},{}],56:[function(e,t,n){var r=e("../../util/buckets.coffee"),a=e("../fetch/value.coffee"),i=e("../console/print.coffee");t.exports=function(e){if(e.dev.value&&i.time("getting color data range"),e.color.domain.value)var t=e.color.domain.value;else{var t=[];e.data.pool.forEach(function(n){var r=parseFloat(a(e,n,e.color.value));"number"==typeof r&&!isNaN(r)&&t.indexOf(r)<0&&t.push(r)})}if(e.dev.value&&i.timeEnd("getting color data range"),t.length>1){if(e.dev.value&&i.time("calculating color scale"),t=d3.extent(t),t[0]<0&&t[1]>0){var n=e.color.range;3==n.length&&(t.push(t[1]),t[1]=0)}else if(t[1]>0&&t[0]>=0){var n=e.color.heatmap;t=r(t,n.length)}else{var n=e.color.range.slice(0);t[0]<0?n.pop():n.shift()}e.color.valueScale=d3.scale.sqrt().domain(t).range(n).interpolate(d3.interpolateRgb),e.dev.value&&i.timeEnd("calculating color scale")}else e.color.valueScale=null}},{"../../util/buckets.coffee":207,"../console/print.coffee":54,"../fetch/value.coffee":69}],57:[function(e,t,n){var r=e("../fetch/value.coffee"),a=e("../console/print.coffee"),i=e("../../object/validate.coffee");t.exports=function(e,t){e.dev.value&&a.time("filtering data");var n=d3.keys(e.data.keys||{});"attrs"in e&&(n=n.concat(d3.keys(e.attrs.keys||{}))),t=t.filter(function(t){var n=r(e,t,e.id.value);return null!==n});var o=e.types[e.type.value].requirements||[];e.data.filters.forEach(function(a){n.indexOf(e[a].value)>=0&&o.indexOf(a)>=0&&(t=t.filter(function(t){var n=r(e,t,e[a].value);return"y"===a&&e.y2.value&&null===n?n=r(e,t,e.y2.value):"x"===a&&e.x2.value&&null===n&&(n=r(e,t,e.x2.value)),"size"===a?"number"==typeof n:null!==n}))});var l=e.data.solo.length?"solo":"mute";return e.data[l].length?e.data[l].forEach(function(n){function o(t){var r=e[n][l].value,a=!1;return r.forEach(function(e){"function"==typeof e?a=e(t):e===t&&(a=!0)}),"solo"===l?a:!a}function s(t,a){if(!a&&e[n].nesting){var l=e[n].nesting;i(l)&&(l=d3.values(l));for(var s=0;s=4||l.indexOf(t)<=3)return d.timeFormat[t+"-"+e];var r;return r="Date"===t?d.timeFormat[t]:d.timeFormat[t+"-Date"],"Hours"===e?r+" "+d.timeFormat[e]:r+" "+d.timeFormat["Hours-"+e]};if(e.data.time.getFormat=h,f)"string"==typeof f?e.data.time.format=d3.locale(d.format).timeFormat(f):"function"==typeof f?e.data.time.format=f:f instanceof Array&&(e.data.time.format=d3.locale(d.format).timeFormat.multi(f)),e.data.time.multiFormat=e.data.time.format;else{for(var v=e.data.time.stepType,g=e.data.time.totalType,m=[],y=l.indexOf(v);y<=l.indexOf(g);y++){var x=y-11?(m[m.length-1][1]=function(e){return!0},e.data.time.multiFormat=d3.locale(d.format).timeFormat.multi(m)):e.data.time.multiFormat=e.data.time.format}e.data.time.ticks=[];for(var _=d3.min(e.data.time.values),k=d3.max(e.data.time.values),z=0;z<=e.data.time.stepIntervals;z++){var M=new Date(_);M["set"+e.data.time.stepType](M["get"+e.data.time.stepType]()+z),M<=k&&e.data.time.ticks.push(M)}e.dev.value&&i.timeEnd(t)}if(e.dev.value&&(t="nesting data by time and depths",i.time(t)),e.data.nested={},0===e.data.time.values.length)e.data.nested.all={},e.id.nesting.forEach(function(t,n){var a=e.id.nesting.slice(0,n+1);e.data.nested.all[t]=r(e,e.data.value,a)});else{var A=e.data.value.reduce(function(t,n){var r=a(e,n,e.time.value).getTime();return r in t||(t[r]=[]),t[r].push(n),t},{});e.data.time.values.forEach(function(t){var n=t.getTime();e.data.nested[n]={},e.id.nesting.forEach(function(t,a){var i=e.id.nesting.slice(0,a+1);e.data.nested[n][t]=r(e,A[n],i)})})}e.dev.value&&i.timeEnd(t)}},{"../../util/uniques.coffee":213,"../console/print.coffee":54,"../fetch/value.coffee":69,"./nest.js":62}],59:[function(e,t,n){var r;r=e("../fetch/value.coffee"),t.exports=function(e,t,n){var a,i,o,l,s,u,c,f,d,p;if(i=d3.nest(),e.id.grouping.value)for(void 0===n&&(n=e.id.nesting),o=l=0,u=n.length;l0&&(delete a.d3plus.r,delete a.d3plus.x,delete a.d3plus.y,d.push({d3plus:a,id:a[e.id.value],value:p}));return i.entries(d)}},{"../fetch/value.coffee":69}],60:[function(e,t,n){var r,a,i=[].indexOf||function(e){for(var t=0,n=this.length;t=0||null===d?f.push(void 0):f.push(e[t].keys[s]=typeof d);return f}},a(e[t].value)){s=d3.keys(e[t].value).length===e.id.nesting.length,u=e[t].value;for(o in u)if(d=u[o],s&&e.id.nesting.indexOf(o)>=0&&a(d))for(l in d)p=d[l],n(p);else n(d)}else{c=e[t].value;for(o in c)d=c[o],n(d)}if(e.dev.value)return r.time(f)}},{"../../object/validate.coffee":175,"../console/print.coffee":54}],61:[function(e,t,n){var r,a;r=e("../console/print.coffee"),a=e("../../object/validate.coffee"),t.exports=function(e,t,n){var i,o,l,s;return i=e.dev.value,i&&r.time("loading "+t),s=e[t].url,e[t].filetype.value?o=e[t].filetype.value:(o=s.slice(s.length-5).split("."),o=o.length>1&&o[1],o?("txt"===o&&(o="text"),e[t].filetype.accepted.indexOf(o)<0&&(o="json")):o="json"),(l="dsv"===o?d3.dsv(e[t].delimiter.value,"text/plain"):d3[o])(s,function(l,u){var c,f;if(!l&&u){if("function"==typeof e[t].callback){if(f=e[t].callback(u))if(a(f)&&t in f)for(c in f)c in e&&(e[c].value=f[c]);else e[t].value=f}else e[t].value=u;["json"].indexOf(o)<0&&e[t].value.forEach(function(e){var t;t=[];for(c in e)isNaN(e[c])?"false"===e[c].toLowerCase()?t.push(e[c]=!1):"true"===e[c].toLowerCase()?t.push(e[c]=!0):"null"===e[c].toLowerCase()?t.push(e[c]=null):"undefined"===e[c].toLowerCase()?t.push(e[c]=void 0):t.push(void 0):t.push(e[c]=parseFloat(e[c]));return t}),e[t].changed=!0,e[t].loaded=!0}else e.error.internal='Could not load data from: "'+s+'"';return i&&r.timeEnd("loading "+t),n()})}},{"../../object/validate.coffee":175,"../console/print.coffee":54}],62:[function(e,t,n){var r=e("../fetch/value.coffee"),a=e("../../object/validate.coffee"),i=e("../../util/uniques.coffee"),o=function(e,t,n,a){void 0===a&&(a=!0);var o=d3.nest(),c=[],f="temp"in e?["active","temp","total"]:[];n.length?n.forEach(function(t,n){o.key(function(n){return r(e,n,t)})}):o.key(function(e){return!0}),a&&e.axes&&e.axes.discrete&&(!e.time||e[e.axes.discrete].value!==e.time.value)&&o.key(function(t){return r(e,t,e[e.axes.discrete].value)});var d=n.length&&e.id.nesting.indexOf(n[n.length-1])>=0,p=n.length&&d?n.length-1:0;d?e.id.nesting[p]:e.depth.value;o.rollup(function(t){if(1===t.length&&"d3plus"in t[0])return c.push(t[0]),t[0];t=t.reduce(function(e,t){return t.values instanceof Array?e.concat(t.values):(e.push(t),e)},[]);var a={d3plus:{data:{},depth:p}},o=d3.sum(t,function(e){return"d3plus"in e&&e.d3plus.merged?1:0});if(o===t.length)for(var u=0;u=0,_="time"in e&&m===e.time.value;if(m in a.d3plus.data)a[m]=a.d3plus[m];else if("function"===x)a[m]=e.aggs.value[m](t);else if(_)a[m]=s(i(t,m));else if(e.axes&&e.axes.discrete&&e[e.axes.discrete].value===m)a[m]=i(t,m);else if("number"!==b||"string"!==x||w){var k=l(t,m),z=1===k.length?k[0][m]:i(k,m);if(1===k.length)a[m]=z;else if(z&&z.length)z instanceof Array||(z=[z]),w&&e.id.nesting.indexOf(m)>p?a[m]=k:a[m]=z;else if(w){var M=e.id.nesting.indexOf(m)-1;M>=p&&(!("endPoint"in a.d3plus)||a.d3plus.endPoint>p)&&(a.d3plus.endPoint=p)}}else{var A=t.map(function(e){return e[m]});A=A.filter(function(e){return typeof e===b}),A.length&&(a[m]=d3[y](A))}}m in a&&a[m]instanceof Array&&1===a[m].length&&(a[m]=a[m][0])}for(var j=0;j0){var s=[],u=0===e.depth.value?0:{},c=[],f=[],d=[],p={},h=d3.nest();n&&h.key(function(t){return i(e,t,n)}),h.rollup(function(t){var r=t.length; +e.aggs.value[e.size.value]?"function"==typeof e.aggs.value[e.size.value]?r=e.aggs.value[e.size.value](t):"string"==typeof e.aggs.value[e.size.value]&&(r=d3[e.aggs.value[e.size.value]](t,function(t){return i(e,t,e.size.value)})):r=d3.sum(t,function(t){return i(e,t,e.size.value)});var a=n?i(e,t[0],n):"all";return p[a]=r,r}).entries(t),t.forEach(function(t){var r=i(e,t,e.id.value),a=i(e,t,e.size.value),o=n?i(e,t,n):"all",u=a/p[o]>=l;if(u&&s.indexOf(r)<0&&(s.push(r),e.depth.value)){var c=i(e,t,e.id.nesting[e.depth.value-1]);f.indexOf(c)<0&&f.push(c)}});var v=t.filter(function(t){var n=i(e,t,e.id.value),r=s.indexOf(n)>=0,a=e.depth.value?i(e,t,e.id.nesting[e.depth.value-1]):null;if(null!==a&&f.indexOf(a)<0&&d.indexOf(a)<0&&d.push(a),!r){var o=i(e,t,e.size.value);o>0&&(0===e.depth.value?o>u&&(u=o):(a in u||(u[a]=0),o>u[a]&&(u[a]=o)),c.push(t))}return r});if(c.length>1){c=r(c,e.size.value,"desc",[],e);var g=e.id.nesting.slice(0,e.depth.value);e.types[e.type.value].requirements.indexOf(e.axes.discrete)>=0&&g.push(e[e.axes.discrete].value);var m=a(e,c,g);m.forEach(function(t){var n=e.id.nesting[e.depth.value-1],r=i(e,t,n);if(children=n?c.filter(function(t){return i(e,t,n)===r}):c,children.length>1){e.id.nesting.forEach(function(n,r){if(e.depth.value==r){var a=t[n];"string"==typeof a?t[n]="d3plus_other_"+a:t[n]="d3plus_other"}else r>e.depth.value&&delete t[n]}),e.color.value&&"string"===e.color.type&&(0===e.depth.value?t[e.color.value]=e.color.missing:t[e.color.value]=i(e,r,e.color.value,n)),e.icon.value&&(t[e.icon.value]=i(e,r,e.icon.value,n)),r&&(t.d3plus.depth=e.depth.value);var a;0===e.depth.value?(a=e.format.value(e.format.locale.value.ui.values,{key:"threshold",vars:e}),a+=" < "+e.format.value(u,{key:e.size.value,vars:e})):(a=o(e,t,e.depth.value-1),a=a.length?a[0].split(" < ")[0]:e.format.value(e.format.locale.value.ui.values,{key:"threshold",vars:e}),d.indexOf(r)<0&&(a+=" < "+e.format.value(u[r],{key:e.size.value,vars:e}))),d.indexOf(r)<0&&(a+=" ("+e.format.value(100*l,{key:"share",vars:e})+")"),t.d3plus.threshold=u,t.d3plus.merged=children,e.text.value&&(t[e.text.value]=a),t.d3plus.text=a}})}else m=c;return v.concat(m)}return t}},{"../../array/sort.coffee":36,"../fetch/color.coffee":65,"../fetch/text.js":68,"../fetch/value.coffee":69,"./nest.js":62}],64:[function(e,t,n){var r;r=e("../../font/sizes.coffee"),t.exports=function(e,t){var n,a,i,o,l,s,u,c,f,d,p,h,v,g,m,y,x,b;if(b=t.values||e.data.time.ticks,g=t.style||{},l=t.limit||e.width.value,m={},c=e.data.time.periods,v=e.data.time.stepType,y=e.data.time.totalType,i=e.data.time.functions,o=e.data.time.getFormat,s=e.format.locale.value.format,e.time.format.value)m.format=e.data.time.format,m.values=b,m.sizes=r(b.map(function(e){return m.format(e)}),g);else for(u=c.indexOf(v);u<=c.indexOf(y);){if(x=b.filter(function(e){var t,n;if(u===c.indexOf(v))return!0;if(t=!0,n=u-1,u<0)return!0;for(;n>=c.indexOf(v)&&t;)t=!i[n](e),n--;return t}),c[u]===y)a=d3.locale(s).timeFormat(o(c[u],y));else{for(f=u,a=[];f<=c.indexOf(y);)d=f-1=0;){if(s=e.id.nesting[f],p=l(t,e.color.value,r,e,s),1===p.length&&(p=p[0]),!(p instanceof Array)&&void 0!==p&&null!==p){o=a(e,t,p,n),c.indexOf(o)<0&&c.push(o);break}f--}return 1===c.length?c[0]:e.color.missing}return i(e,t,n)},a=function(e,t,n,r){return n?e.color.valueScale?e.color.valueScale(n):s(n)?n:i(e,n,r):e.color.value&&"function"==typeof e.color.valueScale?e.color.valueScale(0):i(e,t,r)},i=function(e,t,n){return u(t)&&(t=r(e,t,n)),t instanceof Array&&(t=t[0]),o(t,e.color.scale.value)}},{"../../color/random.coffee":49,"../../color/validate.coffee":53,"../../object/validate.coffee":175,"../../util/uniques.coffee":213,"./value.coffee":69}],66:[function(e,t,n){var r=e("../data/filter.js"),a=e("../data/nest.js"),i=e("../console/print.coffee"),o=e("../../string/format.js"),l=e("../../string/list.coffee");t.exports=function(e,t,n){if(!e.data.value)return[];void 0===n&&(n=e.depth.value);var s=e.id.nesting[n];if(!t||t instanceof Array||(t=[t]),!t&&"time"in e){t=[];var u=e.time.solo.value.length?"solo":"mute",c=e.time[u].value;if(c.length){t=[];for(var f=0;f=0&&e.data.time.values.length){t=e.data.time.values.slice(0);for(var g=0;g1&&(j=d3.extent(j)),j=j.map(function(t){return e.data.time.format(new Date(t))}),j=j.join(" - ");var O=e.format.locale.value.error.dataYear,N=e.format.locale.value.ui.and;j=l(j,N),e.error.internal=o(O,j),e.time.missing=!0}else{if(e.time&&(e.time.missing=!1),t.length>1){var F=!1;if(["x","y","x2","y2"].forEach(function(t){e[t].value===e.time.value&&"discrete"===e[t].scale.value&&(F=!0)}),!F){var C=e.id.nesting.slice(0,n+1);A=a(e,A,C)}}A=A?r(e,A):[],20===x.length&&(x.sort(),delete e.data.cache[x[0]]),m=(new Date).getTime()+"_"+m,e.data.cache[m]={data:A},"nodes"in e&&(e.data.cache[m].nodes=e.nodes.restricted,e.data.cache[m].edges=e.edges.restricted),"function"==typeof b&&(A=b(e,A)),e.dev.value&&i.comment("storing data in cache")}return A}},{"../../string/format.js":176,"../../string/list.coffee":177,"../console/print.coffee":54,"../data/filter.js":57,"../data/nest.js":62}],67:[function(e,t,n){var r,a,i;i=e("./value.coffee"),r=e("./color.coffee"),a=e("./text.js"),t.exports=function(e,t,n,o,l){var s,u,c,f,d,p;for(n instanceof Array||(n=[n]),o instanceof Array||(o=[o]),e&&(void 0===l?l=e.id.value:"number"!=typeof l&&(l=e.id.nesting.indexOf(l))),d={},u=0,f=n.length;u=0?r(e,t,l):c===e.text.value?a(e,t,l):3===d3.keys(t).length&&t.d3plus&&t.key&&t.values?i(e,t.values.map(function(e){return e.d3plus}),c,l):i(e,t,c,l):t[c],[e.data.keys[c],e.attrs.keys[c]].indexOf("number")>=0?(s=e.order.agg.value||e.aggs.value[c]||"sum",s.constructor===String&&(s=d3[s]),p instanceof Array||(p=[p]),p=s(p)):(p instanceof Array&&(p=p[0]),p="string"==typeof p?p.toLowerCase():p),d[c]=p;return d}},{"./color.coffee":65,"./text.js":68,"./value.coffee":69}],68:[function(e,t,n){var r=e("./value.coffee"),a=e("../../object/validate.coffee"),i=e("../../util/uniques.coffee");t.exports=function(e,t,n){"number"!=typeof n&&(n=e.depth.value);var o,l=e.id.nesting[n];e.text.nesting&&a(e.text.nesting)?o=e.text.nesting[l]?e.text.nesting[l]:e.text.value:(o=[],e.text.value&&n===e.depth.value&&o.push(e.text.value),o.push(l)),o instanceof Array||(o=[o]);var s=[];if(a(t)&&"d3plus"in t&&t.d3plus.text)s.push(t.d3plus.text.toString()),s.push(e.format.value(t.d3plus.text.toString(),{vars:e,data:t}));else{var u=a(t)?t:void 0;u&&t[e.id.value]instanceof Array?t=t[e.id.value]:t instanceof Array||(t=[t]),o.forEach(function(n){var a=i(t,n,r,e,l);a.length&&(a.length>1&&(a=a.filter(function(e){return e instanceof Array||"string"==typeof e&&e.indexOf(" < ")<0})),a=a.map(function(t){return t instanceof Array?(t=t.filter(function(e){return e}),t.map(function(t){return e.format.value(t.toString(),{vars:e,data:u,key:n})})):t?e.format.value(t.toString(),{vars:e,data:u,key:n}):void 0}),1===a.length&&(a=a[0]),s.push(a))})}return s}},{"../../object/validate.coffee":175,"../../util/uniques.coffee":213,"./value.coffee":69}],69:[function(e,t,n){var r,a,i,o,l,s,u,c,f,d;f=e("../../object/validate.coffee"),c=e("../../util/uniques.coffee"),u=function(e,t,n,o){var l,s,u,d;if(s=f(t),"function"==typeof n&&s)return n(t,e);if(s){if(n in t)return t[n];if(l=e.data.cacheID+"_"+o,r(t,l,e),n in t.d3plus.data[l])return t.d3plus.data[l][n];if(o in t)t=t[o];else{if(!(e.id.value in t))return null;if(t=t[e.id.value],o!==n&&(u=i(e,t,o,e.id.value)),null!==u&&void 0!==u||(u=a(e,t,o,e.id.value)),null===u||void 0===u)return null;if(o===n)return u;t=u}}return t instanceof Array&&!f(t[0])&&(t=c(t)),t instanceof Array&&f(t[0])&&(d=c(t,n),d.length)?d:(d=i(e,t,n,o))?d:d=a(e,t,n,o)},i=function(e,t,n,r){var a;return e.data.viz instanceof Array&&n in e.data.keys&&(a=c(s(e.data.viz,t,r),n)),a&&a.length?a:null},a=function(e,t,n,r){var a,i,o,l;if("attrs"in e&&e.attrs.value&&n in e.attrs.keys)if(a=f(e.attrs.value)&&r in e.attrs.value?e.attrs.value[r]:e.attrs.value,a instanceof Array){if(o=c(s(a,t,r),n),o.length)return o}else if(t instanceof Array){if(a=[function(){var e,n,r;if(i in a){for(r=[],e=0,n=t.length;e=0}):e.filter(function(e){return e[n]===t})},r=function(e,t,n){return"d3plus"in e||(e.d3plus={}),"data"in e.d3plus||(e.d3plus.data={}),!(n.data.changed||n.attrs&&n.attrs.changed)&&t in e.d3plus.data||(e.d3plus.data[t]={}),e},d=function(e,t,n,r,a){var i,o,l,s,u,c,d;if(null===a)return a;c="time"in e&&e.time.value===r,a instanceof Array||(a=[a]);for(l=s=0,u=a.length;s=0?(n.url=e,[]):(r=d3.selectAll(e),r.size()?r:(e.indexOf(".")>=0&&(n.url=e),[])):e}},{}],90:[function(e,t,n){var r,a;r=e("../../../util/copy.coffee"),a=e("../../../array/update.coffee"),t.exports=function(e,t,n){return t.process===Array?a(r(t.value),n):"object"==typeof t.process&&"string"==typeof n?t.process[n]:"function"==typeof t.process?t.process(n,e,t):n}},{"../../../array/update.coffee":37,"../../../util/copy.coffee":210}],91:[function(e,t,n){var r;r=e("../../../client/css.coffee"),t.exports=function(e,t,n){return e===!1||e.indexOf("fa-")<0||0===e.indexOf("fa-")&&r("font-awesome")?e:n.fallback}},{"../../../client/css.coffee":38}],92:[function(e,t,n){t.exports=function(e,t){var n,r,a,i,o,l,s,u,c,f,d,p,h;if("string"==typeof e){for(e=e.split(" "),n=r=0,o=e.length;r=0?(v=e.format.locale.value.error.accepted,f=e.format.locale.value.visualization[e.type.value]||e.type.value,o.warning(a(v,g,l,f,h),l)):(v=e.format.locale.value.dev.accepted,o.warning(a(v,g,s,h),l))}return!c}},{"../../array/contains.coffee":35,"../../string/format.js":176,"../../string/list.coffee":177,"../console/print.coffee":54}],94:[function(e,t,n){t.exports=function(e){var t;return t=["auto","optimizeSpeed","crispEdges","geometricPrecision"],t.indexOf(e)>=0||(e="crispEdges"),{accepted:t,value:e}}},{}],95:[function(e,t,n){var r,a;a=e("../../object/validate.coffee"),r=function(e,t){var n;e.changed&&(e.changed=!1),"draw"===t&&(e.frozen=!1,e.update=!0,e.first=!1);for(n in e)n.indexOf("d3plus")<0&&a(e[n])&&r(e[n],n)},t.exports=r},{"../../object/validate.coffee":175}],96:[function(e,t,n){var r,a,i,o,l,s,u,c,f;r=e("../../util/copy.coffee"),a=e("../../util/d3selection.coffee"),f=e("../../object/validate.coffee"),i=e("../../object/merge.coffee"),o=e("../console/print.coffee"),l=e("./process/detect.coffee"),s=e("./rejected.coffee"),u=e("../../string/format.js"),c=e("../../array/update.coffee"),t.exports=function(e,t,n,d,p){var h,v,g,m,y,x,b,w,_,k,z,M,A,j;if(M="value"!==d&&d&&d!==t?'"'+d+'" '+e.format.locale.value.dev.of+" ."+t+"()":"."+t+"()",h="value"===d&&"accepted"in n?n.accepted:f(n[d])&&"accepted"in n[d]?n[d].accepted:[p],!s(e,h,p,t,M)){if(f(n[d])&&"value"in n[d]&&(k=d,n=n[d],d="value"),"value"===d&&"process"in n&&(p=l(e,n,p)),n[d]instanceof Array||n[d]!==p||void 0===p){if(n.changed=!0,n.loaded&&(n.loaded=!1),"history"in e&&"draw"!==t&&(v=r(n),v.method=t,e.history.chain.push(v)),n.previous=n[d],"id"in e&&"value"===d&&"nesting"in n)if("id"!==t){if("object"!=typeof n.nesting&&(n.nesting={}),f(p)){for(x in p)"string"==typeof p[x]&&(p[x]=[p[x]]);n.nesting=i(n.nesting,p),e.id.value in n.nesting||(n.nesting[e.id.value]=p[d3.keys(p)[0]])}else p instanceof Array?n.nesting[e.id.value]=p:n.nesting[e.id.value]=[p];n[d]=n.nesting[e.id.value][0]}else p instanceof Array?(n.nesting=p,"depth"in e&&e.depth.value=e.id.nesting.length?e.depth.value=e.id.nesting.length-1:p<0?e.depth.value=0:e.depth.value=p,e.id.value=e.id.nesting[e.depth.value],"object"==typeof e.text.nesting&&(_=e.text.nesting[e.id.value],_&&(e.text.nesting[e.id.value]="string"==typeof _?[_]:_,e.text.value=_ instanceof Array?_[0]:_))):f(n[d])&&f(p)?n[d]=i(n[d],p):n[d]=p;"value"===d&&n.global&&(y=n[d].length>0,b=k||d,b in e&&(y&&e.data[b].indexOf(t)<0||!y&&e.data[b].indexOf(t)>=0)&&(e.data[b]=c(e.data[b],t))),"value"===d&&n.dataFilter&&e.data&&e.data.filters.indexOf(t)<0&&e.data.filters.push(t),e.dev.value&&n.changed&&void 0!==n[d]&&(w=n[d]instanceof Array&&n[d].length>10,m=a(n[d]),A="function"==typeof n[d],j=w||m||A?null:"string"==typeof n[d]?n[d]:JSON.stringify(n[d]),null!==j&&j.length<260?(z=e.format.locale.value.dev.setLong,o.log(u(z,M,'"'+j+'"'))):(z=e.format.locale.value.dev.set,o.log(u(z,M))))}else z=e.format.locale.value.dev.noChange,e.dev.value&&o.comment(u(z,M));"value"===d&&n.callback&&!n.url&&(g="function"==typeof n.callback?n.callback:n.callback.value,g&&g(p,e.self))}}},{"../../array/update.coffee":37,"../../object/merge.coffee":174,"../../object/validate.coffee":175,"../../string/format.js":176,"../../util/copy.coffee":210,"../../util/d3selection.coffee":211,"../console/print.coffee":54,"./process/detect.coffee":90,"./rejected.coffee":93}],97:[function(e,t,n){var r=e("../console/print.coffee"),a=e("../../string/format.js");t.exports=function(e){if(e.dev.value){var t="analyzing edges list";r.time(t)}var n=e.types[e.type.value].requirements;n instanceof Array||(n=[n]);var i=n.indexOf("nodes")>=0&&!e.nodes.value;if(i){e.nodes.value=[];var o=[];e.nodes.changed=!0}e.edges.value.forEach(function(t){["source","target"].forEach(function(n){var r=typeof t[e.edges[n]];if("object"!==r)if("number"!==r||i||"number"===e.data.keys[e.id.value])if(i&&o.indexOf(t[e.edges[n]])>=0)t[e.edges[n]]=e.nodes.value.filter(function(r){return r[e.id.value]===t[e.edges[n]]})[0];else{var a={};a[e.id.value]=t[e.edges[n]],t[e.edges[n]]=a}else t[e.edges[n]]=e.nodes.value[t[e.edges[n]]];var l=t[e.edges[n]];i&&o.indexOf(l[e.id.value])<0&&(o.push(l[e.id.value]),e.nodes.value.push(l))}),"keys"in e.data||(e.data.keys={}),e.id.value in e.data.keys||(e.data.keys[e.id.value]=typeof t[e.edges.source][e.id.value])}),e.edges.value=e.edges.value.filter(function(t){var n=t[e.edges.source][e.id.value],i=t[e.edges.target][e.id.value];if(n===i){var o=e.format.locale.value.dev.sameEdge;return r.warning(a(o,'"'+n+'"'),"edges"),!1}return!0}),e.edges.linked=!0,e.dev.value&&r.timeEnd(t)}},{"../../string/format.js":176,"../console/print.coffee":54}],98:[function(e,t,n){var r=e("./hideElement.js");t.exports=function(e){function t(e,t){[].forEach.call(t.attributes,function(t){if(/^data-/.test(t.name)){var n=t.name.substr(5).replace(/-(.)/g,function(e,t){return t.toUpperCase()});e[n]=t.value}}),n.forEach(function(n){null!==t.getAttribute(n)&&(e[n]=t.getAttribute(n))})}var n=[e.color.value,e.icon.value,e.keywords.value,e.alt.value,"style"];e.text.value||e.self.text("text"),n=n.concat(e.id.nesting),e.self.data({element:e.data.value});var a=e.data.element.value.node().tagName.toLowerCase(),i=e.data.element.value.attr("type"),o=[];if("select"===a){var l=e.data.element.value.node().id;l&&e.self.container({id:l}),e.data.element.value.selectAll("option").each(function(n,r){var a={};if(a.text=d3.select(this).text(),t(a,this),o.push(a),this.selected)for(var r=e.id.nesting.length-1;r>=0;r--){var i=e.id.nesting[r];if(i in a){e.self.focus(a[i]);break}}})}else if("input"===a&&"radio"===i){var s=e.data.element.value.node().getAttribute("name");s&&e.self.container({id:s}),e.data.element.value.each(function(n,a){var i={};t(i,this);var l=i[e.id.value]||this.id||!1;if(l&&isNaN(parseFloat(l))){var s=d3.select("label[for="+l+"]");s.empty()||(i.text=s.html(),s.call(r))}o.push(i),this.checked&&e.self.focus(i[e.id.value])})}!e.focus.value.length&&o.length&&(e.data.element.value.node().selectedIndex=0,e.self.focus(o[0][e.id.value]));var u=d3.select("legend[for="+e.container.id+"]");u.empty()||(e.self.title(u.html()),u.call(r));var c=!!e.container.value&&e.container.value.node().tagName.toLowerCase();return e.container.value!==!1&&"body"!==c||(e.container.value=d3.select(e.data.element.value.node().parentNode)),e.data.element.value.call(r),o}},{"./hideElement.js":99}],99:[function(e,t,n){t.exports=function(e){e.style("position","absolute","important").style("clip","rect(1px 1px 1px 1px)","important").style("clip","rect(1px, 1px, 1px, 1px)","important").style("width","1px","important").style("height","1px","important").style("margin","-1px","important").style("padding","0","important").style("border","0","important").style("overflow","hidden","important")}},{}],100:[function(e,t,n){var r=e("../console/print.coffee");t.exports=function(e){if("network"===e.type.value){if(e.dev.value){var t="analyzing node positions";r.time(t)}var n=e.nodes.value.filter(function(e){return"number"==typeof e.x&&"number"==typeof e.y}).length;if(n===e.nodes.value.length)e.nodes.positions=!0;else{var a=d3.layout.force().size([e.width.viz,e.height.viz]).nodes(e.nodes.value).links(e.edges.value),i=e.edges.strength.value;i&&("string"==typeof i?a.linkStrength(function(e){return e[i]}):a.linkStrength(i));var o=50,l=.01;a.start();for(var s=o;s>0&&(a.tick(),!(a.alpha()r;c=1<=r?++n:--n)a.push(function(){var t,n,r;for(r=[],n=0,t=e.length;nw;d=0<=w?++v:--v){for(o=[function(){var e,t,r;for(r=[],b=e=0,t=n;0<=t?et;b=0<=t?++e:--e)r.push(1);return r}()],f=[0],p=m=0,_=t.maxDegree;0<=_?m<_:m>_;p=0<=_?++m:--m)(d&1<0&&(o.push(i[p]),f.push(p+1));a=r.transpose(o),h=f.length,s=r.dot(r.dot(r.inv(r.dot(o,a)),o),A),j=r.dot(a,s),k=r.sub(A,j),M=r.dot(k,k),z=M/(n-h),g=-.5*n*Math.log(2*Math.PI)-.5*n*Math.log(z)-M/(2*z),u=-2*g+h*(Math.log(n)-Math.log(2*Math.PI)),us;t=0<=s?++l:--l)i=r[t]-a[t],o+=i*i;return o},o=function(){var n,r,i;for(i=[],a=n=0,r=e.length;0<=r?nr;a=0<=r?++n:--n)i.push(p(a,u[a][t-1]));return i}(),f=function(e,t){return Math.max(p(e,t),o[t])},l=function(e){var n,r,a,i,o;for(i=0,o=u[e],r=0,a=o.length;rn;a=0<=n?++t:--t)r.push(l(a));return r}(),d=function(){var r,o,l,c,f,d;for(d=[],a=r=0,c=e.length;0<=c?rc;a=0<=c?++r:--r){for(n=0,f=u[a],o=0,l=f.length;ot.data.large;if(t.draw.timing=t.draw.first||n||u?0:t.timing.ui,t.data.value instanceof Array){if(t.dev.value&&f.group('drawing "'+t.type.value+'"'),t.data.changed&&(t.data.cache={},o(t,"data"),i(t)),t.data.viz=s(t),t.data.sort.value&&(t.data.changed||t.order.changed||t.order.sort.changed)&&r(t.data.viz,t.order.value||t.text.value,t.order.sort.value,t.color.value,t),t.focus.value===!1&&["auto","button"].indexOf(t.type.value)<0){var a=t.data.element.value;if(a&&"select"===a.node().tagName.toLowerCase()){var d=a.property("selectedIndex");d=d<0?0:d;var p=a.selectAll("option")[0][d],h=p.getAttribute("data-"+t.id.value)||p.getAttribute(t.id.value);h&&(t.focus.value=h)}t.focus.value===!1&&t.data.viz.length&&(t.focus.value=t.data.viz[0][t.id.value]),t.dev.value&&t.focus.value!==!1&&f.log('"value" set to "'+t.focus.value+'"')}var v=function(e,n){n="number"!=typeof n?1===t.id.nesting.length?0:t.id.nesting.length-1:n;var r=t.id.nesting[n];return n>0&&(!(r in e)||e[r]instanceof Array)?v(e,n-1):r};if(t.data.changed){"auto"===t.search.value?t.data.viz.length>10?(t.search.enabled=!0,t.dev.value&&f.log("Search enabled.")):(t.search.enabled=!1,t.dev.value&&f.log("Search disabled.")):t.search.enabled=t.search.value;var g=t.data.element.value?t.data.element.value.node().tagName.toLowerCase():"";if(t.data.element.value&&"select"===g){var m=[];for(var y in t.data.nested.all)m=m.concat(t.data.nested.all[y]);options=t.data.element.value.selectAll("option").data(m,function(e){var t=!!e&&v(e);return!!(e&&t in e)&&e[t]}),options.exit().remove(),options.enter().append("option"),options.each(function(e){var n=v(e),r=n===t.id.value?t.text.value||t.id.value:t.text.nesting!==!0&&n in t.text.nesting?t.text.nesting[n]:n;for(var a in e)"object"!=typeof e[a]&&(a===r&&d3.select(this).html(e[a]),["alt","value"].indexOf(a)>=0?d3.select(this).attr(a,e[a]):d3.select(this).attr("data-"+a,e[a]));e[n]===t.focus.value?this.selected=!0:this.selected=!1})}}else if(t.focus.changed&&t.data.element.value){var x=t.data.element.value.node().tagName.toLowerCase();if("select"===x)t.data.element.value.selectAll("option").each(function(e){e[v(e)]===t.focus.value?this.selected=!0:this.selected=!1});else{var x=t.data.element.value.attr("type").toLowerCase();"radio"===x&&t.data.element.value.each(function(e){this.value===t.focus.value?this.checked=!0:this.checked=!1})}}if("auto"!==t.type.value){if(!t.container.ui){t.container.ui=t.container.value.selectAll("div#d3plus_"+t.type.value+"_"+t.container.id).data(["container"]);var b=t.data.element.value?t.data.element.value[0][0]:null;if(b)if(b.id)b="#"+b.id;else{var w=b.getAttribute(t.id.value)?t.id.value:"data-"+t.id.value;b=b.getAttribute(w)?"["+w+"="+b.getAttribute(w)+"]":null}t.container.ui.enter().insert("div",b).attr("id","d3plus_"+t.type.value+"_"+t.container.id).style("position","relative").style("overflow","visible").style("vertical-align","top")}t.container.ui.style("display",t.ui.display.value),t.container.ui.transition().duration(t.draw.timing).style("margin",t.ui.margin.css);var _=t.container.ui.selectAll("div.d3plus_title").data(t.title.value?[t.title.value]:[]);_.enter().insert("div","#d3plus_"+t.type.value+"_"+t.container.id).attr("class","d3plus_title").style("display","inline-block"),_.style("color",t.font.color).style("font-family",t.font.family.value).style("font-size",t.font.size+"px").style("font-weight",t.font.weight).style("padding",t.ui.padding.css).style("border-color","transparent").style("border-style","solid").style("border-width",t.ui.border+"px").text(String).each(function(e){t.margin.left=this.offsetWidth})}if(t.data.value.length){var k=t.format.locale.value.visualization[t.type.value];t.dev.value&&f.time("drawing "+k),t.types[t.type.value](t),t.dev.value&&f.timeEnd("drawing "+k)}else!t.data.url||t.data.loaded&&!t.data.stream||l(t,"data",t.self.draw);t.dev.value&&f.timeEnd("total draw time"), +c(t)}},a(t,{active:e("./methods/active.coffee"),alt:e("./methods/alt.coffee"),color:e("./methods/color.coffee"),config:e("./methods/config.coffee"),container:e("./methods/container.coffee"),data:e("./methods/data.js"),depth:e("./methods/depth.coffee"),dev:e("./methods/dev.coffee"),draw:e("./methods/draw.js"),focus:e("./methods/focus.coffee"),font:e("./methods/font.coffee"),format:e("./methods/format.coffee"),height:e("./methods/height.coffee"),history:e("./methods/history.coffee"),hover:e("./methods/hover.coffee"),icon:e("./methods/icon.coffee"),id:e("./methods/id.coffee"),keywords:e("./methods/keywords.coffee"),margin:e("./methods/margin.coffee"),open:e("./methods/open.coffee"),order:e("./methods/order.coffee"),remove:e("./methods/remove.coffee"),search:e("./methods/search.coffee"),select:e("./methods/select.coffee"),selectAll:e("./methods/selectAll.coffee"),text:e("./methods/text.coffee"),timing:e("./methods/timing.coffee"),title:e("./methods/title.coffee"),type:e("./methods/type.coffee"),ui:e("./methods/ui.coffee"),width:e("./methods/width.coffee")}),t.self}},{"../array/sort.coffee":36,"../client/ie.js":39,"../core/console/print.coffee":54,"../core/data/format.js":58,"../core/data/keys.coffee":60,"../core/data/load.coffee":61,"../core/fetch/data.js":66,"../core/methods/attach.coffee":82,"../core/methods/reset.coffee":95,"./methods/active.coffee":107,"./methods/alt.coffee":108,"./methods/color.coffee":109,"./methods/config.coffee":110,"./methods/container.coffee":111,"./methods/data.js":112,"./methods/depth.coffee":113,"./methods/dev.coffee":114,"./methods/draw.js":115,"./methods/focus.coffee":116,"./methods/font.coffee":117,"./methods/format.coffee":118,"./methods/height.coffee":119,"./methods/history.coffee":120,"./methods/hover.coffee":121,"./methods/icon.coffee":122,"./methods/id.coffee":123,"./methods/keywords.coffee":124,"./methods/margin.coffee":125,"./methods/open.coffee":126,"./methods/order.coffee":127,"./methods/remove.coffee":128,"./methods/search.coffee":129,"./methods/select.coffee":130,"./methods/selectAll.coffee":131,"./methods/text.coffee":132,"./methods/timing.coffee":133,"./methods/title.coffee":134,"./methods/type.coffee":135,"./methods/ui.coffee":136,"./methods/width.coffee":137,"./types/auto.js":138,"./types/button/button.coffee":139,"./types/drop/drop.coffee":144,"./types/toggle.js":161}],107:[function(e,t,n){var r;r=e("../../core/methods/filter.coffee"),t.exports={accepted:[!1,Array,Function,Number,String],value:!1}},{"../../core/methods/filter.coffee":83}],108:[function(e,t,n){var r;r=e("../../core/methods/filter.coffee"),t.exports={accepted:[!1,Array,Function,Object,String],mute:r(!0),solo:r(!0),value:"alt"}},{"../../core/methods/filter.coffee":83}],109:[function(e,t,n){t.exports={accepted:[String],value:"color"}},{}],110:[function(e,t,n){t.exports={accepted:[Object],objectAccess:!1,process:function(e,t){var n,r;for(n in e)r=e[n],n in t.self&&t.self[n](r);return e},value:{}}},{}],111:[function(e,t,n){var r;r=e("../../util/d3selection.coffee"),t.exports={accepted:[!1,Array,Object,String],element:!1,id:"default",process:function(e){return e===!1?d3.select("body"):r(e)?e:e instanceof Array?d3.select(e[0][0]):(this.selector=e,d3.select(e))},value:d3.select("body")}},{"../../util/d3selection.coffee":211}],112:[function(e,t,n){var r=e("../../util/d3selection.coffee"),a=e("../../core/methods/process/data.coffee");t.exports={accepted:[!1,Array,Function,String],delimiter:{accepted:[String],value:"|"},element:{process:function(e,t){var n=!1;return r(e)?n=e:"string"!=typeof e||d3.select(e).empty()||(n=d3.select(e)),n&&t.self.container(d3.select(n.node().parentNode)),n},value:!1},filetype:{accepted:[!1,"json","xml","html","csv","dsv","tsv","txt"],value:!1},filters:[],large:400,mute:[],process:function(e,t){return"default"===t.container.id&&e.length&&t.self.container({id:"default"+e.length}),a(e,t,this)},solo:[],sort:{accepted:[Boolean],value:!1},value:!1}},{"../../core/methods/process/data.coffee":89,"../../util/d3selection.coffee":211}],113:[function(e,t,n){t.exports={accepted:[Number],value:0}},{}],114:[function(e,t,n){t.exports={accepted:[Boolean],value:!1}},{}],115:[function(e,t,n){var r=e("../../util/d3selection.coffee"),a=e("../../core/parse/hideElement.js"),i=e("../../core/parse/element.js"),o=e("../../core/console/print.coffee"),l=e("../../string/format.js");t.exports={accepted:[void 0,Function],first:!0,frozen:!1,process:function(e,t){if(this.initialized===!1)return this.initialized=!0,e;if(!t.data.value||t.data.value instanceof Array&&!r(t.data.value)?t.data.element.value&&t.data.element.value.call(a):t.data.value=i(t),void 0===e&&"function"==typeof this.value&&(e=this.value),t.container.value===!1){var n=t.format.locale.value.dev.setContainer;o.warning(n,"container")}else if(t.container.value.empty()){var n=t.format.locale.value.dev.noContainer,s=t.container.selector||"";o.warning(l(n,'"'+s+'"'),"container")}else t.dev.value&&o.time("total draw time"),t.container.value.call(t.self);if("function"==typeof e&&t.history.chain.length){var u={};t.history.chain.forEach(function(e){var t=e.method;delete e.method,u[t]=e}),e(u),t.history.chain=[]}return e},update:!0,value:void 0}},{"../../core/console/print.coffee":54,"../../core/parse/element.js":98,"../../core/parse/hideElement.js":99,"../../string/format.js":176,"../../util/d3selection.coffee":211}],116:[function(e,t,n){t.exports={accepted:[!1,Number,String],deprecates:"highlight",process:function(e,t){var n,r,a,i,o,l,s,u,c,f;if(r=t.data.element.value,r&&["string","number"].indexOf(typeof e)>=0)if(a=r.node().tagName.toLowerCase(),i=r.attr("type"),"select"===a)for(f=r.selectAll("option"),o=l=0,u=f.length;l=0})),t.dev.value&&l.time("update"),u.classed("d3plus_button_active",function(e){return t.focus.value===e[t.id.value]}),t.draw.timing?u.transition().duration(t.draw.timing).call(a,t).call(s,t):u.call(a,t).call(s,t),u.call(i,t).call(o,t),t.dev.value&&l.timeEnd("update"),n.exit().remove()}},{"../../../core/console/print.coffee":54,"./functions/color.coffee":140,"./functions/icons.js":141,"./functions/mouseevents.coffee":142,"./functions/style.js":143}],140:[function(e,t,n){t.exports=function(t,n){var r,a,i;return r=e("../../../../color/legible.coffee"),a=e("../../../../color/lighter.coffee"),i=e("../../../../color/text.coffee"),t.style("background-color",function(e){var t;return t=n.focus.value===e[n.id.value]?n.ui.color.secondary.value:n.ui.color.primary.value,n.hover.value===e[n.id.value]&&(t=d3.rgb(t).darker(.15).toString()),t}).style("color",function(e){var t,a,o,l;return l=n.focus.value===e[n.id.value]?.75:1,o=e[n.icon.value]&&n.data.viz.length0){var f=t.ui.padding;f=3===o.length?f.top+"px "+(2*f.right+s)+"px "+f.bottom+"px "+(2*f.left+s)+"px":o.indexOf("icon")>=0&&!a||o.indexOf("selected")>=0&&a?f.top+"px "+f.right+"px "+f.bottom+"px "+(2*f.left+s)+"px":f.top+"px "+(2*f.right+s)+"px "+f.bottom+"px "+f.left+"px",c.style("padding",f)}else c.style("padding",t.ui.padding.css);if("number"==typeof t.width.value){var d=t.width.value;d-=parseFloat(c.style("padding-left"),10),d-=parseFloat(c.style("padding-right"),10),d-=2*t.ui.border,d+="px"}else var d="auto";c.style("width",d)})}},{"../../../../client/prefix.coffee":41,"../../../../client/rtl.coffee":42}],142:[function(e,t,n){t.exports=function(t,n,r){var a,i;return r=e("./color.coffee"),a=e("../../../../client/pointer.coffee"),i=e("../../../../client/ie.js"),t.on(a.over,function(e,t){return n.self.hover(e[n.id.value]),i||!n.draw.timing?d3.select(this).style("cursor","pointer").call(r,n):d3.select(this).style("cursor","pointer").transition().duration(n.timing.mouseevents).call(r,n)}).on(a.out,function(e){return n.self.hover(!1),i||!n.draw.timing?d3.select(this).style("cursor","auto").call(r,n):d3.select(this).style("cursor","auto").transition().duration(n.timing.mouseevents).call(r,n)}).on(a.click,function(e){return n.focus.value!==!1?n.self.focus(e[n.id.value]).draw():n.focus.callback?n.focus.callback(e,n.self):void 0})}},{"../../../../client/ie.js":39,"../../../../client/pointer.coffee":40,"./color.coffee":140}],143:[function(e,t,n){t.exports=function(e,t){e.style("position","relative").style("margin",t.ui.margin.css).style("display",t.ui.display.value).style("border-style","solid").style("border-width",t.ui.border+"px").style("font-family",t.font.family.value).style("font-size",t.font.size+"px").style("font-weight",t.font.weight).style("letter-spacing",t.font.spacing+"px")}},{}],144:[function(e,t,n){t.exports=function(t){var n,r,a,i,o,l,s,u,c,f,d;return a=e("./functions/element.coffee"),i=e("./functions/keyboard.coffee"),d=e("./functions/window.js"),f=e("./functions/width.js"),n=e("./functions/button.js"),s=e("./functions/selector.js"),u=e("./functions/title.js"),l=e("./functions/search.js"),o=e("./functions/list.js"),r=e("./functions/data.js"),c=e("./functions/update.js"),t.margin.top=0,t.margin.title=0,a(t),i(t),d(t),f(t),n(t),s(t),u(t),l(t),o(t),r(t),c(t)}},{"./functions/button.js":147,"./functions/data.js":148,"./functions/element.coffee":149,"./functions/keyboard.coffee":152,"./functions/list.js":153,"./functions/search.js":155,"./functions/selector.js":156,"./functions/title.js":157,"./functions/update.js":158,"./functions/width.js":159,"./functions/window.js":160}],145:[function(e,t,n){t.exports=function(e,t,n){var r=[],n=n||e.active.value;if(n instanceof Array)for(var a=0;a=0}},{}],146:[function(e,t,n){var r=e("../../../../core/console/print.coffee");t.exports=function(e){e.dev.value&&r.time("rotating arrow");var t="❯"===e.icon.drop.value?90:0;if(e.open.value!=e.open.flipped.value)var n=180+t;else var n=t;e.container.button.icon({select:{opacity:e.open.value?.5:1,rotate:n}}).draw(),e.dev.value&&r.timeEnd("rotating arrow")}},{"../../../../core/console/print.coffee":54}],147:[function(e,t,n){var r=e("../../../../util/copy.coffee"),a=e("../../../../client/pointer.coffee"),i=e("../../../form.js"),o=e("../../../../core/console/print.coffee");t.exports=function(e){if("button"in e.container||(e.dev.value&&o.time("creating main button"),e.container.button=i().container(e.container.ui).type("button").ui({margin:0}),e.dev.value&&o.timeEnd("creating main button")),e.focus.changed||e.data.changed||e.depth.changed){var t=e.depth.value,n=r(e.data.value.filter(function(n){for(var r=!1,a=0;a=0&&0===u.indexOf(e.search.term))o.push(t),r=!0;else if(u.indexOf(e.search.term)>=0)l.push(t),r=!0;else{var c=a(u).split("_");for(var f in c){if(r)break;for(var d in n)if(0===c[f].indexOf(n[d])){s.push(t),r=!0;break}}}}})}),e.data.filtered=d3.merge([o,l,s]),e.data.filtered.forEach(function(e,t){e.d3plus_order=t}),e.data.changed=!0,e.data.lastFilter="search",0===e.data.filtered.length){var c={},f=e.format.value(e.format.locale.value.ui.noResults);c[e.text.value||e.id.value]=r(f,'"'+e.search.term+'"'),e.data.filtered=[c]}}else e.data.filtered=e.data.viz,e.data.changed="viz"!==e.data.lastFilter,e.data.lastFilter="viz",e.id.nesting.length>1&&e.depth.valuee.height.max&&(t=e.height.max),e.self.height({secondary:t})}},{}],151:[function(e,t,n){var r,a,i,o;r=e("./active.js"),a=e("../../../../util/copy.coffee"),i=e("../../../form.js"),o=e("../../../../core/console/print.coffee"),t.exports=function(e){var t,n,l;e.open.value&&(e.dev.value&&o.time("updating list items"),"items"in e.container||(e.container.items=i().container(e.container.list).type("button").ui({border:0,display:"block",margin:0}).width(!1)),n=e.draw.timing?e.data.large:1,l=a(e.order),l.value=e.search.term.length?"d3plus_order":e.order.value,t=e.depth.value===e.id.nesting.length-1,(e.focus.changed||e.container.items.focus()===!1)&&e.container.items.focus(e.focus.value,function(t){var n,a,i,o;a=e.data.filtered.filter(function(n){return n[e.id.value]===t})[0],e.depth.value=0)return l===!1?l=0:38===u?e.open.value&&(l<=0?l=e.data.filtered.length-1:l-=1):40===u&&e.open.value&&(l>=e.data.filtered.length-1?l=0:l+=1),i="boolean"!=typeof e.hover.value?e.data.filtered[l][e.id.value]:e.focus.value,e.self.hover(i).open(!0).draw();if(13===u)return"boolean"!=typeof e.hover.value?(n=e.data.filtered.filter(function(t){return t[e.id.value]===e.hover.value})[0],r=e.depth.value,re.height.secondary&&(e.container.listHeight=e.height.secondary,l=!0),t&&e.container.selector.style("display","none"),e.dev.value&&r.timeEnd("calculating height"),l){e.dev.value&&r.time("calculating scroll position");var s=e.container.list.select("div").selectAll("div.d3plus_node"),u=s[0][0],c="boolean"!=typeof e.hover.value?e.hover.value:e.focus.value;s.each(function(t,n){t[e.id.value]===c&&(u=this)});var t=!1;"none"===e.container.selector.style("display")&&(t=!0,e.container.selector.style("display","block"));var f=u.offsetTop,d=u.offsetHeight||u.getBoundingClientRect().height,p=e.container.list.property("scrollTop");t&&e.container.selector.style("display","none"),t||e.data.changed||e.depth.changed?e.container.listScroll=f:(e.container.listScroll=p,fp+e.height.secondary-e.search.height&&(e.container.listScroll=f-(e.height.secondary-d-e.search.height))),e.dev.value&&r.timeEnd("calculating scroll position")}else e.container.listScroll=0}else e.container.listScroll=e.container.list.property("scrollTop"),e.container.listHeight=0}},{"../../../../core/console/print.coffee":54}],155:[function(e,t,n){var r=e("../../../../client/prefix.coffee"),a=e("../../../../core/console/print.coffee");t.exports=function(t){function n(e){e.style("padding",t.ui.padding.css).style("display","block").style("background-color",d3.rgb(t.ui.color.primary.value).darker(.15).toString())}function i(e){var n=t.width.secondary-2*t.ui.padding.left-2*t.ui.padding.right+2*t.ui.border;e.style("padding",t.ui.padding.left/2+t.ui.padding.right/2+"px").style("width",n+"px").style("border-width","0px").style("font-family",t.font.secondary.family.value).style("font-size",t.font.secondary.size+"px").style("font-weight",t.font.secondary.weight).style("text-align",t.font.secondary.align).style("outline","none").style(r()+"border-radius","0").attr("placeholder",t.format.value(t.format.locale.value.method.search))}t.dev.value&&a.time("creating search");var o=e("./data.js"),l=e("./items.coffee"),s=e("./update.js");t.container.search=t.container.selector.selectAll("div.d3plus_drop_search").data(t.search.enabled?["search"]:[]),t.draw.timing?(t.container.search.transition().duration(t.draw.timing).call(n),t.container.search.select("input").transition().duration(t.draw.timing).call(i)):(t.container.search.call(n),t.container.search.select("input").call(i)),t.container.search.enter().insert("div","#d3plus_drop_list_"+t.container.id).attr("class","d3plus_drop_search").attr("id","d3plus_drop_search_"+t.container.id).call(n).append("input").attr("id","d3plus_drop_input_"+t.container.id).style("-webkit-appearance","none").call(i),t.container.search.select("input").on("keyup."+t.container.id,function(e){var n=this.value;t.search.term!==n&&(t.search.term=n,o(t),l(t),s(t))}),t.container.search.exit().remove();var u=t.container.selector.style("display");t.container.selector.style("display","block"),t.search.height=t.search.enabled?t.container.search.node().offsetHeight||t.container.search.node().getBoundingClientRect().height:0, +t.container.selector.style("display",u),t.search.enabled&&(t.margin.title+=t.search.height),t.dev.value&&a.timeEnd("creating search")}},{"../../../../client/prefix.coffee":41,"../../../../core/console/print.coffee":54,"./data.js":148,"./items.coffee":151,"./update.js":158}],156:[function(e,t,n){t.exports=function(e){e.container.selector=e.container.ui.selectAll("div.d3plus_drop_selector").data(["selector"]),e.container.selector.enter().append("div").attr("class","d3plus_drop_selector").style("position","absolute").style("top","0px").style("z-index","-1").style("overflow","hidden"),e.container.selector.style("padding",e.ui.border+"px")}},{}],157:[function(e,t,n){var r=e("../../../../client/pointer.coffee"),a=e("../../../../color/lighter.coffee"),i=e("../../../../core/console/print.coffee"),o=e("../../../../color/text.coffee");t.exports=function(e){function t(t){t.style("padding",e.ui.padding.css).style("display","block").style("background-color",e.ui.color.secondary.value).style("font-family",e.font.secondary.family.value).style("font-size",e.font.secondary.size+"px").style("font-weight",e.font.secondary.weight).style("text-align",e.font.secondary.align).style("color",o(e.ui.color.secondary.value))}function n(t){if(!t.empty()){var n=0===e.icon.back.value.indexOf("fa-")?" fa "+e.icon.back.value:"";n="d3plus_drop_back"+n;var r=0===e.icon.back.value.indexOf("fa-")?"":e.icon.back.value;t.style("position","absolute").attr("class",n).style("top",e.ui.padding.top+e.font.secondary.size/2/2.5+"px").html(r)}}function l(t){var n=u?e.focus.value:e.format.locale.value.ui.back;t.text(e.format.value(n)).style("padding","0px "+(e.ui.padding.left+e.ui.padding.right)+"px")}if(e.open.value){e.dev.value&&i.time("creating title and back button");var s=1===e.id.solo.value.length&&e.depth.value>0,u=s,c=e.container.button.data(Object).viz[0];u=!0;for(var f=0;f=0&&(t=n.parentNode),t&&n&&!r(e.container.ui,t)&&(e.open.value||e.hover.value)&&e.self.open(!1).hover(!1).draw()});try{var n=window.parent.location.host===window.location.host}catch(e){var n=!1}n&&t.self!==window.top&&a(e,t.parent)};t.exports=a},{"../../../../util/child.coffee":208}],161:[function(e,t,n){var r=e("../form.js");t.exports=function(e){"buttons"in e.container||(e.container.buttons=r().container(e.container.ui).type("button"));var t=e.data.viz.length,n=!!e.width.value&&e.width.value/t,a=e.container.ui.selectAll("div.d3plus_toggle").data(e.data.viz,function(t){return t[e.id.value]});a.exit().remove(),a.enter().append("div").attr("class","d3plus_toggle").style("display","inline-block").style("vertical-align","top"),a.order().each(function(t){"form"in t.d3plus||(t.d3plus.form=r().container(d3.select(this)));var a=e.id.nesting.length>e.depth.value?e.id.nesting[e.depth.value+1]:e.id.value;t[a]instanceof Array?t.d3plus.form.container({id:e.container.id+"_"+t[e.id.value]}).data(t[a]).id(e.id.nesting.slice(1)).type("drop"):t.d3plus.form.data([t]).id(e.id.value).type("button"),t.d3plus.form.color(e.color).focus(e.focus.value,function(t){t!==e.focus.value&&e.self.focus(t).draw()}).hover(e.hover.value).icon({select:!1,value:e.icon.value}).font(e.font).format(e.format).order(e.order).text(e.text.value).ui({border:e.ui.border,color:e.ui.color,display:"inline-block",margin:0,padding:e.ui.padding.css}).width(n).draw()}),e.data.element.value&&e.data.element.value.on("focus."+e.container.id,function(){e.self.focus(this.value).hover(this.value).draw()}).on("blur."+e.container.id,function(){e.self.hover(!1).draw()})}},{"../form.js":106}],162:[function(e,t,n){var r,a,i,o,l,s,u,c,f,d,p;d=e("simplify-js"),t.exports=function(e,t){var n,a,o,s,u,f,h,v,g,m,y,x,b,w,_,k,z,M,A,j,E,S,O,N,F,C,T,q,P,B,D,R,I,L,V,U,Y,H,X,G,Z,W,J,Q,K,$,ee,te,ne,re,ae,ie,oe,le,se,ue,ce,fe,de,pe,he,ve,ge,me,ye,xe,be;if(e.length<3)return null;if(w=[],v=.5,u=5,null==t&&(t={}),null==t.maxAspectRatio&&(t.maxAspectRatio=15),null==t.minWidth&&(t.minWidth=0),null==t.minHeight&&(t.minHeight=0),null==t.tolerance&&(t.tolerance=.02),null==t.nTries&&(t.nTries=20),null!=t.angle&&(t.angle instanceof Array?f=t.angle:"number"==typeof t.angle?f=[t.angle]:"string"!=typeof t.angle||isNaN(t.angle)||(f=[Number(t.angle)])),null==f&&(f=d3.range(-90,90+u,u)),null!=t.aspectRatio&&(t.aspectRatio instanceof Array?g=t.aspectRatio:"number"==typeof t.aspectRatio?g=[t.aspectRatio]:"string"!=typeof t.aspectRatio||isNaN(t.aspectRatio)||(g=[Number(t.aspectRatio)])),null!=t.origin&&t.origin instanceof Array&&(W=t.origin[0]instanceof Array?t.origin:[t.origin]),h=Math.abs(d3.geom.polygon(e).area()),0===h)return null;if(ne=d3.extent(e,function(e){return e[0]}),Y=ne[0],R=ne[1],re=d3.extent(e,function(e){return e[1]}),H=re[0],I=re[1],ge=Math.min(R-Y,I-H)*t.tolerance,ve=function(){var t,n,r;for(r=[],t=0,n=e.length;t0&&(ve=d(ve,ge),e=function(){var e,t,n;for(n=[],e=0,t=ve.length;e=ye&&t.vdebug&&w.push({type:"aRatio",aRatio:n});fe-E>=ye;)me=(E+fe)/2,_=me/n,xe=Z[0],be=Z[1],te=[[xe-me/2,be-_/2],[xe+me/2,be-_/2],[xe+me/2,be+_/2],[xe-me/2,be+_/2]],te=c(te,s,Z),l(te,e)?(z=!0,T=me*_,B={cx:xe,cy:be,width:me,height:_,angle:o},E=me):(z=!1,fe=me),t.vdebug&&w.push({type:"rectangle",cx:xe,cy:be,width:me,height:_,areaFraction:me*_/h,angle:o,insidePoly:z});return[B,T,w]},p=function(e,t){var n,r;return n=t[0]-e[0],r=t[1]-e[1],n*n+r*r},s=function(e,t,n){var r,a,i,o,l;return l=t[1]a[1]||e[1]r[0]&&e[0]>a[0])&&(e[0]i)))},i=function(e,t){var n,r,a,i,o;for(i=-1,o=t.length,r=t[o-1],a=0;++iMath.max(t[0],n[0])+r||iMath.max(t[1],n[1])+r)},a=function(e,t,n,r){var a,i,o,l,s,u,c,f,d,p;return f=1e-9,l=e[0]-t[0],u=e[1]-t[1],s=n[0]-r[0],c=n[1]-r[1],o=l*c-u*s,Math.abs(o)t[f]&&yf&&(f=k[a][i],M=a,A=i);if(f<0)break;for(b in k[M])b!==A&&(b in k[A]?k[A][b]+=k[M][b]:k[A][b]=k[M][b]-2*u[A].score*u[b].score,k[b][A]=k[A][b]),delete k[b][M];for(b in k[A])b in k[M]||b===A||(k[A][b]-=2*u[M].score*u[b].score,k[b][A]=k[A][b]);for(F=u[M].nodes,x=0,_=F.length;x<_;x++)j=F[x],u[A].nodes.push(j);u[A].score+=u[M].score,t.vdebug&&v.push({type:"merge",father:A,child:M,nodes:u[A].nodes}),delete u[M],delete k[M],n+=f,y++}return s=function(){var e;e=[];for(o in u)c=u[o],e.push([o,c.nodes.length]);return e}(),s.sort(function(e,t){return t[1]-e[1]}),C=function(){var e,t,n;for(n=[],e=0,t=s.length;e=0?u=e:"share"===i?(u=0===e?0:e>=100?a.numberFormat(",f")(e):e>99?a.numberFormat(".3g")(e):a.numberFormat(".2g")(e),u+="%"):e<10&&e>-10?(l=e.toString().split("."),c=1,l.length>1&&(c=d3.min([parseFloat(l[1]).toString().length,2]),-13?(f=d3.formatPrefix(e).symbol,f=f.replace("G","B"),e=d3.formatPrefix(e).scale(e),e=a.numberFormat(".3g")(e),e=e.replace(s.format.decimal,"."),e=parseFloat(e)+"",e=e.replace(".",s.format.decimal),u=e+f):u=3===l?a.numberFormat(",f")(e):0===e?0:e===parseInt(e,10)?a.numberFormat(".2")(e):a.numberFormat(".3g")(e),u.length>2&&""+u.indexOf(".0")===u.length-2&&(u=u.slice(0,u.length-2)),o&&i&&"format"in p&&i in p.format.affixes.value?(n=p.format.affixes.value[i],n[0]+u+n[1]):u)}},{"../core/locale/languages/en_US.coffee":72}],174:[function(e,t,n){var r,a;r=e("../util/d3selection.coffee"),a=e("./validate.coffee"),t.exports=function(e,t){var n,i;return n=function(e,t,i){var o,l,s;l=[];for(o in e)s=e[o],"undefined"!=typeof s?!i&&a(s)?("object"!=typeof t[o]&&(t[o]={}),l.push(n(s,t[o],0===o.indexOf("d3plus")))):!r(s)&&s instanceof Array?l.push(t[o]=s.slice(0)):l.push(t[o]=s):l.push(void 0);return l},i={},e&&n(e,i),t&&n(t,i),i}},{"../util/d3selection.coffee":211,"./validate.coffee":175}],175:[function(e,t,n){t.exports=function(e){return e&&e.constructor===Object}},{}],176:[function(e,t,n){t.exports=function(){var e=Array.prototype.slice.call(arguments),t=e.shift();return t.unkeyed_index=0,t.replace(/\{(\w*)\}/g,function(n,r){if(""===r&&(r=t.unkeyed_index,t.unkeyed_index++),r==+r)return"undefined"!==e[r]?e[r]:n;for(var a=0;an&&(o=e.length-n+1,e=e.slice(0,n-1),e[n-1]=r(i,o)),e.length>1&&(e[e.length-1]=t+" "+e[e.length-1]),e.join(", "))):e}},{"../core/locale/languages/en_US.coffee":72,"./format.js":176}],178:[function(e,t,n){t.exports=function(e){var t=["!","@","#","$","%","^","&","*","(",")","[","]","{","}",".",",","/","\\","|","'",'"',";",":","<",">","?","=","+"],n=[[/[\300-\306]/g,"A"],[/[\340-\346]/g,"a"],[/[\310-\313]/g,"E"],[/[\350-\353]/g,"e"],[/[\314-\317]/g,"I"],[/[\354-\357]/g,"i"],[/[\322-\330]/g,"O"],[/[\362-\370]/g,"o"],[/[\331-\334]/g,"U"],[/[\371-\374]/g,"u"],[/[\321]/g,"N"],[/[\361]/g,"n"],[/[\307]/g,"C"],[/[\347]/g,"c"]];return e+="",""+e.replace(/[^A-Za-z0-9\-_]/g,function(e){if(" "===e)return"_";if(t.indexOf(e)>=0)return"";for(var r=e,a=0;a=0?a[i]:l.indexOf(t.toLowerCase())>=0&&0!==r&&r!==e.length-1?t.toLowerCase():t.charAt(0).toUpperCase()+t.substr(1).toLowerCase()):""}))):""}},{"../core/locale/languages/en_US.coffee":72}],180:[function(e,t,n){var r,a;r=e("./foreign.coffee"),a=e("./tspan.coffee"),t.exports=function(e){e.text.html.value?r(e):a(e)}},{"./foreign.coffee":181,"./tspan.coffee":184}],181:[function(e,t,n){t.exports=function(e){var t,n,r,a,i;i=e.container.value,r=i.attr("font-family")||i.style("font-family"),t=e.align.value||i.attr("text-anchor")||i.style("text-anchor"),n=i.attr("fill")||i.style("fill"),a=i.attr("opacity")||i.style("opacity"),t="end"===t?"right":"middle"===t?"center":"left",d3.select(i.node().parentNode).append("foreignObject").attr("width",e.width.value+"px").attr("height",e.height.value+"px").attr("x","0px").attr("y","0px").append("xhtml:div").style("font-family",r).style("font-size",e.size.value[1]+"px").style("color",n).style("text-align",t).style("opacity",a).text(e.text.current)}},{}],182:[function(e,t,n){t.exports=function(e){var t,n,r,a,i,o,l,s,u,c;if(n=e.container.value,a=n.node().previousElementSibling,o=a?a.tagName.toLowerCase():"",a&&(a=d3.select(a)),e.container.x=e.x.value||parseFloat(n.attr("x"),10),e.container.y=e.y.value||parseFloat(n.attr("y"),10),a&&(e.shape.accepted.indexOf(o)>=0&&e.self.shape(o), +"rect"===o?(u=parseFloat(a.attr("x"),10)||0,c=parseFloat(a.attr("y"),10)||0,e.padding.value===!1&&(t=Math.abs(u-e.container.x),t&&e.self.padding(t)),e.container.x||(e.container.x=u+e.padding.value),e.container.y||(e.container.y=c+e.padding.value),e.width.value||(s=parseFloat(a.attr("width")),e.self.width(s)),e.height.value||(r=parseFloat(a.attr("height")),e.self.height(r))):"circle"===o?(i=parseFloat(a.attr("r"),10),u=parseFloat(a.attr("cx"),10)||0,u-=i,c=parseFloat(a.attr("cy"),10)||0,c-=i,e.padding.value===!1&&(t=Math.abs(u-e.container.x),t&&e.self.padding(t)),e.container.x||(e.container.x=u+e.padding.value),e.container.y||(e.container.y=c+e.padding.value),e.width.value||e.self.width(2*i,10),e.height.value||e.self.height(2*i,10)):(e.width.value||e.self.width(500),e.height.value||e.self.height(500))),e.container.x||(e.container.x=0),e.container.y||(e.container.y=0),e.width.inner=e.width.value-2*e.padding.value,e.height.inner=e.height.value-2*e.padding.value,l=n.attr("font-size")||n.style("font-size"),l=parseFloat(l,10),e.container.fontSize=l,e.container.dy=parseFloat(n.attr("dy"),10),!e.size.value)return e.resize.value?e.self.size([4,80]):e.self.size([l/2,l])}},{}],183:[function(e,t,n){t.exports=function(e){var t;if(e.text.value||(t=e.container.value.text(),t&&(t.indexOf("tspan")>=0&&(t.replace(/\<\/tspan\>\/g," "),t.replace(/\<\/tspan\>/g,""),t.replace(/\/g,"")),t=t.replace(/(\r\n|\n|\r)/gm,""),t=t.replace(/^\s+|\s+$/g,""),e.self.text(t))),e.text.value instanceof Array?e.text.phrases=e.text.value.filter(function(e){return["string","number"].indexOf(typeof e)>=0}):e.text.phrases=[e.text.value+""],!e.align.value)return e.container.align=e.container.value.style("text-anchor")||e.container.value.attr("text-anchor")}},{}],184:[function(e,t,n){var r;r=e("../../client/rtl.coffee"),t.exports=function(e){var t,n,a,i,o,l,s,u,c,f,d,p,h,v,g,m,y,x,b,w,_,k,z,M,A,j,E,S,O,N,F;return d=function(t){var r;return r=!v||t?e.container.value.append("tspan"):e.container.value.insert("tspan","tspan"),r.attr("x",S+"px").attr("dy",n+"px").style("baseline-shift","0%").attr("dominant-baseline","alphabetic")},f=e.rotate.value===-90||90===e.rotate.value,A=f?e.height.inner:e.width.inner,l=f?e.width.inner:e.height.inner,t="circle"===e.shape.value?"middle":e.align.value||e.container.align||"start",O="end"===t||"start"===t&&r?A:"middle"===t?A/2:0,M=e.valign.value||"top",S=e.container.x+O,i=e.resize.value?e.size.value[1]:e.container.fontSize||e.size.value[0],n=e.container.dy||1.1*i,_=null,h=null,j=null,v=!1,F=0,"circle"===e.shape.value&&("middle"===M?F=l/n%1*n/2:"end"===M&&(F=l/n%1*n)),e.container.value.attr("text-anchor",t).attr("font-size",i+"px").style("font-size",i+"px").attr("x",e.container.x).attr("y",e.container.y),z=function(){if(_.remove(),v?(s++,_=e.container.value.select("tspan")):(s--,_=d3.select(e.container.value.node().lastChild)),!_.empty())return j=_.text().match(/[^\s-]+-?/g),a()},u=function(){var t;return"circle"===e.shape.value?(t=(s-1)*n+F,t>l/2&&(t+=n),2*Math.sqrt(t*(2*(A/2)-t))):A},a=function(){var t,n;return j&&j.length?(n=j.pop(),t=n.charAt(n.length-1),1===n.length&&e.text.split.value.indexOf(n)>=0?a():(e.text.split.value.indexOf(t)>=0&&(n=n.substr(0,n.length-1)),_.text(j.join(" ")+" "+n+"..."),_.node().getComputedTextLength()>u()?a():void 0)):z()},p=function(t){var n,r,a,i;if(n=_.text(),i="",v){if(i=e.text.current.charAt(e.text.current.length-h.length-1)," "===i)for(a="",r=2;" "===i;)a+=" ",i=e.text.current.charAt(e.text.current.length-h.length-r),r++;else a="";h=t+a+h,_.text(t+a+n)}else{if(i=e.text.current.charAt(h.length)," "===i)for(a="",r=1;" "===i;)a+=" ",i=e.text.current.charAt(h.length+r),r++;else a="";h+=a+t,_.text(n+a+t)}if(Math.floor(_.node().getComputedTextLength())>u()||"\n"===i)return _.text(n),n.length&&(_=d()),_.text(t),v?s--:s++},w=1,s=null,c=null,E=function(){var t,r,a,i,o,u;for(e.container.value.text("").html(""),j=e.text.words.slice(),v&&j.reverse(),h="",_=d(!0),s=w,r=0,a=j.length;rl){z();break}for(p(u),o=!0;o;){for(i=e.text.current.charAt(h.length),t=1;" "===i;)i=e.text.current.charAt(h.length+t),t++;o=e.text.split.value.indexOf(i)>=0,o&&p(i)}}return s*n>l&&z(),c=Math.abs(s-w)+1},E(),c=0,e.container.value.selectAll("tspan").each(function(){if(d3.select(this).text().length)return c++}),"circle"===e.shape.value&&(b=l-c*n,b>n&&("middle"===M?(w=(b/n/2>>0)+1,E()):"bottom"===M&&(v=!0,w=l/n>>0,E()))),c=0,e.container.value.selectAll("tspan").each(function(){if(d3.select(this).text().length)return c++}),"top"===M?N=0:(o=c*n,N="middle"===M?l/2-o/2:l-o),N-=.2*n,k="translate(0,"+N+")",180===e.rotate.value||e.rotate.value===-180?(y=e.container.x+A/2,x=e.container.y+l/2):(g=e.rotate.value<0?A:l,y=e.container.x+g/2,x=e.container.y+g/2),m="rotate("+e.rotate.value+", "+y+", "+x+")",e.container.value.attr("transform",m+k)}},{"../../client/rtl.coffee":42}],185:[function(e,t,n){var r,a,i,o;r=e("./flow.coffee"),a=e("../../font/sizes.coffee"),o=function(e){var t;e.text.phrases.length&&(e.text.current=e.text.phrases.shift()+"",e.text.words=e.text.current.match(e.text.split.break),t=e.text.current.charAt(0),t!==e.text.words[0].charAt(0)&&(e.text.words[0]=t+e.text.words[0]),e.container.value.html(""),e.resize.value?i(e):r(e))},t.exports=o,i=function(e){var t,n,i,l,s,u,c,f,d,p,h,v,g,m,y,x,b;for(b=[],c=0;cf||m>l)&&(i=Math.sqrt(l/m),x=f/d,v=d3.min([i,x]),h=d3.max([e.size.value[0],Math.floor(h*v)])),u=Math.floor(.8*s),h>u&&(h=u),d*(h/e.size.value[1])<=f?(h!==e.size.value[1]&&e.self.size([e.size.value[0],h]),r(e)):o(e)}},{"../../font/sizes.coffee":104,"./flow.coffee":180}],186:[function(e,t,n){t.exports={accepted:[!1,"start","middle","end","left","center","right"],process:function(e){var t;return t=["left","center","right"].indexOf(e),t>=0&&(e=this.accepted[t+1]),e},value:!1}},{}],187:[function(e,t,n){arguments[4][110][0].apply(n,arguments)},{dup:110}],188:[function(e,t,n){var r;r=e("../../util/d3selection.coffee"),t.exports={accepted:[!1,Array,Object,String],element:!1,id:"default",process:function(e){return e!==!1&&(r(e)?e:e instanceof Array?d3.select(e[0][0]):(this.selector=e,d3.select(e)))},value:!1}},{"../../util/d3selection.coffee":211}],189:[function(e,t,n){arguments[4][114][0].apply(n,arguments)},{dup:114}],190:[function(e,t,n){var r,a;r=e("../../core/console/print.coffee"),a=e("../../string/format.js"),t.exports={accepted:[void 0],process:function(e,t){var n,i;return this.initialized===!1?e:(t.container.value===!1?(i=t.format.locale.value.dev.setContainer,r.warning(i,"container")):t.container.value.empty()?(i=t.format.locale.value.dev.noContainer,n=t.container.selector||"",r.warning(a(i,'"'+n+'"'),"container")):(t.dev.value&&r.time("total draw time"),t.container.value.call(t.self)),e)},value:void 0}},{"../../core/console/print.coffee":54,"../../string/format.js":176}],191:[function(e,t,n){var r,a;r=e("../../core/locale/locale.coffee"),a=e("../../object/merge.coffee"),t.exports={accepted:[Function,String],locale:{accepted:function(){return d3.keys(r)},process:function(e){var t,n;return t="en_US",n=r[t],e!==t&&(n=a(n,r[e])),this.language=e,n},value:"en_US"},process:function(e,t){if(this.initialized&&"string"==typeof e)t.self.format({locale:e});else if("function"==typeof e)return e;return this.value},value:"en_US"}},{"../../core/locale/locale.coffee":81,"../../object/merge.coffee":174}],192:[function(e,t,n){t.exports={accepted:[!1,Number],value:!1}},{}],193:[function(e,t,n){arguments[4][192][0].apply(n,arguments)},{dup:192}],194:[function(e,t,n){arguments[4][114][0].apply(n,arguments)},{dup:114}],195:[function(e,t,n){t.exports={accepted:[-180,-90,0,90,180],value:0}},{}],196:[function(e,t,n){t.exports={accepted:["circle","square"],value:!1}},{}],197:[function(e,t,n){t.exports={accepted:[Array,!1],value:!1}},{}],198:[function(e,t,n){t.exports={accepted:[!1,Array,Number,String],html:{accepted:[Boolean],value:!1},init:function(e){var t;return t=this.split.value,this.split.break=new RegExp("[^\\s\\"+t.join("\\")+"]+\\"+t.join("?\\")+"?","g"),!1},split:{accepted:[Array],process:function(e){return this.break=new RegExp("[^\\s\\"+e.join("\\")+"]+\\"+e.join("?\\")+"?","g"),e},value:["-","/",";",":","&"]}}},{}],199:[function(e,t,n){t.exports={accepted:[!1,"top","middle","bottom"],value:!1}},{}],200:[function(e,t,n){arguments[4][192][0].apply(n,arguments)},{dup:192}],201:[function(e,t,n){arguments[4][192][0].apply(n,arguments)},{dup:192}],202:[function(e,t,n){arguments[4][192][0].apply(n,arguments)},{dup:192}],203:[function(e,t,n){var r,a,i,o,l;r=e("../core/methods/attach.coffee"),i=e("./helpers/parseSize.coffee"),a=e("../core/console/print.coffee"),o=e("./helpers/parseText.coffee"),l=e("./helpers/wrap.coffee"),t.exports=function(){var t;return t={self:function(e){return e.each(function(){i(t),t.size.value[0]<=t.height.inner?(o(t),l(t)):t.container.value.html(""),t.dev.value&&a.timeEnd("total draw time")}),t.self}},r(t,{align:e("./methods/align.coffee"),config:e("./methods/config.coffee"),container:e("./methods/container.coffee"),dev:e("./methods/dev.coffee"),draw:e("./methods/draw.coffee"),format:e("./methods/format.coffee"),height:e("./methods/height.coffee"),padding:e("./methods/padding.coffee"),resize:e("./methods/resize.coffee"),rotate:e("./methods/rotate.coffee"),text:e("./methods/text.coffee"),shape:e("./methods/shape.coffee"),size:e("./methods/size.coffee"),valign:e("./methods/valign.coffee"),width:e("./methods/width.coffee"),x:e("./methods/x.coffee"),y:e("./methods/y.coffee")}),t.self}},{"../core/console/print.coffee":54,"../core/methods/attach.coffee":82,"./helpers/parseSize.coffee":182,"./helpers/parseText.coffee":183,"./helpers/wrap.coffee":185,"./methods/align.coffee":186,"./methods/config.coffee":187,"./methods/container.coffee":188,"./methods/dev.coffee":189,"./methods/draw.coffee":190,"./methods/format.coffee":191,"./methods/height.coffee":192,"./methods/padding.coffee":193,"./methods/resize.coffee":194,"./methods/rotate.coffee":195,"./methods/shape.coffee":196,"./methods/size.coffee":197,"./methods/text.coffee":198,"./methods/valign.coffee":199,"./methods/width.coffee":200,"./methods/x.coffee":201,"./methods/y.coffee":202}],204:[function(e,t,n){function r(){d3.selectAll("div.d3plus_tooltip_data_desc").style("height","0px"),d3.selectAll("div.d3plus_tooltip_data_help").style("background-color","#ccc")}var a=e("../core/locale/languages/en_US.coffee"),i=e("../client/pointer.coffee"),o=e("../color/legible.coffee"),l=e("./move.coffee"),s=e("../client/prefix.coffee"),u=e("../client/rtl.coffee"),c=e("./remove.coffee"),f=e("../client/scroll.js"),d=e("../client/scrollbar.coffee"),p=e("../string/list.coffee"),h=e("../color/text.coffee");t.exports=function(e){var t=e.fullscreen?250:200,n=s();e.width=e.width||t,e.max_width=e.max_width||386,e.id=e.id||"default",e.size=e.fullscreen||e.html?"large":"small",e.offset=e.offset||0,e.arrow_offset=e.arrow?8:0,e.x=e.x||0,e.y=e.y||0,e.parent=e.parent||d3.select("body"),e.curtain=e.curtain||"#fff",e.curtainopacity=e.curtainopacity||.8,e.background=e.background||"#fff",e.fontcolor=e.fontcolor||"#444",e.fontfamily=e.fontfamily||"sans-serif",e.fontweight=e.fontweight||"normal",e.fontsize=e.fontsize||"12px",e.style=e.style||"default",e.zindex="small"==e.size?2e3:500,e.locale=e.locale||a,e.stacked=e.stacked||!1;var v=e.parent?e.parent.node().offsetHeight||e.parent.node().getBoundingClientRect().height:0;if(e.iconsize||(e.iconsize="small"==e.size?22:50),e.parent.node()===document.body){e.limit=[window.innerWidth+f.x(),window.innerHeight+f.y()];var g=d();document.body.scrollHeight>window.innerHeight&&(e.limit[0]-=g)}else e.limit=[parseFloat(e.parent.style("width"),10),parseFloat(e.parent.style("height"),10)];if(e.title instanceof Array){var m=e.locale.ui.and,y=e.locale.ui.more;e.title=p(e.title,m,3,y)}if(c(e.id),e.anchor={},e.fullscreen)e.anchor.x="center",e.anchor.y="center",e.x=e.parent?e.parent.node().offsetWidth/2:window.innerWidth/2,e.y=e.parent?v/2:window.innerHeight/2;else if(e.align){var x=e.align.split(" ");e.anchor.y=x[0],x[1]?e.anchor.x=x[1]:e.anchor.x="center"}else e.anchor.x="center",e.anchor.y="top";var b=e.width-30;if(e.fullscreen){e.parent.append("div").attr("id","d3plus_tooltip_curtain_"+e.id).attr("class","d3plus_tooltip_curtain").style("background-color",e.curtain).style("opacity",e.curtainopacity).style("position","absolute").style("z-index",499).style("top","0px").style("right","0px").style("bottom","0px").style("left","0px").on(i.click,function(){c(e.id)})}var w=e.parent.append("div").datum(e).attr("id","d3plus_tooltip_id_"+e.id).attr("class","d3plus_tooltip d3plus_tooltip_"+e.size).style("color",e.fontcolor).style("font-family",e.fontfamily).style("font-weight",e.fontweight).style("font-size",e.fontsize+"px").style(n+"box-shadow","0px 1px 3px rgba(0, 0, 0, 0.25)").style("position","absolute").on(i.out,r);e.max_height&&w.style("max-height",e.max_height+"px"),e.fixed?(w.style("z-index",500),e.mouseevents=!0):w.style("z-index",2e3);var _=w.append("div").datum(e).attr("class","d3plus_tooltip_container").style("background-color",e.background).style("padding","6px");if(e.fullscreen&&e.html&&!e.stacked){z=e.parent?.75*e.parent.node().offsetWidth:.75*window.innerWidth,B=e.parent?.75*v:.75*window.innerHeight,_.style("width",z+"px").style("height",B+"px");var k=_.append("div").attr("class","d3plus_tooltip_body").style("padding-right","6px").style("display","inline-block").style("z-index",1).style("width",e.width+"px")}else{if("auto"==e.width){var z="auto";_.style("max-width",e.max_width+"px")}else var z=e.width-14+"px";var k=_.style("width",z)}if(e.title||e.icon)var M=k.append("div").attr("class","d3plus_tooltip_header").style("position","relative").style("z-index",1);if(e.fullscreen){w.append("div").attr("class","d3plus_tooltip_close").style("background-color",e.color).style("color",h(e.color)).style("position","absolute").style(n+"box-shadow","0 1px 3px rgba(0, 0, 0, 0.25)").style("font-size","20px").style("height","18px").style("line-height","14px").style("text-align","center").style("right","16px").style("top","-10px").style("width","18px").style("z-index",10).html("×").on(i.over,function(){d3.select(this).style("cursor","pointer").style(n+"box-shadow","0 1px 3px rgba(0, 0, 0, 0.5)")}).on(i.out,function(){d3.select(this).style("cursor","auto").style(n+"box-shadow","0 1px 3px rgba(0, 0, 0, 0.25)")}).on(i.click,function(){c(e.id)});d3.select("body").on("keydown.esc_"+e.id,function(){27===d3.event.keyCode&&(c(e.id),d3.select("body").on("keydown.esc_"+e.id,null))})}if(e.mouseevents){if(e.mouseevents!==!0){var A=d3.select(e.mouseevents).on(i.out),j=function(){var t=d3.event.toElement||d3.event.relatedTarget;if(t)var n="string"==typeof t.className?t.className:t.className.baseVal,a=0==n.indexOf("d3plus_tooltip");else var a=!1;t&&(E(w.node(),t)||E(e.mouseevents,t)||a)||(A(d3.select(e.mouseevents).datum()),r(),d3.select(e.mouseevents).on(i.out,A))},E=function(e,t){for(var n=t.parentNode;null!==n;){if(n==e)return!0;n=n.parentNode}return!1};d3.select(e.mouseevents).on(i.out,j),w.on(i.out,j);var S=d3.select(e.mouseevents).on(i.move);S&&w.on(i.move,S)}}else w.style("pointer-events","none");if(e.arrow){w.append("div").attr("class","d3plus_tooltip_arrow").style("background-color",e.background).style(n+"box-shadow","0px 1px 3px rgba(0, 0, 0, 0.25)").style("position","absolute").style("bottom","-5px").style("height","10px").style("left","50%").style("margin-left","-5px").style("width","10px").style(n+"transform","rotate(45deg)").style("z-index",-1)}if(e.icon){var O=M.append("div").attr("class","d3plus_tooltip_icon").style("width",e.iconsize+"px").style("height",e.iconsize+"px").style("z-index",1).style("background-position","50%").style("background-size","100%").style("background-image","url("+e.icon+")").style("display","inline-block").style("margin","0px 3px 3px 0px");"knockout"==e.style&&O.style("background-color",e.color),b-=O.node().offsetWidth}if(e.title){var N=e.max_width-6;e.icon&&(N-=e.iconsize+6),N+="px";M.append("div").attr("class","d3plus_tooltip_title").style("max-width",N).style("color",e.icon?e.fontcolor:o(e.color)).style("vertical-align","top").style("width",b+"px").style("display","inline-block").style("overflow","hidden").style("text-overflow","ellipsis").style("word-wrap","break-word").style("z-index",1).style("font-size","large"===e.size?"18px":"16px").style("line-height","large"===e.size?"20px":"17px").style("padding","large"===e.size?"3px 6px":"3px").text(e.title)}if(e.description){k.append("div").attr("class","d3plus_tooltip_description").style("font-size","12px").style("padding","6px").text(e.description)}if(e.data||e.html&&!e.fullscreen)var F=k.append("div").attr("class","d3plus_tooltip_data_container").style("overflow-y","auto").style("z-index",-1);if(e.data){var C=0,T={},q=null;e.data.forEach(function(t,a){t.group&&q!=t.group&&(q=t.group,F.append("div").attr("class","d3plus_tooltip_data_title").style("font-size","12px").style("font-weight","bold").style("padding","6px 3px 0px 3px").text(t.group));var l=F.append("div").attr("class","d3plus_tooltip_data_block").style("font-size","12px").style("padding","3px 6px").style("position","relative").datum(t);t.highlight===!0?l.style("color",o(e.color)):(t.allColors||t.highlight!==e.color)&&l.style("color",o(t.highlight));var c=l.append("div").attr("class","d3plus_tooltip_data_name").style("display","inline-block").html(t.name).on(i.out,function(){d3.event.stopPropagation()});if(t.link&&c.style("cursor","pointer").on(i.click,t.link),t.value instanceof Array){var f=e.locale.ui.and,d=e.locale.ui.more;t.value=list(t.value,f,3,d)}var p=l.append("div").attr("class","d3plus_tooltip_data_value").style("display","block").style("position","absolute").style("text-align","right").style("top","3px").html(t.value).on(i.out,function(){d3.event.stopPropagation()});if(u?p.style("left","6px"):p.style("right","6px"),e.mouseevents&&t.desc){var h=l.append("div").attr("class","d3plus_tooltip_data_desc").style("color","#888").style("overflow","hidden").style(n+"transition","height 0.5s").style("width","85%").text(t.desc).on(i.out,function(){d3.event.stopPropagation()}),v=h.node().offsetHeight||h.node().getBoundingClientRect().height;h.style("height","0px");var g=c.append("div").attr("class","d3plus_tooltip_data_help").style("background-color","#ccc").style(n+"border-radius","5px").style("color","#fff").style("cursor","pointer").style("display","inline-block").style("font-size","8px").style("font-weight","bold").style("height","10px").style("margin","3px 0px 0px 3px").style("padding-right","1px").style("text-align","center").style("width","10px").style("vertical-align","top").style(s+"transition","background-color 0.5s").text("?").on(i.over,function(){var e=d3.select(this.parentNode.parentNode).style("color");d3.select(this).style("background-color",e),h.style("height",v+"px")}).on(i.out,function(){d3.event.stopPropagation()});c.style("cursor","pointer").on(i.over,function(){r();var e=d3.select(this.parentNode).style("color");g.style("background-color",e),h.style("height",v+"px")}),l.on(i.out,function(){d3.event.stopPropagation(),r()})}var m=parseFloat(p.style("width"),10);m>e.width/2&&(m=e.width/2),m>C&&(C=m),a!=e.data.length-1&&(t.group&&t.group==e.data[a+1].group||!t.group&&!e.data[a+1].group)&&F.append("div").attr("class","d3plus_tooltip_data_seperator").style("background-color","#ddd").style("display","block").style("height","1px").style("margin","0px 3px")}),F.selectAll(".d3plus_tooltip_data_name").style("width",function(){var e=parseFloat(d3.select(this.parentNode).style("width"),10);return e-C-30+"px"}),F.selectAll(".d3plus_tooltip_data_value").style("width",C+"px").each(function(e){var t=parseFloat(d3.select(this).style("height"),10);T[e.name]=t}),F.selectAll(".d3plus_tooltip_data_name").style("min-height",function(e){return T[e.name]+"px"})}!e.html||e.fullscreen&&!e.stacked||(F.append("div").html(e.html),e.js&&e.js(_));var P=k.append("div").attr("class","d3plus_tooltip_footer").style("font-size","10px").style("position","relative").style("text-align","center");if(e.footer&&P.html(e.footer),e.height=w.node().offsetHeight||w.node().getBoundingClientRect().height,e.html&&e.fullscreen&&!e.stacked){var B=e.height-12,z=w.node().offsetWidth-e.width-44;_.append("div").attr("class","d3plus_tooltip_html").style("width",z+"px").style("height",B+"px").style("display","inline-block").style("vertical-align","top").style("overflow-y","auto").style("padding","0px 12px").style("position","absolute").html(e.html),e.js&&e.js(_)}if(e.width=w.node().offsetWidth,"center"!=e.anchor.y?e.height+=e.arrow_offset:e.width+=e.arrow_offset,e.data||(!e.fullscreen||e.stacked)&&e.html){if(!e.fullscreen||e.stacked)var D=e.fixed?v-e.y-10:v-10,B=e.heighti.limit[0]&&(i.x=i.limit[0]-i.width),i.yi.limit[1]&&(i.y=i.limit[1]-i.height)),l.style("top",i.y+"px").style("left",i.x+"px"),i.arrow&&l.selectAll(".d3plus_tooltip_arrow").call(r)),l},r=function(e){return e.style("bottom",function(e){return"center"===e.anchor.y||e.flip?"auto":"-5px"}).style("right",function(e){return"center"!==e.anchor.y||e.flip?"auto":"-5px"}).style("top",function(e){return"center"!==e.anchor.y&&e.flip?"-5px":"center"===e.anchor.y?"50%":"auto"}).style("left",function(e){return"center"===e.anchor.y&&e.flip?"-5px":"center"!==e.anchor.y?"50%":"auto"}).style("margin-left",function(e){var t;return"center"===e.anchor.y?"auto":(t="right"===e.anchor.x?-e.width/2+e.arrow_offset/2:"left"===e.anchor.x?e.width/2-2*e.arrow_offset-5:-5,e.cx-e.width/2-5t&&(t=-(e.limit[0]-e.cx-e.width/2+5),t>e.width/2-11&&(t=e.width/2-11)),t+"px")}).style("margin-top",function(e){var t;return"center"!==e.anchor.y?"auto":(t="bottom"===e.anchor.y?-e.height/2+e.arrow_offset/2-1:"top"===e.anchor.y?e.height/2-2*e.arrow_offset-2:-9,e.cy-e.height/2-e.arrow_offsett&&(t=-(e.limit[1]-e.cy-e.height/2+e.arrow_offset),t>e.height/2-22&&(t=e.height/2-22)),t+"px")})}},{"../client/scroll.js":43}],206:[function(e,t,n){t.exports=function(e){return e?(d3.selectAll("div#d3plus_tooltip_curtain_"+e).remove(),d3.selectAll("div#d3plus_tooltip_id_"+e).remove()):(d3.selectAll("div.d3plus_tooltip_curtain").remove(),d3.selectAll("div.d3plus_tooltip").remove())}},{}],207:[function(e,t,n){t.exports=function(e,t){var n,r;return n=[],r=1/(t-1)*(e[1]-e[0]),d3.range(e[0],e[1]+r,r)}},{}],208:[function(e,t,n){var r;r=e("./d3selection.coffee"),t.exports=function(e,t){var n;if(!e||!t)return!1;for(r(e)&&(e=e.node()),r(e)&&(t=t.node()),n=t.parentNode;null!==n;){if(n===e)return!0;n=n.parentNode}return!1}},{"./d3selection.coffee":211}],209:[function(e,t,n){t.exports=function(e,t){var n,r;return t.constructor===String?(r=e.indexOf(t),r>-1?e[r]:e[0]):(n=e[0],e.forEach(function(e){if(Math.abs(t-e)=0,t?e:"relative"}),e.container.changed&&e.container.value.html(""),a=["width","height"],n=0,r=a.length;n=0?(a=window["inner"+i.charAt(0).toUpperCase()+i.slice(1)],r=document!==n&&d3.select(n),r&&("width"===i?(a-=parseFloat(r.style("margin-left"),10),a-=parseFloat(r.style("margin-right"),10),a-=parseFloat(r.style("padding-left"),10),a-=parseFloat(r.style("padding-right"),10)):(a-=parseFloat(r.style("margin-top"),10),a-=parseFloat(r.style("margin-bottom"),10),a-=parseFloat(r.style("padding-top"),10),a-=parseFloat(r.style("padding-bottom"),10))),e[i].value=a<=20?e[i].small:a):(a=parseFloat(d3.select(n).style(i),10),"number"==typeof a&&a>0?e[i].value=a:"BODY"!==n.tagName?t(n.parentNode):void 0)},t(e.container.value.node()),1===d3.selectAll("body > *:not(script)").size()&&d3.select("body").style("overflow","hidden"));e.container.value.style("width",e.width.value+"px").style("height",e.height.value+"px")}},{}],215:[function(e,t,n){var r=e("../../core/data/format.js"),a=e("../../core/data/color.js"),i=e("../../core/data/keys.coffee"),o=e("../../core/data/load.coffee"),l=e("./ui/drawer.js"),s=e("./ui/legend.js"),u=e("./ui/timeline.coffee"),c=e("./errorCheck.js"),f=e("../../core/fetch/data.js"),d=e("./finish.js"),p=e("./focus/tooltip.coffee"),h=e("./ui/history.coffee"),v=e("../../core/parse/edges.js"),g=e("../../core/parse/nodes.js"),m=e("../../core/console/print.coffee"),y=e("../../tooltip/remove.coffee"),x=e("./types/run.coffee"),b=e("./shapes/draw.js"),w=e("../../string/format.js"),_=e("./svg/enter.js"),k=e("./svg/update.js"),z=e("./ui/titles.js"),M=e("../../object/validate.coffee");t.exports=function(e){var t=[],n=e.type.value,A=e.format.locale.value,j=A.message.ui,E=A.message.draw,S=["data","attrs","coords","nodes","edges"];if(S.forEach(function(n){e.error.value||e[n].loaded||!e[n].url||t.push({function:function(e,t){o(e,n,t)},message:A.message.loading,wait:!0})}),e.draw.update){var O=A.visualization[n]||n,N=e.types[n].setup||!1,F=e.types[n].requirements||[],C=w(A.message.initializing,O),T=A.message.data;F instanceof Array||(F=[F]),O=O.toLowerCase(),e.error.value||"function"!=typeof N||t.push({function:function(e){if(e.dev.value){var t="running "+O+" setup";m.time(t)}N(e),e.dev.value&&m.timeEnd(t)},message:C}),e.container.changed&&t.push({function:_,message:C}),n in e.g.apps||t.push({function:function(e){if(e.dev.value){var t="creating "+O+" group";m.time(t)}e.g.apps[n]=e.g.app.append("g").attr("id",n).attr("opacity",0),e.dev.value&&m.timeEnd(t)},message:C}),e.data.changed&&t.push({function:function(e){e.data.cache={},delete e.nodes.restricted,delete e.edges.restricted,i(e,"data")},message:T}),e.attrs.changed&&t.push({function:function(e){i(e,"attrs")},message:T}),t.push({function:function(e){if(!e.color.type||e.color.changed||e.data.changed||e.attrs.changed||e.id.changed||e.depth.changed||e.id.solo.changed||!e.time.fixed.value&&(e.time.solo.changed||e.time.mute.changed)){if(e.color.valueScale=!1,e.dev.value){var t="checking color type";m.time(t)}if(e.color.type=!1,e.color.value){var n=e.color.value;M(n)&&(n=n[e.id.value]?n[e.id.value]:n[d3.keys(n)[0]]),e.data.keys&&n in e.data.keys?e.color.type=e.data.keys[n]:e.attrs.keys&&n in e.attrs.keys&&(e.color.type=e.attrs.keys[n])}else e.data.keys&&(e.color.type=e.data.keys[e.id.value]);e.dev.value&&m.timeEnd(t)}},message:T}),F.indexOf("edges")>=0&&e.edges.value&&(!e.edges.linked||e.edges.changed)&&t.push({function:v,message:T}),F.indexOf("nodes")>=0&&e.edges.value&&(!e.nodes.positions||e.nodes.changed||e.type.changed)&&t.push({function:g,message:T}),(e.data.changed||e.time.changed||e.time.format.changed||e.type.changed||e.id.changed||e.x.scale.changed&&[e.x.scale.value,e.x.scale.previous].indexOf("discrete")>=0||e.y.scale.changed&&[e.y.scale.value,e.y.scale.previous].indexOf("discrete")>=0)&&t.push({function:r,message:T}),e.error.value||t.push({function:function(e){var t=e.time.fixed.value?["all"]:null;if(e.dev.value){var n=t?"fetching pool data":"fetching data";m.time(n)}e.data.pool=f(e,t),e.dev.value&&m.timeEnd(n),t?(e.dev.value&&m.time("fetching data for current year"),e.data.viz=f(e),e.dev.value&&m.timeEnd("fetching data for current year")):e.data.viz=e.data.pool,e.draw.timing=e.data.viz.length1){var u=e.format.locale.value.error.methods,c=e.format.locale.value.visualization[e.type.value]||e.type.value,f=e.format.locale.value.ui.and;s=l(s,f),e.error.internal=o(u,c,s)}else if(1===s.length){var u=e.format.locale.value.error.method,c=e.format.locale.value.visualization[e.type.value]||e.type.value;e.error.internal=o(u,c,s[0])}if(!e.error.internal&&t.indexOf("edges")>=0&&t.indexOf("focus")>=0){var d=e.edges.connections(e.focus.value[0],e.id.value);if(0==d.length){var p=r(e,e.focus.value[0],e.depth.value),u=e.format.locale.value.error.connections;e.error.internal=o(u,'"'+p+'"')}}var t=["d3"];e.types[e.type.value].libs&&(t=t.concat(e.types[e.type.value].libs));var s=[];if(t.forEach(function(e){window[e]||s.push('"'+e+'"')}),s.length>1){var u=e.format.locale.value.error.libs,c=e.format.locale.value.visualization[e.type.value],f=e.format.locale.value.ui.and;s=l(s,f),e.error.internal=o(u,c,s)}else if(1===s.length){var u=e.format.locale.value.error.lib,c=e.format.locale.value.visualization[e.type.value];e.error.internal=o(u,c,s[0])}var h=e.shape.accepted(e);h instanceof Array||(h=[h]);var v=e.shape.value;if(v&&!i(e,h,v,"shape")||e.self.shape(h[0]),"modes"in e.types[e.type.value]){var g=e.types[e.type.value].modes;g instanceof Array||(g=[g]);var m=e.type.mode.value;m&&!i(e,g,m,"mode")||e.self.type({mode:g[0]})}e.dev.value&&a.timeEnd("checking for errors")}},{"../../core/console/print.coffee":54,"../../core/fetch/text.js":68,"../../core/methods/rejected.coffee":93,"../../string/format.js":176,"../../string/list.coffee":177}],217:[function(e,t,n){var r=e("./shapes/edges.js"),a=e("./shapes/paths.js"),i=e("./ui/message.js"),o=e("./focus/viz.js"),l=e("../../core/methods/reset.coffee"),s=e("../../core/console/print.coffee"),u=e("./shapes/labels.js"),c=e("../../string/title.coffee"),f=e("./zoom/bounds.coffee"),d=e("./zoom/labels.coffee"),p=e("./zoom/mouse.coffee");t.exports=function(e){if(e.draw.first?setTimeout(function(){o(e)},e.draw.timing):o(e),!e.error.value){var t=e.zoom.viewport||e.zoom.bounds;e.types[e.type.value].zoom&&e.zoom.value&&t?(e.dev.value&&s.time("calculating zoom"),e.draw.first||e.zoom.reset?f(e,t,0):(e.type.changed||e.focus.changed||e.height.changed||e.width.changed||e.nodes.changed||e.legend.changed||e.timeline.changed||e.ui.changed)&&f(e,t),e.dev.value&&s.timeEnd("calculating zoom")):(e.zoom.bounds=[[0,0],[e.width.viz,e.height.viz]],e.zoom.scale=1,f(e))}var n=e.zoom.size?e.zoom.size.width:e.width.viz,h=e.zoom.size?e.zoom.size.height:e.height.viz,v=e.zoom.bounds?e.zoom.bounds[0][0]:0,g=e.zoom.bounds?e.zoom.bounds[0][1]:0;if(e.g.overlay.attr("width",n).attr("height",h).attr("x",v).attr("y",g),e.error.value||(e.draw.update?(e.edges.path?a(e):r(e),u(e,"data"),e.edges.label&&!e.edges.path&&setTimeout(function(){u(e,"edges")},e.draw.timing+200)):(e.labels.value||e.labels.changed)&&e.types[e.type.value].zoom&&e.zoom.value&&e.draw.timing&&setTimeout(function(){d(e)},e.draw.timing)),!e.error.value){var m=e.types[e.type.value].requirements||[];m instanceof Array||(m=[m]);var y=m.indexOf("data")>=0;e.error.internal||e.data.viz&&e.returned.nodes.length||!y||(e.error.internal=e.format.locale.value.error.data)}var x=e.type.previous;if(x&&e.type.value!=x&&e.g.apps[x]&&(e.dev.value&&s.time('hiding "'+x+'"'),e.draw.timing?e.g.apps[x].transition().duration(e.draw.timing).attr("opacity",0):e.g.apps[x].attr("opacity",0),e.dev.value&&s.timeEnd()),!e.error.value){var b=y&&0===e.data.viz.length||e.error.internal||e.error.value?0:e.focus.value.length&&e.types[e.type.value].zoom&&e.zoom.value?1-e.tooltip.curtain.opacity:1,w=e.draw.timing;e.group.transition().duration(w).attr("opacity",b),e.g.data.transition().duration(w).attr("opacity",b),e.g.edges.transition().duration(w).attr("opacity",b)}e.error.value?i(e,e.error.value):e.error.internal?(e.error.internal=c(e.error.internal),s.warning(e.error.internal),i(e,e.error.internal),e.error.internal=null):i(e),setTimeout(function(){l(e),e.types[e.type.value].zoom&&e.zoom.value?(e.g.zoom.datum(e).call(e.zoom.behavior.on("zoom",p)),e.zoom.scroll.value||e.g.zoom.on("mousewheel.zoom",null).on("MozMousePixelScroll.zoom",null).on("wheel.zoom",null),e.zoom.click.value||e.g.zoom.on("dblclick.zoom",null),e.zoom.pan.value||e.g.zoom.on("mousedown.zoom",null).on("mousemove.zoom",null)):e.g.zoom.call(e.zoom.behavior.on("zoom",null)).on("dblclick.zoom",null).on("mousedown.zoom",null).on("mousemove.zoom",null).on("mousewheel.zoom",null).on("MozMousePixelScroll.zoom",null).on("touchstart.zoom",null).on("wheel.zoom",null)},e.draw.timing)}},{"../../core/console/print.coffee":54,"../../core/methods/reset.coffee":95,"../../string/title.coffee":179,"./focus/viz.js":219,"./shapes/edges.js":229,"./shapes/labels.js":231,"./shapes/paths.js":233,"./ui/message.js":249,"./zoom/bounds.coffee":252,"./zoom/labels.coffee":254,"./zoom/mouse.coffee":255}],218:[function(e,t,n){var r,a,i,o;r=e("../tooltip/create.js"),a=e("../../../core/fetch/value.coffee"),i=e("../../../core/console/print.coffee"),o=e("../../../tooltip/remove.coffee"),t.exports=function(e){var t,n,l;n=e.focus,!e.error.internal&&1===n.value.length&&n.value.length&&!e.small&&n.tooltip.value?(e.dev.value&&i.time("drawing focus tooltip"),t=e.data.pool.filter(function(t){return a(e,t,e.id.value)===n.value[0]}),t.length>=1?t=t[0]:(t={},t[e.id.value]=n.value[0]),l=e.labels.padding,r({anchor:"top left",arrow:!1,data:t,fullscreen:!1,id:"visualization_focus",length:"long",maxheight:e.height.viz-2*l,mouseevents:!0,offset:0,vars:e,width:e.tooltip.large,x:e.width.value-e.margin.right-l,y:e.margin.top+l}),e.width.viz-=e.tooltip.large+2*l,e.dev.value&&i.timeEnd("drawing focus tooltip")):o("visualization_focus")}},{"../../../core/console/print.coffee":54,"../../../core/fetch/value.coffee":69,"../../../tooltip/remove.coffee":206,"../tooltip/create.js":243}],219:[function(t,n,r){var a=t("../../../client/pointer.coffee"),i=t("../../../client/ie.js"),o=t("../../../core/fetch/value.coffee"),l=t("../../../core/console/print.coffee"),s=t("../../../util/uniques.coffee");n.exports=function(t){if(t.g.edge_focus.selectAll("g").remove(),t.g.data_focus.selectAll("g").remove(),t.focus.value.length&&t.types[t.type.value].zoom&&t.zoom.value){t.dev.value&&l.time("drawing focus elements");var n=t.g.edges.selectAll("g");if(n.size()>0){n.each(function(e){var n=e[t.edges.source][t.id.value],r=e[t.edges.target][t.id.value];if(n==t.focus.value[0]||r==t.focus.value[0]){var a=t.g.edge_focus.node().appendChild(this.cloneNode(!0));d3.select(a).datum(e).attr("opacity",1).selectAll("line, path").datum(e)}});var r=t.edges.arrows.value;t.g.edge_focus.selectAll("line, path").attr("vector-effect","non-scaling-stroke").style("stroke",t.color.focus).style("stroke-width",function(){return i&&t.types[t.type.value].zoom?0:t.edges.size.value?d3.select(this).style("stroke-width"):2*t.data.stroke.width}).attr("marker-start",function(e){var n=t.edges.arrows.direction.value;if("bucket"in e.d3plus)var a="_"+e.d3plus.bucket;else var a="";return"source"==n&&r?"url(#d3plus_edge_marker_focus"+a+")":"none"}).attr("marker-end",function(e){var n=t.edges.arrows.direction.value;if("bucket"in e.d3plus)var a="_"+e.d3plus.bucket;else var a="";return"target"==n&&r?"url(#d3plus_edge_marker_focus"+a+")":"none"}),t.g.edge_focus.selectAll("text").style("fill",t.color.focus)}var u=s(t.edges.connections(t.focus.value[0],t.id.value,!0),t.id.value,o,t);u.push(t.focus.value[0]);var c=[],f=[],d=[0],p=[0];t.g.data.selectAll("g").each(function(n){if(u.indexOf(n[t.id.value])>=0){var r=t.g.data_focus.node().appendChild(this.cloneNode(!0)),r=d3.select(r).datum(n).attr("opacity",1);"coordinates"==t.shape.value?t.zoom.viewport=t.path.bounds(t.zoom.coords[n.d3plus.id]):"d3plus"in n&&("x"in n.d3plus&&c.push(n.d3plus.x),"y"in n.d3plus&&f.push(n.d3plus.y),"r"in n.d3plus?(d.push(n.d3plus.r),p.push(n.d3plus.r)):("width"in n.d3plus&&d.push(n.d3plus.width/2),"height"in n.d3plus&&p.push(n.d3plus.height/2)));for(e in a){var i=d3.select(this).on(a[e]);i&&r.on(a[e],i)}}});if(c.length&&f.length){var h=d3.extent(c),v=d3.extent(f),g=d3.max(d),m=d3.max(p);t.zoom.viewport=[[h[0]-g,v[0]-m],[h[1]+g,v[1]+m]]}t.g.data_focus.selectAll("path").style("stroke-width",i&&t.types[t.type.value].zoom?0:2*t.data.stroke.width),t.dev.value&&l.timeEnd("drawing focus elements")}else t.zoom.viewport=!1}},{"../../../client/ie.js":39,"../../../client/pointer.coffee":40,"../../../core/console/print.coffee":54,"../../../core/fetch/value.coffee":69,"../../../util/uniques.coffee":213}],220:[function(e,t,n){var r,a,i,o;o=e("./style.coffee"),a=e("../../../geom/largestRect.coffee"),i=e("../../../geom/path2poly.coffee"),r={start:{},end:{}},t.exports=function(e,t,n,l){var s,u,c,f;s=d3.svg.arc().innerRadius(0).outerRadius(function(e){return e.d3plus.r}).startAngle(function(e){return e.d3plus.startAngle}).endAngle(function(e){return e.d3plus.endAngle}),c=function(t){var n,r;return e.labels.value&&(t.d3plus.label?t.d3plus_label=t.d3plus.label:(n=i(s(t)),r=a(n,{angle:0}),r[0]?t.d3plus_label={w:r[0].width,h:r[0].height,x:r[0].cx,y:r[0].cy}:delete t.d3plus_label)),[t]},e.draw.timing?(f=d3.svg.arc().innerRadius(0).outerRadius(function(e){return e.d3plus.r}).startAngle(function(e){return void 0===r.start[e.d3plus.id]&&(r.start[e.d3plus.id]=0),isNaN(r.start[e.d3plus.id])&&(r.start[e.d3plus.id]=e.d3plus.startAngle),r.start[e.d3plus.id]}).endAngle(function(e){return void 0===r.end[e.d3plus.id]&&(r.end[e.d3plus.id]=0),isNaN(r.end[e.d3plus.id])&&(r.end[e.d3plus.id]=e.d3plus.endAngle),r.end[e.d3plus.id]}),u=function(e,t){return e.attrTween("d",function(e){var n,a,i,o;return void 0===t?(o=e.d3plus.startAngle,n=e.d3plus.endAngle):0===t&&(o=0,n=0),i=d3.interpolate(r.start[e.d3plus.id],o),a=d3.interpolate(r.end[e.d3plus.id],n),function(t){return r.start[e.d3plus.id]=i(t),r.end[e.d3plus.id]=a(t),f(e)}})},n.append("path").attr("class","d3plus_data").call(o,e).attr("d",f),t.selectAll("path.d3plus_data").data(c).transition().duration(e.draw.timing).call(o,e).call(u),l.selectAll("path.d3plus_data").transition().duration(e.draw.timing).call(u,0)):(n.append("path").attr("class","d3plus_data"),t.selectAll("path.d3plus_data").data(c).call(o,e).attr("d",s))}},{"../../../geom/largestRect.coffee":162,"../../../geom/path2poly.coffee":164,"./style.coffee":237}],221:[function(e,t,n){var r=e("../../../core/fetch/text.js"),a=e("../../../font/sizes.coffee"),i=e("../../../geom/largestRect.coffee"),o=e("./style.coffee");t.exports=function(e,t,n,l){var s=d3.svg.area().x(function(e){return e.d3plus.x}).y0(function(e){return e.d3plus.y0}).y1(function(e){return e.d3plus.y}).interpolate(e.shape.interpolate.value),u=d3.svg.area().x(function(e){return e.d3plus.x}).y0(function(e){return e.d3plus.y0}).y1(function(e){return e.d3plus.y0}).interpolate(e.shape.interpolate.value);n.append("path").attr("class","d3plus_data").attr("d",function(e){return u(e.values)}).call(o,e);var c={"font-weight":e.labels.font.weight,"font-family":e.labels.font.family.value};t.selectAll("path.d3plus_data").data(function(t){if(e.labels.value&&t.values.length>1){var n=d3.max(t.values,function(e){return e.d3plus.y0-e.d3plus.y}),o=!1;if(n>e.labels.font.size){var l=[],s=[],u=r(e,t);t.values.forEach(function(e){l.push([e.d3plus.x,e.d3plus.y]),s.push([e.d3plus.x,e.d3plus.y0])}),l=l.concat(s.reverse());var f=null;if(u.length){var d=a(u[0],c);f=d[0].width/d[0].height}o=i(l,{angle:d3.range(-70,71,1),aspectRatio:f,tolerance:0})}if(o&&o[0]){var p={w:~~o[0].width,h:~~o[0].height,x:~~o[0].cx,y:~~o[0].cy,angle:o[0].angle*-1,padding:2,names:u};0!==o[0].angle?p.translate={x:p.x,y:p.y}:p.translate=!1,p.w>=10&&p.h>=10&&(t.d3plus_label=p)}}return[t]}),e.draw.timing?t.selectAll("path.d3plus_data").transition().duration(e.draw.timing).attr("d",function(e){return s(e.values)}).call(o,e):t.selectAll("path.d3plus_data").attr("d",function(e){return s(e.values)}).call(o,e)}},{"../../../core/fetch/text.js":68,"../../../font/sizes.coffee":104,"../../../geom/largestRect.coffee":162,"./style.coffee":237}],222:[function(e,t,n){var r=(e("../../../core/fetch/text.js"),e("../../../geom/largestRect.coffee"),e("./style.coffee"));t.exports=function(e,t,n,a){function i(e){e.attr("transform","scale(1)")}function o(e){e.attr("transform",function(e){var t=Math.min(e.d3plus.width,e.d3plus.height),n=Math.floor(t/16);return"scale("+n+")"})}n.append("path").attr("class","d3plus_data").attr("d","M5-6.844L3.594-5.407L-2,0.188l-1.594-1.594L-5-2.844L-7.844,0l1.438,1.406l3,3L-2,5.843l1.406-1.438l7-7L7.844-4L5-6.844z").call(i).call(r,e),t.selectAll("path.d3plus_data").data(function(e){return[e]}),e.draw.timing?t.selectAll("path.d3plus_data").transition().duration(e.draw.timing).call(o).call(r,e):t.selectAll("path.d3plus_data").call(o).call(r,e)}},{"../../../core/fetch/text.js":68,"../../../geom/largestRect.coffee":162,"./style.coffee":237}],223:[function(e,t,n){var r,a,i,o;a=e("../../../core/fetch/value.coffee"),r=e("../../../core/fetch/color.coffee"),i=e("../../../color/lighter.coffee"),o=e("./segments.coffee"),t.exports=function(e,t,n){var a,l,s,u;return l=e.d3plus.shape||t.shape.value,"line"===t.shape.value&&"circle"!==l?"none":"area"===t.shape.value||"active"===l||"line"===t.shape.value?r(t,e):"temp"===l?n?r(t,e):"url(#d3plus_hatch_"+e.d3plus.id+")":e.d3plus.static?i(r(t,e),.75):(a=o(t,e,"active"),s=o(t,e,"temp"),u=o(t,e,"total"),!t.active.value&&!t.temp.value||a===!0||a&&u&&a>=u&&!s||a&&!u?r(t,e):t.active.spotlight.value?t.color.missing:i(r(t,e),.75))}},{"../../../color/lighter.coffee":47,"../../../core/fetch/color.coffee":65,"../../../core/fetch/value.coffee":69,"./segments.coffee":236}],224:[function(e,t,n){var r,a,i,o,l,s,u,c;r=e("../../../util/copy.coffee"),a=e("../../../network/distance.coffee"),i=e("../../../core/fetch/text.js"),o=e("../../../font/sizes.coffee"),s=e("../../../geom/largestRect.coffee"),u=e("../../../geom/path2poly.coffee"),c=e("./style.coffee"),l={},t.exports=function(e,t,n,f){var d,p;return d=d3.geo[e.coords.projection.value](),d.center&&d.center(e.coords.center),e.zoom.scale||(e.zoom.scale=1),e.zoom.area=1/e.zoom.scale/e.zoom.scale,e.path=d3.geo.path().projection(d),e.draw.timing?t.selectAll("path.d3plus_data").attr("d",e.path).transition().duration(e.draw.timing).call(c,e):t.selectAll("path.d3plus_data").attr("d",e.path).call(c,e),n.append("path").attr("id",function(e){return e.id}).attr("class","d3plus_data").attr("d",e.path).call(c,e),p=e.old_height!==e.height.viz||e.height.changed||e.old_width!==e.width.viz||e.width.changed,e.old_height=e.height.viz,e.old_width=e.width.viz,e.coords.changed||p||e.coords.mute.changed||e.coords.solo.changed||e.type.changed||e.text.changed||e.coords.projection.changed||e.labels.changed?(e.zoom.bounds=null,e.zoom.reset=!0,e.zoom.coords={},t.each(function(t){var n,c,f,d,p,h,v,g,m,y,x,b,w,_,k,z,M,A,j,E,S;if(e.coords.simplify.value&&t.geometry.coordinates.length>1){for(m=[],c=[],n=0,b=r(t),A=r(t),t.geometry.coordinates=t.geometry.coordinates.filter(function(t,r){var a;return A.geometry.coordinates=[t],a=e.path.area(A),a>0&&(c.push(a),a>n&&(b.geometry.coordinates=[t],n=a),!0)}),p=e.path.centroid(b),j=t.geometry.coordinates,y=x=0,w=j.length;x=v}),h=b.geometry.coordinates[0],h&&"MultiPolygon"===b.geometry.type&&(h=h[0],b.geometry.coordinates[0]=h,b.geometry.type="Polygon")}else A=t,b=t,h=t.geometry.coordinates[0];return e.zoom.coords[t.d3plus.id]=A,delete t.d3plus_label,e.labels.value&&(_=i(e,t),h&&_.length&&(k=u(e.path(b)),S={"font-weight":e.labels.font.weight,"font-family":e.labels.font.family.value},z=null,1===_[0].split(" ").length&&(E=o(_[0],S)[0],z=E.width/E.height),M=s(k,{angle:0,aspectRatio:z}),M&&(M=M[0],t.d3plus_label={anchor:"middle",valign:"center",h:M.height,w:M.width,x:M.cx,y:M.cy,names:_}))),l[t.id]=t.d3plus_label,f=e.path.bounds(A),e.zoom.bounds?(e.zoom.bounds[0][0]>f[0][0]&&(e.zoom.bounds[0][0]=f[0][0]),e.zoom.bounds[0][1]>f[0][1]&&(e.zoom.bounds[0][1]=f[0][1]),e.zoom.bounds[1][0]2*Math.PI?2*Math.PI:n}).innerRadius(function(t){if(t.d3plus.static)return 0;var n=e.arcs[t.d3plus.shape][t.d3plus.id].r;return n*e.data.donut.size}).outerRadius(function(t){return e.arcs[t.d3plus.shape][t.d3plus.id].r});e.draw.timing?(a.selectAll("path.d3plus_data").transition().duration(e.draw.timing).call(i,0,0).each("end",function(t){delete e.arcs[t.d3plus.shape][t.d3plus.id]}),t.selectAll("path.d3plus_data").data(o).transition().duration(e.draw.timing).call(i).call(r,e),n.append("path").attr("class","d3plus_data").transition().duration(0).call(i,0,0).call(r,e).transition().duration(e.draw.timing).call(i).call(r,e)):(a.selectAll("path.d3plus_data").each(function(t){delete e.arcs[t.d3plus.shape][t.d3plus.id]}),n.append("path").attr("class","d3plus_data"),t.selectAll("path.d3plus_data").data(o).call(i).call(r,e))}},{"./style.coffee":237}],228:[function(e,t,n){var r=e("../../../util/child.coffee"),a=e("../../../util/closest.coffee"),i=e("../tooltip/create.js"),o=e("../../../client/pointer.coffee"),l=e("../../../core/fetch/value.coffee"),s=e("../../../core/fetch/color.coffee"),u=e("../../../core/fetch/text.js"),c=e("../../../color/legible.coffee"),f=e("../../../core/console/print.coffee"),d=e("../../../tooltip/remove.coffee"),p=e("./segments.coffee"),h=e("./fill.js"),v=e("../../../string/strip.js"),g=e("../../../client/touch.coffee"),m=e("../zoom/propagation.coffee"),y=e("../../../util/uniques.coffee"),x=e("../../../object/validate.coffee"),b=e("../zoom/direction.coffee"),w={arc:e("./arc.coffee"),area:e("./area.js"),check:e("./check.js"),coordinates:e("./coordinates.coffee"),cross:e("./cross.js"),diamond:e("./diamond.js"),donut:e("./donut.js"),line:e("./line.js"),radial:e("./radial.coffee"),rect:e("./rect.coffee"),triangle_down:e("./triangle_down.js"),triangle_up:e("./triangle_up.js"),whisker:e("./whisker.coffee")};t.exports=function(e){function t(t){if(!t.d3plus.id){t.d3plus.id="";for(var n=0;n<=e.depth.value;n++)t.d3plus.id+=l(e,t,e.id.nesting[n])+"_";t.d3plus.id+=O,["x","y","x2","y2"].forEach(function(n){if("discrete"==e[n].scale.value){var r=l(e,t,e[n].value);r.constructor===Date&&(r=r.getTime()),t.d3plus.id+="_"+r}}),t.d3plus.suffix&&(t.d3plus.id+="_"+t.d3plus.suffix),t.d3plus.id=v(t.d3plus.id)}return t}function n(t,n){var r=e.types[e.type.value].scale,a=1;r&&(x[r]&&e.shape.value in r?a=r[e.shape.value]:"function"==typeof r?a=r(e,e.shape.value):"number"==typeof r&&(a=r)),a=n?a:1,t.attr("transform",function(e){if(["line","area","coordinates"].indexOf(O)<0){var t=e.d3plus.x||0,n=e.d3plus.y||0;return"translate("+t+","+n+")scale("+a+")"}return"scale("+a+")"})}function _(t){t.attr("id",function(e){return"d3plus_group_"+e.d3plus.id}).attr("class",function(t){var n=e.class.value?" "+l(e,t,e.class.value):"";return"d3plus_"+O+n})}function k(t){if(t&&e.g.edges.selectAll("g").size()>0){e.g.edge_hover.selectAll("*").remove(),e.g.edges.selectAll("g").each(function(n){var r=t[e.id.value],a=n[e.edges.source][e.id.value],i=n[e.edges.target][e.id.value];if(a==r||a=="left_"+r||a=="right_"+r||i==r||i=="left_"+r||i=="right_"+r){var o=e.g.edge_hover.node().appendChild(this.cloneNode(!0));d3.select(o).datum(n).attr("opacity",1).selectAll("line, path").datum(n)}});var n=e.edges.arrows.value;e.g.edge_hover.attr("opacity",0).selectAll("line, path").style("stroke",e.color.primary).style("stroke-width",function(t){return e.edges.path&&t.dy?Math.max(1,t.dy):e.edges.size.value?d3.select(this).style("stroke-width"):2*e.data.stroke.width}).attr("marker-start",function(t){var r=e.edges.arrows.direction.value;if("bucket"in t.d3plus)var a="_"+t.d3plus.bucket;else var a="";return"source"==r&&n?"url(#d3plus_edge_marker_highlight"+a+")":"none"}).attr("marker-end",function(t){var r=e.edges.arrows.direction.value;if("bucket"in t.d3plus)var a="_"+t.d3plus.bucket;else var a="";return"target"==r&&n?"url(#d3plus_edge_marker_highlight"+a+")":"none"}),e.g.edge_hover.selectAll("text").style("fill",e.color.primary),e.draw.timing?(e.g.edge_hover.transition().duration(e.timing.mouseevents).attr("opacity",1),e.g.edges.transition().duration(e.timing.mouseevents).attr("opacity",.5)):e.g.edge_hover.attr("opacity",1)}else e.draw.timing?(e.g.edge_hover.transition().duration(e.timing.mouseevents).attr("opacity",0).transition().selectAll("*").remove(),e.g.edges.transition().duration(e.timing.mouseevents).attr("opacity",1)):e.g.edge_hover.selectAll("*").remove()}var z=e.returned.nodes||[],M=e.returned.edges||[];e.draw.timing=z.length=0&&e.types[e.type.value].fill&&(e.dev.value&&f.time('filling "'+O+'" shapes'),h(e,N,T,F,n),e.dev.value&&f.timeEnd('filling "'+O+'" shapes'))}if(k(),e.tooltip.value)e.g.data.selectAll("g").on(o.over,function(t){if(g&&m(e,d3.event),d3.event.buttons||!e.mouse.value||!e.mouse.over.value||e.draw.frozen||t.d3plus&&t.d3plus.static)d(e.type.value);else{var r="function"!=typeof e.mouse.over.value;if("function"==typeof e.mouse.over.value&&(r=e.mouse.over.value(t,e.self)),r){var l=b(t.d3plus_data||t,e),s="function"==typeof e.mouse.viz||"function"==typeof e.mouse.viz[o.click]||e.zoom.value&&(e.types[e.type.value].zoom||t.d3plus.threshold&&t.d3plus.merged||1===l||l===-1&&e.history.states.length&&!e.tooltip.value.long);if(d3.select(this).style("cursor",s?"pointer":"auto").transition().duration(e.timing.mouseevents).call(n,!0),d3.select(this).selectAll(".d3plus_data").transition().duration(e.timing.mouseevents).attr("opacity",1),e.covered=!1,t.values&&e.axes.discrete){var u="x"===e.axes.discrete?0:1,c=d3.mouse(e.container.value.node())[u],f=y(t.values,function(t){return t.d3plus[e.axes.discrete]}),p=a(f,c);t.d3plus_data=t.values[f.indexOf(p)],t.d3plus=t.values[f.indexOf(p)].d3plus}var h=t.d3plus_data?t.d3plus_data:t;i({vars:e,data:h}),"function"==typeof e.mouse.viz?e.mouse.viz(t.d3plus_data||t,e):e.mouse.viz[o.over]&&e.mouse.viz[o.over](t.d3plus_data||t,e),k(t)}}}).on(o.move,function(t){if(g&&m(e,d3.event),d3.event.buttons||!e.mouse.value||!e.mouse.move.value||e.draw.frozen||t.d3plus&&t.d3plus.static)d(e.type.value);else{var n="function"!=typeof e.mouse.move.value;if("function"==typeof e.mouse.move.value&&(n=e.mouse.move.value(t,e.self)),n){var r=b(t.d3plus_data||t,e),l="function"==typeof e.mouse.viz||"function"==typeof e.mouse.viz[o.click]||e.zoom.value&&(e.types[e.type.value].zoom||t.d3plus.threshold&&t.d3plus.merged||1===r||r===-1&&e.history.states.length&&!e.tooltip.value.long);d3.select(this).style("cursor",l?"pointer":"auto");e.types[e.type.value].tooltip||"follow";if(t.values&&e.axes.discrete){var s="x"===e.axes.discrete?0:1,u=d3.mouse(e.container.value.node())[s],c=y(t.values,function(t){return t.d3plus[e.axes.discrete]}),f=a(c,u);t.d3plus_data=t.values[c.indexOf(f)],t.d3plus=t.values[c.indexOf(f)].d3plus}var p=t.d3plus_data?t.d3plus_data:t;i({vars:e,data:p}),"function"==typeof e.mouse.viz?e.mouse.viz(t.d3plus_data||t,e):e.mouse.viz[o.move]&&e.mouse.viz[o.move](t.d3plus_data||t,e)}}}).on(o.out,function(t){if(g&&m(e,d3.event),!d3.event.buttons&&e.mouse.value&&e.mouse.out.value){var a="function"!=typeof e.mouse.out.value;if("function"==typeof e.mouse.out.value&&(a=e.mouse.out.value(t,e.self)),a){var i=r(this,d3.event.toElement);i||e.draw.frozen||t.d3plus&&t.d3plus.static||(d3.select(this).transition().duration(e.timing.mouseevents).call(n),d3.select(this).selectAll(".d3plus_data").transition().duration(e.timing.mouseevents).attr("opacity",e.data.opacity),e.covered||d(e.type.value),"function"==typeof e.mouse.viz?e.mouse.viz(t.d3plus_data||t,e):e.mouse.viz[o.out]&&e.mouse.viz[o.out](t.d3plus_data||t,e),k())}}else d(e.type.value)});else{var q=function(){m(e,d3.event)};e.g.data.selectAll("g").on(o.over,q).on(o.move,q).on(o.out,q)}d3.select(window).on("scroll.d3plus",function(){d(e.type.value)}),e.g.data.selectAll("g").on(o.click,function(t){if((!e.mouse.viz||e.mouse.viz.click!==!1)&&e.mouse.value&&e.mouse.click.value&&!d3.event.defaultPrevented&&!e.draw.frozen&&(!t.d3plus||!t.d3plus.static)){var r="function"!=typeof e.mouse.click.value;if("function"==typeof e.mouse.click.value&&(r=e.mouse.click.value(t,e.self)),r){if(t.values&&e.axes.discrete){var f="x"===e.axes.discrete?0:1,p=d3.mouse(e.container.value.node())[f],h=y(t.values,function(t){return t.d3plus[e.axes.discrete]}),v=a(h,p);t.d3plus_data=t.values[h.indexOf(v)],t.d3plus=t.values[h.indexOf(v)].d3plus}"function"==typeof e.mouse.viz?e.mouse.viz(t.d3plus_data||t,e):e.mouse.viz[o.out]?e.mouse.viz[o.out](t.d3plus_data||t,e):e.mouse.viz[o.click]&&e.mouse.viz[o.click](t.d3plus_data||t,e);var g=b(t.d3plus_data||t,e),m=e.id.solo.value,x=u(e,t)[0],w=c(s(e,t)),_=e.title.sub.value||!1,z=e.title.sub.font.color,M=e.title.total.font.color;if(t.d3plus.threshold&&t.d3plus.merged&&e.zoom.value)e.history.states.push(function(){e.self.id({solo:m}).title({sub:{font:{color:z},value:_},total:{font:{color:M}}}).draw()}),e.self.id({solo:m.concat(y(t.d3plus.merged,e.id.value,l,e))}).title({sub:{font:{color:w},value:x},total:{font:{color:w}}}).draw();else if(1===g&&e.zoom.value){var A=l(e,t.d3plus_data||t,e.id.value);e.history.states.push(function(){e.self.depth(e.depth.value-1).id({solo:m}).title({sub:{font:{color:z},value:_},total:{font:{color:M}}}).draw()}),e.self.depth(e.depth.value+1).id({solo:m.concat(A)}).title({sub:{font:{color:w},value:x},total:{font:{color:w}}}).draw()}else if(g===-1&&e.zoom.value&&e.history.states.length&&!e.tooltip.value.long)e.history.back();else if(e.types[e.type.value].zoom&&e.zoom.value)k(),d3.select(this).transition().duration(e.timing.mouseevents).call(n),d3.select(this).selectAll(".d3plus_data").transition().duration(e.timing.mouseevents).attr("opacity",e.data.opacity),d(e.type.value),e.draw.update=!1,t&&t[e.id.value]!=e.focus.value[0]?e.self.focus(t[e.id.value]).draw():e.self.focus(!1).draw();else if(e.types[e.type.value].requirements.indexOf("focus")<0){ +k();var j=t.d3plus_data?t.d3plus_data:t;i({vars:e,data:j})}}}})}},{"../../../client/pointer.coffee":40,"../../../client/touch.coffee":45,"../../../color/legible.coffee":46,"../../../core/console/print.coffee":54,"../../../core/fetch/color.coffee":65,"../../../core/fetch/text.js":68,"../../../core/fetch/value.coffee":69,"../../../object/validate.coffee":175,"../../../string/strip.js":178,"../../../tooltip/remove.coffee":206,"../../../util/child.coffee":208,"../../../util/closest.coffee":209,"../../../util/uniques.coffee":213,"../tooltip/create.js":243,"../zoom/direction.coffee":253,"../zoom/propagation.coffee":256,"./arc.coffee":220,"./area.js":221,"./check.js":222,"./coordinates.coffee":224,"./cross.js":225,"./diamond.js":226,"./donut.js":227,"./fill.js":230,"./line.js":232,"./radial.coffee":234,"./rect.coffee":235,"./segments.coffee":236,"./triangle_down.js":238,"./triangle_up.js":239,"./whisker.coffee":240}],229:[function(e,t,n){var r=e("../../../util/buckets.coffee"),a=e("../../../geom/offset.coffee");t.exports=function(e){function t(t){t.attr("opacity",0).style("stroke-width",0).style("stroke",e.background.value).style("fill","none")}function n(t){var n=e.edges.arrows.value;t.attr("opacity",function(t){return"number"===h?p:"function"===h?p(t,e):e.edges.opacity.scale.value(t[p])}).style("stroke-width",function(t){return e.edges.scale(t[e.edges.size.value])}).style("stroke",e.edges.color).attr("marker-start",function(t){var r=e.edges.arrows.direction.value;if("bucket"in t.d3plus)var a="_"+t.d3plus.bucket;else var a="";return"source"==r&&n?"url(#d3plus_edge_marker_default"+a+")":"none"}).attr("marker-end",function(t){var r=e.edges.arrows.direction.value;if("bucket"in t.d3plus)var a="_"+t.d3plus.bucket;else var a="";return"target"==r&&n?"url(#d3plus_edge_marker_default"+a+")":"none"}).attr("vector-effect","non-scaling-stroke").attr("pointer-events","none")}function i(t){t.attr("x1",function(t){return t[e.edges.source].d3plus.edges[t[e.edges.target][e.id.value]].x}).attr("y1",function(t){return t[e.edges.source].d3plus.edges[t[e.edges.target][e.id.value]].y}).attr("x2",function(t){return t[e.edges.target].d3plus.edges[t[e.edges.source][e.id.value]].x}).attr("y2",function(t){return t[e.edges.target].d3plus.edges[t[e.edges.source][e.id.value]].y})}function o(e){e.attr("d",function(e){return v(e.d3plus.spline)})}function l(t){if(delete t.d3plus_label,e.g.edges.selectAll("line, path").size()90)&&(l-=180),s*e.zoom.behavior.scaleExtent()[0]>20&&(t.d3plus_label={x:u,y:c,translate:{x:u,y:c},w:s,h:15+2*e.labels.padding,angle:l,anchor:"middle",valign:"center",color:e.edges.color,resize:!1,names:[e.format.value(t[e.edges.label])],background:1})}}var s=e.returned.edges||[],u=e.zoom.behavior.scaleExtent()[0];if("string"==typeof e.edges.size.value){var c=d3.extent(s,function(t){return t[e.edges.size.value]}),f=d3.min(e.returned.nodes||[],function(e){return e.d3plus.r})*(2*e.edges.size.scale);e.edges.scale=d3.scale.sqrt().domain(c).range([e.edges.size.min,f*u])}else{var d="number"==typeof e.edges.size.value?e.edges.size.value:e.edges.size.min;e.edges.scale=function(){return d}}var p=e.edges.opacity.value,h=typeof p;e.edges.opacity.changed&&"string"===h&&e.edges.opacity.scale.value.domain(d3.extent(s,function(e){return e[p]})).range([e.edges.opacity.min.value,1]);var v=d3.svg.line().interpolate(e.edges.interpolate.value),g=e.edges.arrows.value?"string"==typeof e.edges.size.value?["default_0","default_1","default_2","highlight_0","highlight_1","highlight_2","focus_0","focus_1","focus_2"]:["default","highlight","focus"]:[];if("string"==typeof e.edges.size.value)for(var m=r(e.edges.scale.range(),4),y=[],x=0;x<3;x++)y.push(m[x+1]+(m[1]-m[0])*(x+2)*2);else var b="number"==typeof e.edges.arrows.value?e.edges.arrows.value:8,y="number"==typeof e.edges.size.value?e.edges.size.value/b:b;var w=e.defs.selectAll(".d3plus_edge_marker").data(g,String),_=function(t){t.attr("d",function(t){var n=t.split("_");if(2==n.length&&e.edges.scale){n=parseInt(n[1]);var r=y[n]}else var r=y;return"target"==e.edges.arrows.direction.value?"M 0,-"+r/2+" L "+.85*r+",0 L 0,"+r/2+" L 0,-"+r/2:"M 0,-"+r/2+" L -"+.85*r+",0 L 0,"+r/2+" L 0,-"+r/2}).attr("fill",function(t){var n=t.split("_")[0];return"default"==n?e.edges.color:"focus"==n?e.color.focus:e.color.primary}).attr("transform","scale("+1/u+")")};e.draw.timing?(w.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),w.select("path").transition().duration(e.draw.timing).attr("opacity",1).call(_)):(w.exit().remove(),w.select("path").attr("opacity",1).call(_));var k=e.draw.timing?0:1,z=w.enter().append("marker").attr("id",function(e){return"d3plus_edge_marker_"+e}).attr("class","d3plus_edge_marker").attr("orient","auto").attr("markerUnits","userSpaceOnUse").style("overflow","visible").append("path").attr("opacity",k).attr("vector-effect","non-scaling-stroke").call(_);e.draw.timing&&z.transition().duration(e.draw.timing).attr("opacity",1);var M="string"==typeof e.edges.size.value?r(e.edges.scale.domain(),4):null,A=e.edges.arrows.direction.value,j=s.filter(function(t){if(t.d3plus||(t.d3plus={}),t.d3plus.id="edge_"+t[e.edges.source][e.id.value]+"_"+t[e.edges.target][e.id.value],t.d3plus.spline!==!0){if(M){var n=t[e.edges.size.value];t.d3plus.bucket=no.d3plus.x?1-d:1+d,h=i.d3plus.x>o.d3plus.x?1+d:1-d,v="number"==typeof l.angle?l.angle:Math.atan2(i.d3plus.y-o.d3plus.y,i.d3plus.x-o.d3plus.x)*p,g=a(v,i.d3plus.r+c,e.shape.value),m="number"==typeof s.angle?s.angle:Math.atan2(o.d3plus.y-i.d3plus.y,o.d3plus.x-i.d3plus.x)*h,x=a(m,o.d3plus.r+f,e.shape.value),b=[i.d3plus.x-g.x,i.d3plus.y-g.y],w=!!l.offset&&a(v,l.offset),_=w?[b[0]-w.x,b[1]-w.y]:b,k=[o.d3plus.x-x.x,o.d3plus.y-x.y],z=!!s.offset&&a(m,s.offset),j=z?[k[0]-z.x,k[1]-z.y]:k,E=j[0]-_[0],S=j[1]-_[1],O="number"==typeof l.radius?l.radius:Math.sqrt(E*E+S*S)/4,N="number"==typeof s.radius?s.radius:Math.sqrt(E*E+S*S)/4,F=a(v,O-i.d3plus.r-2*c),C=a(m,N-o.d3plus.r-2*f);t.d3plus.spline=[b,k];var T=Math.abs(Math.atan2(i.d3plus.y-o.d3plus.y,i.d3plus.x-o.d3plus.x)).toFixed(5),q=Math.abs(v).toFixed(5),P=Math.abs(m-Math.PI).toFixed(5);return(q!==P||[q,P].indexOf(T)<0)&&(t.d3plus.spline.splice(1,0,[_[0]-F.x,_[1]-F.y],[j[0]-C.x,j[1]-C.y]),w&&t.d3plus.spline.splice(1,0,_),z&&t.d3plus.spline.splice(t.d3plus.spline.length-1,0,j)),!0}return!1}),O=e.g.edges.selectAll("g.d3plus_edge_path").data(S,function(e){return e.d3plus.id});e.draw.timing?(E.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),O.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),E.selectAll("text.d3plus_label, rect.d3plus_label_bg").transition().duration(e.draw.timing/2).attr("opacity",0).remove(),O.selectAll("text.d3plus_label, rect.d3plus_label_bg").transition().duration(e.draw.timing/2).attr("opacity",0).remove(),E.selectAll("line").data(function(e){return[e]}).transition().duration(e.draw.timing).call(i).call(n).each("end",l),O.selectAll("path").data(function(e){return[e]}).transition().duration(e.draw.timing).call(o).call(n).each("end",l),E.enter().append("g").attr("class","d3plus_edge_line").append("line").call(i).call(t).transition().duration(e.draw.timing).call(n).each("end",l),O.enter().append("g").attr("class","d3plus_edge_path").append("path").call(o).call(t).transition().duration(e.draw.timing).call(n).each("end",l)):(E.exit().remove(),O.exit().remove(),E.selectAll("text.d3plus_label, rect.d3plus_label_bg").remove(),O.selectAll("text.d3plus_label, rect.d3plus_label_bg").remove(),E.selectAll("line").data(function(e){return[e]}).call(i).call(n).call(l),O.selectAll("path").data(function(e){return[e]}).call(o).call(n).call(l),E.enter().append("g").attr("class","d3plus_edge_line").append("line").call(i).call(t).call(n).call(l),O.enter().append("g").attr("class","d3plus_edge_path").append("path").call(o).call(t).call(n).call(l))}},{"../../../geom/offset.coffee":163,"../../../util/buckets.coffee":207}],230:[function(e,t,n){var r=e("../../../util/copy.coffee"),a=e("../../../core/fetch/color.coffee"),i=(e("../../../core/fetch/value.coffee"),e("./segments.coffee")),o=e("./style.coffee");t.exports=function(e,t,n,l){function s(e){e.attr("x",0).attr("y",0).attr("width",0).attr("height",0)}function u(t,n){n||(n=0),t.attr("x",function(e){var t=e.d3plus.r?2*e.d3plus.r:e.d3plus.width;return-t/2-n/2}).attr("y",function(e){var t=e.d3plus.r?2*e.d3plus.r:e.d3plus.height;return-t/2-n/2}).attr("width",function(e){var t=e.d3plus.r?2*e.d3plus.r:e.d3plus.width;return t+n}).attr("height",function(e){var t=e.d3plus.r?2*e.d3plus.r:e.d3plus.height;return t+n}).attr("rx",function(t){var r=t.d3plus.r?2*t.d3plus.r:t.d3plus.width,a=["circle","donut"].indexOf(e.shape.value)>=0;return a?(r+n)/2:0}).attr("ry",function(t){var r=t.d3plus.r?2*t.d3plus.r:t.d3plus.height,a=["circle","donut"].indexOf(e.shape.value)>=0;return a?(r+n)/2:0}).attr("shape-rendering",function(t){return["square"].indexOf(e.shape.value)>=0?e.shape.rendering.value:"auto"})}function c(t,n,r,a){n||(n=0),"number"!=typeof r&&(r=void 0),"number"!=typeof a&&(a=void 0),t.attrTween("d",function(t){if(void 0===r)var i=t.d3plus.r?t.d3plus.r:d3.max([t.d3plus.width,t.d3plus.height]);else var i=r;if(void 0===a)var o=t.d3plus.segments[t.d3plus.shape];else var o=a;e.arcs[t.d3plus.shape][t.d3plus.id]||(e.arcs[t.d3plus.shape][t.d3plus.id]={r:0},e.arcs[t.d3plus.shape][t.d3plus.id].a="donut"===t.d3plus.shape?2*Math.PI:0);var l=d3.interpolate(e.arcs[t.d3plus.shape][t.d3plus.id].r,i+n),s=d3.interpolate(e.arcs[t.d3plus.shape][t.d3plus.id].a,o);return function(n){return e.arcs[t.d3plus.shape][t.d3plus.id].r=l(n),e.arcs[t.d3plus.shape][t.d3plus.id].a=s(n),f(t)}})}e.arcs||(e.arcs={donut:{},active:{},temp:{}});var f=d3.svg.arc().startAngle(0).endAngle(function(t){var n=e.arcs[t.d3plus.shape][t.d3plus.id].a;return n>2*Math.PI?2*Math.PI:n}).innerRadius(function(t){if(t.d3plus.static||"donut"!==e.shape.value)return 0;var n=e.arcs[t.d3plus.shape][t.d3plus.id].r;return n*e.data.donut.size}).outerRadius(function(t){var n=e.arcs[t.d3plus.shape][t.d3plus.id].r;return"donut"===e.shape.value?n:2*n});t.each(function(t){function n(t){t.attr("stroke",h).attr("stroke-width",1).attr("shape-rendering",e.shape.rendering.value)}var l=i(e,t,"active"),f=i(e,t,"temp"),d=i(e,t,"total"),p=d3.select(this),h=a(e,t),v=[],g=[];if(d&&e.types[e.type.value].fill){if(f){var m=r(t);m.d3plus.shape="temp",v.push(m),g=["temp"]}if(l&&(l=2,t.visible?1:0})},h=function(t){e.draw.timing?t.transition().duration(e.draw.timing).attr("opacity",0).remove():t.remove()},v=function(t){var r="bottom"===e.labels.valign.value?"top":"bottom";t.attr("font-weight",e.labels.font.weight).attr("font-family",e.labels.font.family.value).attr("stroke","none").attr("pointer-events",function(e){return e.mouse?"auto":"none"}).attr("fill",function(t){if(t.color)return t.color;var n=s(t.parent,e),r=c(n),a=t.text?.15:1;return i(n,r,.2,a)}).each(function(t){if(t.resize instanceof Array){t.resize[0],t.resize[1]}var a=t.resize,i=!0;if(t.text){a instanceof Array||(a=[9,50],i=t.resize);var o=t.y-t.h*n[1]/2+t.padding/2;"bottom"===r&&(o+=t.h*n[1]/2),f().align("center").container(d3.select(this)).height(t.h*n[1]/2).padding(t.padding/2).resize(i).size(a).text(e.format.value(100*t.text,{key:"share",vars:e})).width(t.w*n[1]).valign(r).x(t.x-t.w*n[1]/2+t.padding/2).y(o).draw()}else{t.resize instanceof Array||(a=[7,40*(n[1]/n[0])],i=t.resize);var l="bottom"===e.labels.valign.value?t.share:0;f().align(t.anchor||e.labels.align.value).container(d3.select(this)).height(t.h*n[1]-t.share).padding(t.padding/2).resize(i).size(a).shape(t.shape||"square").text(t.names).valign(e.labels.valign.value).width(t.w*n[1]).x(t.x-t.w*n[1]/2+t.padding/2).y(t.y-t.h*n[1]/2+t.padding/2+l).draw()}}).attr("transform",function(e){var t=d3.select(this).attr("transform")||"",r=e.angle||0,a=e.translate&&e.translate.x?e.translate.x:0,i=e.translate&&e.translate.y?e.translate.y:0;return t.length&&(t=t.split(")").slice(-3).join(")")),"rotate("+r+","+a+","+i+")scale("+1/n[1]+")translate("+(e.x*n[1]-e.x)+","+(e.y*n[1]-e.y)+")"+t})};if("edges"===t||e.labels.value){if(e.dev.value){var g="drawing "+t+" labels";o.time(g)}d.each(function(t){function i(t){var n="string"==typeof s.background?s.background:"none"===e.background.value?"#ffffff":e.background.value,r="string"==typeof s.background?s.background:n,a=_.attr("transform").split(")");a.pop(),a.pop(),a.push(""),a=a.join(")"),t.attr("fill",r).attr(S).attr("transform",a)}var o=t.d3plus&&"label"in t.d3plus&&!t.d3plus.label,s=t.d3plus_label||null,c=t.d3plus_share,f=t.d3plus.text?t.d3plus.text:s&&s.names?s.names:e.labels.text.value?a(e,t,e.labels.text.value):r(e,t),d=s&&"group"in s?s.group:d3.select(this),g=0,m=e.types[e.type.value].fill;if(f instanceof Array||(f=[f]),s)if(["line","area"].indexOf(e.shape.value)>=0)var y=!0;else if(t&&"d3plus"in t)var x=l(e,t,"active"),b=l(e,t,"temp"),w=l(e,t,"total"),y=!b&&!x||x>=w||!x&&b>=w;if(o||!(s&&s.force||y)&&m)delete t.d3plus_label,d3.select(this).selectAll("text#d3plus_label_"+t.d3plus.id+", rect#d3plus_label_bg_"+t.d3plus.id).call(h),e.g.labels.selectAll("text#d3plus_label_"+t.d3plus.id+", rect#d3plus_label_bg_"+t.d3plus.id).call(h);else{if(c&&t.d3plus.share&&c.w-2*e.labels.padding>=10&&c.h-2*e.labels.padding>=10&&"middle"!=e.labels.valign.value){c.resize=e.labels.resize.value!==!1&&(!(c&&"resize"in c)||c.resize),c.padding=e.labels.padding,c.text=t.d3plus.share,c.parent=t;var _=d.selectAll("text#d3plus_share_"+t.d3plus.id).data([c],function(e){return e.w+""+e.h+e.text});e.draw.timing&&1===e.zoom.scale?(_.transition().duration(e.draw.timing/2).call(v),_.enter().append("text").attr("id","d3plus_share_"+t.d3plus.id).attr("class","d3plus_share").attr("opacity",0).call(v).transition().duration(e.draw.timing/2).delay(e.draw.timing/2).attr("opacity",1)):(_.attr("opacity",1).call(v),_.enter().append("text").attr("id","d3plus_share_"+t.d3plus.id).attr("class","d3plus_share").attr("opacity",1).call(v)),g=_.node().getBBox().height+e.labels.padding,_.exit().call(h)}else d.selectAll("text.d3plus_share").call(h);if(s&&(s.resize=e.labels.resize.value!==!1&&(!(s&&"resize"in s)||s.resize),s.padding="number"==typeof s.padding?s.padding:e.labels.padding),s&&s.w*n[1]-s.padding>=20&&s.h*n[1]-s.padding>=10&&f.length){for(var k=e.format.locale.value.ui.and,z=e.format.locale.value.ui.more,M=0;M0?E.y:-E.height/2};S.width+=e.labels.padding*n[0],S.height+=e.labels.padding*n[0],S.x-=e.labels.padding*n[0]/2,S.y-=e.labels.padding*n[0]/2;var O=_.attr("transform").match(/translate\(([^a-z]+)\)/gi)[0];O=O.replace(/([^a-z])\s([^a-z])/gi,"$1,$2"),O=O.split(","),O.length>1&&(O=O[O.length-1],O=O.substring(0,O.length-1),S.y+=parseFloat(O))}else var j=[],S={};var N=d.selectAll("rect#d3plus_label_bg_"+t.d3plus.id).data(j),F="number"==typeof s.background?s.background:"string"==typeof s.background?1:.6;e.draw.timing?(N.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),N.transition().duration(e.draw.timing).attr("opacity",F).call(i),N.enter().insert("rect",".d3plus_label").attr("id","d3plus_label_bg_"+t.d3plus.id).attr("class","d3plus_label_bg").attr("opacity",0).call(i).transition().duration(e.draw.timing).attr("opacity",F)):(N.exit().remove(),N.enter().insert("rect",".d3plus_label").attr("id","d3plus_label_bg_"+t.d3plus.id).attr("class","d3plus_label_bg"),N.attr("opacity",F).call(i))}}else delete t.d3plus_label,d3.select(this).selectAll("text#d3plus_label_"+t.d3plus.id+", rect#d3plus_label_bg_"+t.d3plus.id).call(h),e.g.labels.selectAll("text#d3plus_label_"+t.d3plus.id+", rect#d3plus_label_bg_"+t.d3plus.id).call(h)}}),e.dev.value&&o.timeEnd(g)}else{if(e.dev.value){var g="removing "+t+" labels";o.time(g)}d.selectAll("text.d3plus_label, rect.d3plus_label_bg").call(h),e.g.labels.selectAll("text.d3plus_label, rect.d3plus_label_bg").call(h),e.dev.value&&o.timeEnd(g)}}},{"../../../client/rtl.coffee":42,"../../../color/mix.coffee":48,"../../../color/text.coffee":52,"../../../core/console/print.coffee":54,"../../../core/fetch/text.js":68,"../../../core/fetch/value.coffee":69,"../../../string/list.coffee":177,"../../../textwrap/textwrap.coffee":203,"../../../util/copy.coffee":210,"./color.coffee":223,"./segments.coffee":236}],232:[function(e,t,n){function r(e){e.attr("x",function(e){return e.d3plus.x}).attr("y",function(e){return e.d3plus.y}).attr("width",0).attr("height",0)}function a(e,t){void 0===t&&(t=0),e.attr("x",function(e){var n=e.d3plus.r?2*e.d3plus.r:e.d3plus.width;return e.d3plus.x-(n/2+t/2)}).attr("y",function(e){var n=e.d3plus.r?2*e.d3plus.r:e.d3plus.height;return e.d3plus.y-(n/2+t/2)}).attr("width",function(e){var n=e.d3plus.r?2*e.d3plus.r:e.d3plus.width;return n+t}).attr("height",function(e){var n=e.d3plus.r?2*e.d3plus.r:e.d3plus.height;return n+t}).attr("rx",function(e){var n=e.d3plus.r?2*e.d3plus.r:e.d3plus.width;return(n+t)/2}).attr("ry",function(e){var n=e.d3plus.r?2*e.d3plus.r:e.d3plus.height;return(n+t)/2})}function i(e,t,n,r){var i=e.draw.timing?e.timing.mouseevents:0;void 0===r&&(r=0),i?(d3.select(t.parentNode).selectAll("path.d3plus_line").transition().duration(i).style("stroke-width",function(t){var a=n;if(a.constructor!==Number){var i=c(e,t,n);a=i&&i.length?d3.max(i):e.data.stroke.width}return a+r}),d3.select(t.parentNode).selectAll("rect").transition().duration(i).style("stroke-width",function(t){var r=n;if(r.constructor!==Number){var a=c(e,t,n);r=a&&a.length?d3.max(a):e.data.stroke.width}return r}).call(a,r)):(d3.select(t.parentNode).selectAll("path.d3plus_line").style("stroke-width",function(t){var a=n;if(a.constructor!==Number){var i=c(e,t,n);a=i&&i.length?d3.max(i):e.data.stroke.width}return a+r}),d3.select(t.parentNode).selectAll("rect").style("stroke-width",function(t){var r=n;if(r.constructor!==Number){var a=c(e,t,n);r=a&&a.length?d3.max(a):e.data.stroke.width}return r}).call(a,r))}var o=e("../../../util/copy.coffee"),l=e("../../../util/closest.coffee"),s=e("../../../client/pointer.coffee"),u=e("./style.coffee"),c=e("../../../core/fetch/value.coffee");t.exports=function(e,t,n,f){var d=d3.svg.line().x(function(e){return e.d3plus.x}).y(function(e){return e.d3plus.y}).interpolate(e.shape.interpolate.value),p=e.size.value||e.data.stroke.width,h=e[e.axes.discrete],v=function(t){var n=p;if(n.constructor!==Number){var r=c(e,t,p);n=r&&r.length?d3.max(r):e.data.stroke.width}return n<15?15:n},g=h.ticks.values.map(function(e){return e.constructor===Date?e.getTime():e});t.each(function(t){var n=!1,f=[],m=[],y=o(t),x=d3.select(this);y.values=[],y.segment_key=y.key,t.values.forEach(function(r,a,i){var s=c(e,r,h.value);s.constructor===Date&&(s=s.getTime());var u=g.indexOf(l(g,s));n===!1||n===u-1?(y.values.push(r),y.segment_key+="_"+u):(y.values.length>1?f.push(y):m.push(y.values[0]),y=o(t),y.values=[r]),a===i.length-1&&(y.values.length>1?f.push(y):m.push(y.values[0])),n=u});var b=x.selectAll("path.d3plus_line").data(f,function(e){return e.d3plus||(e.d3plus={}),e.d3plus.shape="line",e.segment_key}),w=x.selectAll("rect.d3plus_anchor").data(m,function(e){return e.d3plus||(e.d3plus={}),e.d3plus.r=p,e.d3plus.id});e.draw.timing?(b.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),b.transition().duration(e.draw.timing).attr("d",function(e){return d(e.values)}).call(u,e),b.enter().append("path").attr("class","d3plus_line").style("stroke-linecap","round").attr("d",function(e){return d(e.values)}).call(u,e).attr("opacity",0).transition().duration(e.draw.timing).attr("opacity",1),w.enter().append("rect").attr("class","d3plus_anchor").attr("id",function(e){return e.d3plus.id}).call(r).call(u,e),w.transition().duration(e.draw.timing).call(a).call(u,e),w.exit().transition().duration(e.draw.timing).call(r).remove()):(b.exit().remove(),b.enter().append("path").attr("class","d3plus_line").style("stroke-linecap","round"),b.attr("d",function(e){return d(e.values)}).call(u,e),w.enter().append("rect").attr("class","d3plus_anchor").attr("id",function(e){return e.d3plus.id}),w.exit().remove(),w.call(a).call(u,e));var _=x.selectAll("path.d3plus_mouse").data(f,function(e){return e.segment_key});_.enter().append("path").attr("class","d3plus_mouse").attr("d",function(e){return d(e.values)}).style("stroke","black").style("stroke-width",v).style("fill","none").style("stroke-linecap","round").attr("opacity",0),_.on(s.over,function(t){!e.draw.frozen&&e.mouse.value&&e.mouse.over.value&&i(e,this,p,2)}).on(s.out,function(t){!e.draw.frozen&&e.mouse.value&&e.mouse.out.value&&i(e,this,p,0)}),e.draw.timing?_.transition().duration(e.draw.timing).attr("d",function(e){return d(e.values)}).style("stroke-width",v):_.attr("d",function(e){return d(e.values)}).style("stroke-width",v),_.exit().remove()})}},{"../../../client/pointer.coffee":40,"../../../core/fetch/value.coffee":69,"../../../util/closest.coffee":209,"../../../util/copy.coffee":210,"./style.coffee":237}],233:[function(e,t,n){t.exports=function(e){function t(t){t.attr("d",e.edges.path).style("stroke-width",function(e){return Math.max(1,e.dy)}).style("stroke","#ddd").style("fill","none").attr("transform",function(e){return"translate("+e.d3plus.x+","+e.d3plus.y+")"})}var n=e.returned.edges||[],r=e.g.edges.selectAll("g.d3plus_edge_path").data(n,function(t){return t.d3plus.id="path_"+t[e.edges.source][e.id.value]+"_"+t[e.edges.target][e.id.value],t.d3plus.id});e.draw.timing?(r.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),r.selectAll("text.d3plus_label, rect.d3plus_label_bg").transition().duration(e.draw.timing/2).attr("opacity",0).remove(),r.selectAll("path").data(function(e){return[e]}).transition().duration(e.draw.timing).call(t),r.enter().append("g").attr("class","d3plus_edge_path").append("path").style("stroke-width",0).transition().duration(e.draw.timing).call(t)):(r.exit().remove(),r.selectAll("text.d3plus_label, rect.d3plus_label_bg").remove(),r.selectAll("path").data(function(e){return[e]}).call(t),r.enter().append("g").attr("class","d3plus_edge_path").append("path").call(t))}},{}],234:[function(e,t,n){var r,a,i,o;o=e("./style.coffee"),i={},r={},a={r:{},a:{}},t.exports=function(e,t,n,l){var s,u,c,f,d;c=e.id.nesting[e.depth.value+1],f=d3.svg.line.radial().interpolate("linear-closed").radius(function(e){return e.d3plus.r}).angle(function(e){return e.d3plus.a}),s=function(t){return e.labels.value&&(t.d3plus.label?t.d3plus_label=t.d3plus.label:delete t.d3plus_label),[t]},e.draw.timing?(t.each(function(t){var n,r,a,i,o;for(i=t[c],o=[],r=0,a=i.length;r=0?90:0}:e.d3plus.label?e.d3plus_label=e.d3plus.label:delete e.d3plus_label,[e]},d=function(t){return t.style("stroke-width",e.data.stroke.width).style("stroke","#444").attr("fill","none").attr("shape-rendering",e.shape.rendering.value)},o=function(e){return e.attr("x1",0).attr("x2",0).attr("y1",0).attr("y2",0)},c=function(e){return e.attr("x1",function(e){var t,n,r;return["top","bottom"].indexOf(e.d3plus.position)>=0?0:(t=e.d3plus.offset||0,n=e.d3plus.width||0,r=t<0?-n:n,r+t)}).attr("x2",function(e){return["top","bottom"].indexOf(e.d3plus.position)>=0?0:e.d3plus.offset||0}).attr("y1",function(e){var t,n,r;return["left","right"].indexOf(e.d3plus.position)>=0?0:(n=e.d3plus.offset||0,t=e.d3plus.height||0,r=n<0?-t:t,r+n)}).attr("y2",function(e){return["left","right"].indexOf(e.d3plus.position)>=0?0:e.d3plus.offset||0}).attr("marker-start","url(#d3plus_whisker_marker)")},l=e.defs.selectAll("#d3plus_whisker_marker").data([0]),l.enter().append("marker").attr("id","d3plus_whisker_marker").attr("markerUnits","userSpaceOnUse").style("overflow","visible").append("line"),a=t.datum(),a?(u=a.d3plus.position,s=["top","bottom"].indexOf(u)>=0?"horizontal":"vertical",f="horizontal"===s?a.d3plus.width:a.d3plus.height):(s="horizontal",f=0),l.select("line").attr("x1","horizontal"===s?-f/2:0).attr("x2","horizontal"===s?f/2:0).attr("y1","vertical"===s?-f/2:0).attr("y2","vertical"===s?f/2:0).call(d).style("stroke-width",2*e.data.stroke.width),e.draw.timing?(n.append("line").attr("class","d3plus_data").call(d).call(o),t.selectAll("line.d3plus_data").data(i).transition().duration(e.draw.timing).call(d).call(c),r.selectAll("line.d3plus_data").transition().duration(e.draw.timing).call(o)):(n.append("line").attr("class","d3plus_data"),t.selectAll("line.d3plus_data").data(i).call(d).call(c))}},{}],241:[function(e,t,n){var r=e("../../../client/pointer.coffee"),a=e("../../../client/prefix.coffee"),i=e("../../../core/console/print.coffee"),o=e("../../../client/touch.coffee"),l=e("../zoom/propagation.coffee");t.exports=function(e){e.dev.value&&i.time("creating SVG elements"),e.svg=e.container.value.selectAll("svg#d3plus").data([0]),e.svg.enter().insert("svg","#d3plus_message").attr("id","d3plus").attr("width",e.width.value).attr("height",e.height.value).attr("xmlns","http://www.w3.org/2000/svg").attr("xmlns:xlink","http://www.w3.org/1999/xlink"),e.g.bg=e.svg.selectAll("rect#bg").data(["bg"]),e.g.bg.enter().append("rect").attr("id","bg").attr("fill",e.background.value).attr("stroke","none").attr("width",e.width.value).attr("height",e.height.value),e.g.timeline=e.svg.selectAll("g#timeline").data(["timeline"]),e.g.timeline.enter().append("g").attr("id","timeline").attr("transform","translate(0,"+e.height.value+")"),e.g.legend=e.svg.selectAll("g#key").data(["key"]),e.g.legend.enter().append("g").attr("id","key").attr("transform","translate(0,"+e.height.value+")"),e.g.footer=e.svg.selectAll("g#footer").data(["footer"]),e.g.footer.enter().append("g").attr("id","footer").attr("transform","translate(0,"+e.height.value+")");var t="clipping_"+e.container.id;e.g.clipping=e.svg.selectAll("#clipping").data(["clipping"]),e.g.clipping.enter().append("clipPath").attr("id",t).append("rect").attr("width",e.width.viz).attr("height",e.height.viz),e.g.container=e.svg.selectAll("g#container").data(["container"]),e.g.container.enter().append("g").attr("id","container").attr("clip-path","url(#"+t+")").attr("transform","translate("+e.margin.left+","+e.margin.top+")"),e.g.zoom=e.g.container.selectAll("g#zoom").data(["zoom"]),e.g.zoom.enter().append("g").attr("id","zoom"),e.g.viz=e.g.zoom.selectAll("g#d3plus_viz").data(["d3plus_viz"]),e.g.viz.enter().append("g").attr("id","d3plus_viz"),e.g.overlay=e.g.viz.selectAll("rect#d3plus_overlay").data([{id:"d3plus_overlay"}]),e.g.overlay.enter().append("rect").attr("id","d3plus_overlay").attr("width",e.width.value).attr("height",e.height.value).attr("opacity",0),e.g.overlay.on(r.move,function(t){o&&l(e,d3.event),e.types[e.type.value].zoom&&e.zoom.pan.value&&e.zoom.behavior.scaleExtent()[0]1&&v(C[0])&&(C=i(n,C,[E])),n.size.value&&v(C[0])){var q=[],P=C.filter(function(e){var t=u(n,e,n.size.value);return!(null===t||"d3plus"in e&&e.d3plus.merged)||void q.push(e)});r(P,n.size.value,"desc",[],n),C=P.concat(q)}var B=n.tooltip.children.value===!0?3:n.tooltip.children.value,D="short"===M?B:n.data.large,R=C.length,I=d3.min([R,D]);g={values:[]};for(var L=0;LI&&(g.d3plusMore=R-I)}m.d3plus.tooltip&&(A=c(A,m.d3plus.tooltip)),n.tooltip.size.value&&(T&&"number"!=typeof n.size.value&&(A[p("size")]=T),n.axes.opposite&&n[n.axes.opposite].value!==n.size.value&&(A[p(n.axes.opposite)]=u(n,m,n[n.axes.opposite].value)),n.axes.opposite&&n[n.axes.opposite+"2"].value!==n.size.value&&(A[p(n.axes.opposite+"2")]=u(n,m,n[n.axes.opposite+"2"].value)),n.color.valueScale&&(A[p("color")]=u(n,m,n.color.value)));var Z=d(n,m,"active"),W=d(n,m,"temp"),J=d(n,m,"total");"number"==typeof Z&&Z>0&&J&&(A[p("active")]=Z+"/"+J+" ("+n.format.value(Z/J*100,{key:"share",vars:n,data:m})+")"),"number"==typeof W&&W>0&&J&&(A[p("temp")]=W+"/"+J+" ("+n.format.value(W/J*100,{key:"share",vars:n,data:m})+")"),n.tooltip.share.value&&m.d3plus.share&&(A.share=n.format.value(100*m.d3plus.share,{key:"share",vars:n,data:m}));var j="depth"in e?e.depth:y,Q=e.title||s(n,m,j)[0],K=h(m,n.icon.value,u,n,n.id.nesting[j]),$=e.titleOnly?[]:o(n,m,M,A,g,j);if(K=1===K.length&&"string"==typeof K[0]&&K[0],$.length>0||S||!m.d3plus_label&&"short"==M&&Q||m.d3plus_label&&(!("visible"in m.d3plus_label)||"visible"in m.d3plus_label&&m.d3plus_label.visible===!1)){Q||(Q=n.format.value(Y,{key:n.id.value,vars:n}));var j="d3plus"in m&&"merged"in m.d3plus?y-1:"depth"in e?e.depth:y;if(j<0&&(j=0),j=n.id.nesting[j],"string"==typeof n.icon.style.value)var ee=n.icon.style.value;else if("object"==typeof n.icon.style.value&&n.icon.style.value[j])var ee=n.icon.style.value[j];else var ee="default";var te=n.tooltip.small;e.width?te=e.width:k&&(te=n.tooltip.large);var ne=!k&&"long"!==e.length||k&&n.tooltip.fullscreen.value?d3.select("body"):n.container.value;!e.description&&m&&n.tooltip.sub.value&&(e.description=u(n,m,n.tooltip.sub.value)),a({align:z,arrow:b,locale:n.format.locale.value,background:n.tooltip.background,curtain:n.tooltip.curtain.color,curtainopacity:n.tooltip.curtain.opacity,fontcolor:n.tooltip.font.color,fontfamily:n.tooltip.font.family.value,fontsize:n.tooltip.font.size,fontweight:n.tooltip.font.weight,data:$,color:l(n,m),allColors:!0,footer:e.footer===!1?e.footer:S,fullscreen:k,html:t,js:e.js,icon:K,id:_,max_height:e.maxheight,max_width:te,mouseevents:x,offset:F,parent:ne,stacked:n.tooltip.stacked.value,style:ee,title:Q,description:e.description,width:e.width||k||0!=$.length?te:"auto",x:O,y:N})}else f(_)}"d3plus"in e.data||(e.data.d3plus={});var n=e.vars,m=e.data,y="d3plus"in m&&"depth"in m.d3plus?m.d3plus.depth:n.depth.value,x=(e.ex,!!e.mouseevents&&e.mouseevents),b=!("arrow"in e)||e.arrow,w=u(n,m,n.id.value),_=e.id||n.type.value;if(!d3.event||"click"!=d3.event.type||!n.tooltip.html.value&&!n.tooltip.value.long||"fullscreen"in e){var k=!1,z=e.anchor||n.tooltip.anchor,M=e.length||"short",A=g(m,n);if(A===-1){var j=n.id.nesting[y-1];u(n,w,j)}var E="";if(n.mouse.click.value&&(!n.mouse.viz||n.mouse.viz.click!==!1))if(1===A&&n.zoom.value)var E=n.format.value(n.format.locale.value.ui.expand);else if(A===-1&&n.zoom.value&&n.history.states.length&&!n.tooltip.value.long)var E=n.format.value(n.format.locale.value.ui.collapse);else if(n.small||"short"!=M||!n.tooltip.html.value&&!n.tooltip.value.long||1===n.focus.value.length&&n.focus.value[0]==w){if("long"==M)var E=n.footer.value||""}else var E=n.format.locale.value.ui.moreInfo;var S=!!E.length&&n.format.value(E,{key:"footer",vars:n})}else{var k=!0,b=!1,x=!0,M="long",S=n.footer.value;n.covered=!0}if("x"in e)var O=e.x;else if("static"===n.types[n.type.value].tooltip){var O=m.d3plus.x;n.zoom.translate&&n.zoom.scale&&(O=n.zoom.translate[0]+O*n.zoom.scale),O+=n.margin.left,"long"!==e.length&&(N+=p.x(),O+=n.container.value.node().getBoundingClientRect().left,O+=parseFloat(n.container.value.style("padding-left"),10))}else var O=d3.mouse(d3.select("html").node())[0];if("y"in e)var N=e.y;else if("static"==n.types[n.type.value].tooltip){var N=m.d3plus.y;n.zoom.translate&&n.zoom.scale&&(N=n.zoom.translate[1]+N*n.zoom.scale),N+=n.margin.top,"long"!==e.length&&(N+=p.y(),N+=n.container.value.node().getBoundingClientRect().top,N+=parseFloat(n.container.value.style("padding-top"),10))}else var N=d3.mouse(d3.select("html").node())[1];if("offset"in e)var F=e.offset;else if("static"==n.types[n.type.value].tooltip){var F=m.d3plus.r?m.d3plus.r:m.d3plus.height/2;n.zoom.scale&&(F*=n.zoom.scale)}else var F=3;if(k||"long"===e.length)if("string"==typeof n.tooltip.html.value)t(n.tooltip.html.value);else if("function"==typeof n.tooltip.html.value)t(n.tooltip.html.value(w));else if(n.tooltip.html.value&&"object"==typeof n.tooltip.html.value&&n.tooltip.html.value.url){var C=n.tooltip.html.value.url;"function"==typeof C&&(C=C(w)),d3.json(C,function(e){var r=n.tooltip.html.value.callback?n.tooltip.html.value.callback(e):e;t(r)})}else t(e.html);else t(e.html)}},{"../../../array/sort.coffee":36,"../../../client/scroll.js":43,"../../../core/data/nest.js":62,"../../../core/fetch/color.coffee":65,"../../../core/fetch/text.js":68,"../../../core/fetch/value.coffee":69,"../../../object/merge.coffee":174,"../../../object/validate.coffee":175,"../../../tooltip/create.js":204,"../../../tooltip/remove.coffee":206,"../../../util/uniques.coffee":213,"../shapes/segments.coffee":236,"../zoom/direction.coffee":253,"./data.js":244}],244:[function(e,t,n){var r=e("../../../util/copy.coffee"),a=e("../../../core/fetch/value.coffee"),i=e("../../../core/fetch/color.coffee"),o=e("../../../core/fetch/text.js"),l=e("../../../color/legible.coffee"),s=e("../../../object/merge.coffee"),u=e("../../../client/prefix.coffee"),c=e("../../../string/format.js"),f=e("../../../object/validate.coffee");t.exports=function(e,t,n,d,p,h){function v(n,r){if(e.attrs.value[r])var i=r;else var i=null;r&&(r=e.format.value(r));var o=m[n]||a(e,t,n,i);if(f(o))w.push({name:e.format.value(n),value:e.format.value(o.value,{key:o.key,vars:e}),group:r});else if(null!=o&&"undefined"!=o&&!(o instanceof Array)&&("string"==typeof o&&o.indexOf("d3plus_other")<0||"string"!=typeof o)){var l=e.format.locale.value.ui[n]?e.format.value(e.format.locale.value.ui[n]):e.format.value(n),s=x.indexOf(n)>=0;o instanceof Array?o.forEach(function(r){r=e.format.value(r,{key:n,vars:e,data:t})}):o=e.format.value(o,{key:n,vars:e,data:t});var u={name:l,value:o,highlight:s,group:r};if(e.descs.value)if("function"==typeof e.descs.value){var c=e.descs.value(n);"string"==typeof c&&(u.desc=c)}else n in e.descs.value&&(u.desc=e.descs.value[n]);w.push(u)}}if(e.small)return[];if(!n)var n="long";if("long"==n)var g="short";else var g="long";var m={};if(d&&"string"==typeof d)d=[d];else if(d&&"object"==typeof d){m=s(m,d);var d=[];for(var y in m)d.push(y)}else if(!d)var d=[];var x=[];if(e.tooltip.value instanceof Array)var b=e.tooltip.value;else if("string"==typeof e.tooltip.value)var b=[e.tooltip.value];else{if(e.tooltip.value[e.id.nesting[h]])var b=e.tooltip.value[e.id.nesting[h]];else var b=e.tooltip.value;b instanceof Array||(b=b[n]?b[n]:b[g]?[]:s({"":[]},b)),"string"==typeof b?b=[b]:b instanceof Array||(b=s({"":[]},b))}var w=[];if(b.constructor===Array&&(b={"":b}),e.id.nesting.length&&hh&&b[e]&&delete b[e]})}for(var _ in b){b[_].constructor!==Array&&(b[_]=[b[_]]);for(var k=d.length;k>0;k--)b[_].indexOf(d[k-1])>=0&&d.splice(k-1,1)}if(e.tooltip.value.long&&"object"==typeof e.tooltip.value.long){for(var _ in e.tooltip.value.long)for(var k=d.length;k>0;k--){var z=d[k-1];e.tooltip.value.long[_].indexOf(z)>=0&&(b[_]||(b[_]=[]),b[_].push(z),d.splice(k-1,1))}}d.length&&(b[""]||(b[""]=[]),b[""]=b[""].concat(d));for(var _ in b)b[_].forEach(function(e){v(e,_)});if(p){var M=e.format.locale.value.ui.including,A=p.d3plus_colors;p.values.forEach(function(t){var n=d3.keys(t)[0];w.push({group:e.format.value(M),highlight:!(!A||!A[n])&&A[n],name:n,value:t[n]})}),p.d3plusMore&&w.push({group:e.format.value(M),highlight:!0,name:c(e.format.locale.value.ui.more,p.d3plusMore),value:""})}if(e.tooltip.connections.value&&"long"===n){var j=e.edges.connections(t[e.id.value],e.id.value,!0);j.length&&j.forEach(function(t){var n=e.data.viz.filter(function(n){return n[e.id.value]===t[e.id.value]}),n=n.length?n[0]:t,r=o(e,n)[0],a=i(e,n),s=e.tooltip.font.size,c="square"==e.shape.value?0:s;styles=["background-color: "+a,"border-color: "+l(a),"border-style: solid","border-width: "+e.data.stroke.width+"px","display: inline-block","height: "+s+"px","left: 0px","position: absolute","width: "+s+"px","top: 0px",u()+"border-radius: "+c+"px"],node="
";var f=function(){e.self.focus([n[e.id.value]]).draw()};w.push({group:e.format.value(e.format.locale.value.ui.primary),highlight:!1,link:f,name:""})})}return w}},{"../../../client/prefix.coffee":41,"../../../color/legible.coffee":46,"../../../core/fetch/color.coffee":65,"../../../core/fetch/text.js":68,"../../../core/fetch/value.coffee":69,"../../../object/merge.coffee":174,"../../../object/validate.coffee":175,"../../../string/format.js":176,"../../../util/copy.coffee":210}],245:[function(e,t,n){var r;r=e("../../../core/console/print.coffee"),t.exports=function(e){var t,n,a,i,o,l,s,u,c,f;if(e.group=e.g.apps[e.type.value],e.mouse.viz=!1,e.edges.path=!1,f=e.types[e.type.value],u=f.requirements||[],a=u.indexOf("data")>=0,i=!a||a&&e.data.viz.length,!e.error.internal&&i){for(t=e.format.locale.value.visualization[e.type.value],e.dev.value&&r.time("running "+t),s=e.data.viz,o=0,l=s.length;o1&&n).focus({callback:i}).format(e.format.locale.language).format({number:e.format.number.value,text:e.format.text.value}).title(e.format.value(l)).type(t.type||"auto").ui({align:e.ui.align.value,border:e.ui.border,color:{primary:e.ui.color.primary.value,secondary:e.ui.color.secondary.value},padding:e.ui.padding,margin:0}).width(t.width||!1).draw()});var c=l.node().offsetHeight||l.node().getBoundingClientRect().height;c&&(e.margin[n]+=c),e.dev.value&&t&&i.timeEnd("drawing custom UI elements")}},{"../../../core/console/print.coffee":54,"../../../form/form.js":106,"../../../object/validate.coffee":175,"../../../util/copy.coffee":210}],247:[function(e,t,n){var r,a,i,o;r=e("../../../client/pointer.coffee"),a=e("../../../color/lighter.coffee"),i=e("../../../core/console/print.coffee"),o=e("../../../client/css.coffee"),t.exports=function(e){var t,n,l,s,u,c,f,d,p,h,v,g,m,y,x;return!e.small&&e.history.states.length>0?(e.dev.value&&i.time("drawing back button"),t=e.container.value.selectAll("div#d3plus_back_button").data(["d3plus_back_button"]).style("position","relative").style("z-index",1900),p=e.title.sub.font.size,n=e.title.sub.font.color,u=e.title.sub.font.family.value,x=e.title.sub.font.weight,d=e.title.sub.padding,g=!1,e.title.sub.value&&["start","left"].indexOf(e.title.sub.font.align)<0?g="sub":e.title.total.value&&["start","left"].indexOf(e.title.total.font.align)<0?g="total":e.title.value&&["start","left"].indexOf(e.title.font.align)<0&&(g="title"),g?(h=function(e){var t;return t=e.attr("transform").match(/translate\(([^a-z]+)\)/gi)[0],t=t.replace(/([^a-z])\s([^a-z])/gi,"$1,$2"),t=t.split(","),t=t[t.length-1],parseFloat(t.substring(0,t.length-1))},m=e.svg.select(".d3plus_title."+g),y=h(m)+h(m.select("text"))):(y=e.margin.top-e.title.padding,f=p+2*d,e.margin.top+=f),l=parseFloat(e.container.value.style("padding-top"),10),y+=l,l=parseFloat(e.container.value.style("padding-left"),10),c=e.margin.left+p/2+l,v=function(e){return e.style("position","absolute").style("left",c+"px").style("top",y+"px").style("color",n).style("font-family",u).style("font-weight",x).style("font-size",p+"px")},s=t.enter().append("div").attr("id","d3plus_back_button").style("opacity",0).call(v).html(function(){var t;return o("font-awesome")&&0===e.icon.back.value.indexOf("fa-")?(t=""):t=e.icon.back.value+" ",t+e.format.value(e.format.locale.value.ui.back)}),t.on(r.over,function(){if(!e.small&&e.history.states.length>0)return d3.select(this).style("cursor","pointer").transition().duration(e.timing.mouseevents).style("color",a(n,.25))}).on(r.out,function(){if(!e.small&&e.history.states.length>0)return d3.select(this).style("cursor","auto").transition().duration(e.timing.mouseevents).style("color",n)}).on(r.click,function(){return e.history.back()}).transition().duration(e.draw.timing).style("opacity",1).call(v),e.dev.value?i.timeEnd("drawing back button"):void 0):e.container.value.selectAll("div#d3plus_back_button").transition().duration(e.draw.timing).style("opacity",0).remove()}},{"../../../client/css.coffee":38,"../../../client/pointer.coffee":40,"../../../color/lighter.coffee":47,"../../../core/console/print.coffee":54}],248:[function(e,t,n){var r=e("../../../array/sort.coffee"),a=e("../../../util/buckets.coffee"),i=e("../../../util/copy.coffee"),o=e("../tooltip/create.js"),l=e("../../../core/data/nest.js"),s=e("../../../util/dataURL.coffee"),u=e("../../../client/pointer.coffee"),c=e("../../../core/fetch/value.coffee"),f=e("../../../core/fetch/color.coffee"),d=e("../../../core/fetch/text.js"),p=e("../../../core/console/print.coffee"),h=e("../../../tooltip/remove.coffee"),v=e("../../../color/text.coffee"),g=e("../../../util/uniques.coffee"),m=e("../../../client/scroll.js"),y=e("../../../string/strip.js"),x=e("../../../textwrap/textwrap.coffee"),b=(e("../../../client/touch.coffee"),e("../../../object/validate.coffee"));t.exports=function(e){function t(t){t.attr("transform",function(t,n){var r=C+n*(e.ui.padding+_);return"translate("+r+","+e.ui.padding+")"})}function n(t){t.attr("width",_).attr("height",_).attr("fill",function(t){d3.select(this.parentNode).select("text").remove();var n=g(t,e.icon.value,c,e,I),r=f(e,t,I);if(e.legend.icons.value&&1===n.length&&"string"==typeof n[0]){n=n[0];var a,i=y(n+"_"+r),o=e.icon.style.value,l=e.defs.selectAll("pattern#"+i).data([i]);a="string"==typeof o?e.icon.style.value:b(o)&&o[I]?o[I]:"default",r="knockout"==a?r:"none",l.select("rect").transition().duration(e.draw.timing).attr("fill",r).attr("width",_).attr("height",_),l.select("image").transition().duration(e.draw.timing).attr("width",_).attr("height",_);var u=l.enter().append("pattern").attr("id",i).attr("width",_).attr("height",_);return u.append("rect").attr("fill",r).attr("stroke","none").attr("width",_).attr("height",_),u.append("image").attr("xlink:href",n).attr("width",_).attr("height",_).each(function(e){0===n.indexOf("/")||n.indexOf(window.location.hostname)>=0?s(n,function(e){l.select("image").attr("xlink:href",e)}):l.select("image").attr("xlink:href",n)}),"url(#"+i+")"}if(e.legend.labels.value){var p;if(p=e.legend.text.value?[c(e,t,e.legend.text.value,R)]:d(e,t,R),1===p.length&&!(p[0]instanceof Array)&&p[0].length){var h=d3.select(this.parentNode).append("text"),m=e.legend.font.size;m instanceof Array||(m=[m]),h.attr("font-size",m[m.length-1]+"px").attr("font-weight",e.legend.font.weight).attr("font-family",e.legend.font.family.value).attr("stroke","none").attr("fill",v(r)).attr("x",0).attr("y",0).each(function(t){x().align("middle").container(d3.select(this)).height(_).padding(e.ui.padding).resize(m.length>1).size(m).text(p[0]).width(_).valign("middle").draw()}),h.select("tspan").empty()&&h.remove()}}return r})}var w=!0,_=0;if(!e.error.internal&&e.color.value&&!e.small&&e.legend.value)if(e.color.valueScale)if(e.color.valueScale){e.dev.value&&p.time("drawing color scale"),e.g.legend.selectAll("g.d3plus_color").transition().duration(e.draw.timing).attr("opacity",0).remove();var k=e.color.valueScale.domain(),z=e.color.valueScale.range();k.length<=2&&(k=a(k,6));var M=e.g.legend.selectAll("g.d3plus_scale").data(["scale"]);M.enter().append("g").attr("class","d3plus_scale").attr("opacity",0);var A=e.container.id+"_legend_heatmap",j=M.selectAll("#"+A).data(["heatmap"]);j.enter().append("linearGradient").attr("id",A).attr("x1","0%").attr("y1","0%").attr("x2","100%").attr("y2","0%").attr("spreadMethod","pad");var E=j.selectAll("stop").data(d3.range(0,z.length));E.enter().append("stop").attr("stop-opacity",1),E.attr("offset",function(e){return Math.round(e/(z.length-1)*100)+"%"}).attr("stop-color",function(e){return z[e]}),E.exit().remove();var S=M.selectAll("rect#gradient").data(["gradient"]);S.enter().append("rect").attr("id","gradient").attr("x",function(t){return"middle"==e.legend.align?e.width.value/2:"end"==e.legend.align?e.width.value:0}).attr("y",e.ui.padding).attr("width",0).attr("height",e.legend.gradient.height).attr("stroke",e.legend.font.color).attr("stroke-width",1).style("fill","url(#"+A+")");var O=M.selectAll("text.d3plus_tick").data(d3.range(0,k.length));O.enter().append("text").attr("class","d3plus_tick").attr("stroke","none").attr("x",function(t){return"middle"==e.legend.align?e.width.value/2:"end"==e.legend.align?e.width.value:0}).attr("y",function(t){return this.getBBox().height+e.legend.gradient.height+2*e.ui.padding});var N=0;O.order().attr("font-weight",e.legend.font.weight).attr("font-family",e.legend.font.family.value).attr("font-size",e.legend.font.size+"px").style("text-anchor",e.legend.font.align).attr("fill",e.legend.font.color).text(function(t){return e.format.value(k[t],{key:e.color.value,vars:e})}).attr("y",function(t){return this.getBBox().height+e.legend.gradient.height+2*e.ui.padding}).each(function(e){var t=Math.ceil(this.getBBox().width);t>N&&(N=t)}),N+=2*e.labels.padding;var F=N*(k.length-1);if(F+N=0){if(q=i(e.nodes.restriced||e.nodes.value),e.data.viz.length)for(var P=0;P=0)R=L,I=e.id.nesting[L];else for(var V=0;V<=e.depth.value;V++){R=V,I=e.id.nesting[V];var U=g(q,function(t){return c(e,t,I)}),Y=g(q,D);if(U.length>=Y.length&&Y.length>1)break}var H=[e.color.value],z=l(e,q,H,!1); +e.dev.value&&p.timeEnd("grouping data by color");var X=e.width.value;_=e.legend.size;var F=_*z.length+e.ui.padding*(z.length+1);if(_ instanceof Array){e.dev.value&&p.time("calculating legend size");for(var P=_[1];P>=_[0];P--)if(F=P*z.length+e.ui.padding*(z.length+1),X>=F){_=P;break}e.dev.value&&p.timeEnd("calculating legend size")}else"number"!=typeof _&&_!==!1&&(_=30);if(X=0?d(e,t,f)[0]:e.format.value(c(e,t,e.color.value,I),{key:e.color.value,vars:e,data:t});var p,h;if(e.legend.filters.value&&!(s instanceof Array)){p="
";var v=e.format.locale.value;p+="
"+e.format.value(v.method.mute)+"
",p+="
"+e.format.value(v.method.solo)+"
",p+="
",h=function(t){var n={border:"1px solid #ccc",display:"inline-block",margin:"1px 2px",padding:"3px 5px"};t.select(".mute").style(n).on(u.over,function(){d3.select(this).style("cursor","pointer")}).on(u.click,function(){var t=e.id.mute.value;e.history.states.push(function(){e.self.id({mute:t}).draw()}),e.self.id({mute:s}).draw()}),t.select(".solo").style(n).on(u.over,function(){d3.select(this).style("cursor","pointer")}).on(u.click,function(){var t=e.id.solo.value;e.history.states.push(function(){e.self.id({solo:t}).draw()}),e.self.id({solo:s}).draw()})}}o({data:t,html:p,js:h,depth:R,footer:!1,vars:e,x:i,y:l,mouseevents:this,title:r,titleOnly:!e.legend.data.value,offset:.4*_})}).on(u.out,function(t){h(e.type.value)}),e.dev.value&&p.timeEnd("drawing legend")}}else w=!1;if(e.legend.value&&key&&w){if(e.dev.value&&p.time("positioning legend"),_)var Q=_+e.ui.padding;else var K=e.g.legend.node().getBBox(),Q=K.height+K.y;0===e.margin.bottom&&(e.margin.bottom+=e.ui.padding),e.margin.bottom+=Q,e.g.legend.transition().duration(e.draw.timing).attr("transform","translate(0,"+(e.height.value-e.margin.bottom)+")"),e.dev.value&&p.timeEnd("positioning legend")}else e.dev.value&&p.time("hiding legend"),e.g.legend.transition().duration(e.draw.timing).attr("transform","translate(0,"+e.height.value+")"),e.dev.value&&p.timeEnd("hiding legend")}},{"../../../array/sort.coffee":36,"../../../client/pointer.coffee":40,"../../../client/scroll.js":43,"../../../client/touch.coffee":45,"../../../color/text.coffee":52,"../../../core/console/print.coffee":54,"../../../core/data/nest.js":62,"../../../core/fetch/color.coffee":65,"../../../core/fetch/text.js":68,"../../../core/fetch/value.coffee":69,"../../../object/validate.coffee":175,"../../../string/strip.js":178,"../../../textwrap/textwrap.coffee":203,"../../../tooltip/remove.coffee":206,"../../../util/buckets.coffee":207,"../../../util/copy.coffee":210,"../../../util/dataURL.coffee":212,"../../../util/uniques.coffee":213,"../tooltip/create.js":243}],249:[function(e,t,n){var r=e("../../../client/pointer.coffee"),a=e("../../../color/text.coffee");t.exports=function(e,t){function n(t){t.style(o).style("position","absolute").style("background-color",s).style("text-align","center").style("left",function(){return"center"==l?"50%":"0px"}).style("width",function(){return"center"==l?"auto":e.width.value+"px"}).style("margin-left",function(){return"center"==l?-(this.offsetWidth/2)+"px":"0px"}).style("top",function(){return"center"==l?"50%":"top"==l?"0px":"auto"}).style("bottom",function(){return"bottom"==l?"0px":"auto"}).style("margin-top",function(){if("large"==i){var e=this.offsetHeight||this.getBoundingClientRect().height;return-e/2+"px"}return"0px"})}t=e.messages.value?t:null;var i=e.messages.style.value||(t===e.error.internal?"large":e.messages.style.backup);if("large"===i)var o=e.messages,l="center";else{if(e.footer.value)var o=e.footer;else if(e.title.value)var o=e.title;else if(e.title.sub.value)var o=e.title.sub;else if(e.title.total.value)var o=e.title.total;else var o=e.title.sub;var l=o.position}var o={color:o.font.color,"font-family":o.font.family.value,"font-weight":o.font.weight,"font-size":o.font.size+"px",padding:o.padding+"px"},s=e.messages.background.value;s||(s=e.background.value,"none"!==s&&"transparent"!==s||(s=a(o.color))),e.g.message=e.container.value.selectAll("div#d3plus_message").data(["message"]);var u=e.g.message.enter().append("div").attr("id","d3plus_message").attr("opacity",0);u.append("div").attr("class","d3plus_message_text").style("display","block"),e.g.message.select(".d3plus_message_text").text(t?t:e.g.message.text());var c=navigator.onLine,f=75,d=e.g.message.selectAll(".d3plus_message_branding").data(e.messages.branding.value&&"center"===l?[0]:[]);d.enter().append("div").attr("class","d3plus_message_branding").style("margin-top","15px").style("padding-top","0px").style("display","block").style("font-size","11px").style("background-size",f+"px").style("background-position","center 10px").style("background-repeat","no-repeat").style("cursor","pointer").on(r.click,function(){window.open("http://www.d3plus.org/","_blank")});var p=d3.hsl(s).l<.5?e.messages.branding.image.dark:e.messages.branding.image.light;d.text(c?"Powered by:":"Powered by D3plus").style("background-color",c?s:"transparent").style("background-image",c?"url('"+p+"')":"none").style("min-width",c?f+"px":"auto").style("height",c?f+"px":"auto"),d.exit().remove(),e.g.message.style("display",t?"inline-block":"none").call(n).style("opacity",t?1:0)}},{"../../../client/pointer.coffee":40,"../../../color/text.coffee":52}],250:[function(e,t,n){var r,a,i,o,l,s,u,c,f,d;r=e("../../../util/closest.coffee"),a=e("../../../client/css.coffee"),o=e("../../../font/sizes.coffee"),i=e("../../../client/pointer.coffee"),l=e("../../../color/mix.coffee"),u=e("../../../client/prefix.coffee"),c=e("../../../core/console/print.coffee"),f=e("../../../color/text.coffee"),d=e("../../../core/data/time.coffee"),s=!1,t.exports=function(e){var t,n,o,p,h,v,g,m,y,x,b,w,_,k,z,M,A,j,E,S,O,N,F,C,T,q,P,B,D,R,I,L,V,U,Y,H,X,G,Z,W,J,Q,K,$,ee,te,ne,re,ae,ie,oe;if(!e.timeline.value||e.error.internal&&e.data.missing||e.small||!e.data.time||!(e.data.time.values.length>1))return e.g.timeline.transition().duration(e.draw.timing).attr("transform","translate(0,"+e.height.value+")");if(e.dev.value&&c.time("drawing timeline"),H={"font-weight":e.ui.font.weight,"font-family":e.ui.font.family.value,"font-size":e.ui.font.size+"px","text-anchor":"middle"},oe=e.data.time.ticks.map(function(e){return new Date(e)}),J=d(e,{values:oe,style:H}),te=J.values.map(Number),W=J.format,e.time.solo.value.length)for(w=d3.extent(e.time.solo.value),b=_=0,M=w.length;_=re,t=e.width.value-2*e.ui.padding,V&&e.timeline.play.value&&(t-=P+e.ui.padding),!V||te.length=1)e=[n,t];else if(E+1<=oe.length)e=[n,ie[E+1]];else{for(e=[n],b=1;b<=1;)E+b<=oe.length?e.push(ie[E+b]):e.unshift(ie[E-(E+b-oe.length)]),b++;e=[e[0],e[e.length-1]]}return p=e,U.attr("fill",Y),d3.select(this).call(o.extent(e))}},B=function(){var t;return A-E===oe.length-$?t=[]:(t=ae.filter(function(e,t){return t>=E&&t=p[0]&&r?(a=1,n=f(e.ui.color.secondary.value)):(a=.5,n=f(e.ui.color.primary.value)),$&&e.background.value&&"none"!==e.background.value&&(n=d3.rgb(f(e.background.value))),n=d3.rgb(n),"rgba("+n.r+","+n.g+","+n.b+","+a+")"},n=e.g.timeline.selectAll("rect.d3plus_timeline_background").data(["background"]),n.enter().append("rect").attr("class","d3plus_timeline_background").attr("shape-rendering","crispEdges").attr("width",ee+2).attr("height",K+2).attr("fill",e.ui.color.primary.value).attr("x",R-1).attr("y",e.ui.padding),n.transition().duration(e.draw.timing).attr("width",ee+2).attr("height",K+2).attr("fill",e.ui.color.primary.value).attr("x",R-1).attr("y",e.ui.padding),Z=e.g.timeline.selectAll("g#ticks").data(["ticks"]),Z.enter().append("g").attr("id","ticks").attr("transform","translate("+e.width.value/2+","+e.ui.padding+")"),h=e.g.timeline.selectAll("g#brush").data(["brush"]),h.enter().append("g").attr("id","brush"),z=e.g.timeline.selectAll("g#labels").data(["labels"]),z.enter().append("g").attr("id","labels"),U=z.selectAll("text").data(oe,function(e,t){return t}),U.enter().append("text").attr("stroke","none").attr("y",0).attr("dy","0.5ex").attr("x",0),ne=d3.time.scale().domain(d3.extent(ie)).rangeRound([0,ee]),U.order().attr(H).text(function(e,t){return te.indexOf(+e)>=0?W(e):""}).attr("opacity",function(t,n){return e.data.time.dataSteps.indexOf(n)>=0?1:.4}).attr("fill",Y).attr("transform",function(t,n){var r,a;return r=R+ne(t),$||(r+=k/2),a=K/2+e.ui.padding+1,$&&(a+=K/2+re),"translate("+Math.round(r)+","+Math.round(a)+")"}),U.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),o=d3.svg.brush().x(ne).extent(p).on("brush",v).on("brushend",g),X=e.axes.discrete&&e[e.axes.discrete].value===e.time.value?e[e.axes.discrete].ticks.color:e.x.ticks.color,Z.attr("transform","translate("+R+","+(e.ui.padding+1)+")").transition().duration(e.draw.timing).call(d3.svg.axis().scale(ne).orient("top").ticks(function(){return ie}).tickFormat("").tickSize(-K).tickPadding(0)).selectAll("line").attr("stroke-width",1).attr("shape-rendering","crispEdges").attr("stroke",function(t){return te.indexOf(+t)>=0?X:l(X,e.background.value,.4,1)}),Z.selectAll("path").attr("fill","none"),h.attr("transform","translate("+R+","+(e.ui.padding+1)+")").attr("opacity",1).call(o),U.attr("pointer-events","none"),h.selectAll("rect.background").attr("fill","none").style("visibility","visible").attr("height",K).attr("shape-rendering","crispEdges").on(i.move,function(){var t;return t=e.timeline.hover.value,["grab","grabbing"].indexOf(t)>=0&&(t=u()+t),d3.select(this).style("cursor",t)}),h.selectAll("rect.extent").attr("opacity",.75).attr("height",K).attr("fill",e.ui.color.secondary.value).attr("shape-rendering","crispEdges").on(i.move,function(){var t;return t=e.timeline.hover.value,["grab","grabbing"].indexOf(t)>=0&&(t=u()+t),d3.select(this).style("cursor",t)}),e.timeline.handles.value?(x=h.selectAll("g.resize").selectAll("rect.d3plus_handle").data(["d3plus_handle"]),x.enter().insert("rect","rect").attr("class","d3plus_handle"),x.attr("fill",e.timeline.handles.color).attr("transform",function(t){var n;return n="resize e"===this.parentNode.className.baseVal?-e.timeline.handles.size:0,"translate("+n+",0)"}).attr("width",e.timeline.handles.size).style("visibility","visible").attr("shape-rendering","crispEdges").attr("opacity",e.timeline.handles.opacity),h.selectAll("g.resize").selectAll("rect").attr("height",K)):h.selectAll("g.resize").remove(),Q=e.g.timeline.node().getBBox(),0===e.margin.bottom&&(e.margin.bottom+=e.ui.padding),e.margin.bottom+=Q.height+Q.y,e.g.timeline.transition().duration(e.draw.timing).attr("transform","translate(0,"+Math.round(e.height.value-e.margin.bottom-e.ui.padding/2)+")"),e.margin.bottom+=e.ui.padding,e.dev.value?c.time("drawing timeline"):void 0}},{"../../../client/css.coffee":38,"../../../client/pointer.coffee":40,"../../../client/prefix.coffee":41,"../../../color/mix.coffee":48,"../../../color/text.coffee":52,"../../../core/console/print.coffee":54,"../../../core/data/time.coffee":64,"../../../font/sizes.coffee":104,"../../../util/closest.coffee":209}],251:[function(e,t,n){var r=e("../../../client/pointer.coffee"),a=e("../../../core/fetch/value.coffee"),i=e("../../../core/console/print.coffee"),o=e("../../../client/rtl.coffee"),l=e("../../../textwrap/textwrap.coffee");t.exports=function(e){function t(t){t.attr("font-size",function(e){return e.style.font.size}).attr("fill",function(t){return t.link?e.links.font.color:t.style.font.color}).attr("font-family",function(t){return t.link?e.links.font.family.value:t.style.font.family.value}).attr("font-weight",function(t){return t.link?e.links.font.weight:t.style.font.weight}).style("text-decoration",function(t){return t.link?e.links.font.decoration.value:t.style.font.decoration.value}).style("text-transform",function(t){return t.link?e.links.font.transform.value:t.style.font.transform.value})}function n(e){var t=e.style.font.align;return"center"==t?"middle":"left"==t&&!o||"right"==t&&o?"start":"left"==t&&o||"right"==t&&!o?"end":t}var s=e.size.value?e.size.value:"number"===e.color.type&&e.color.value;if(e.data.viz&&e.title.total.value&&!e.small)if(s){e.dev.value&&i.time("calculating total value");var u=e.data.pool;e.focus.value.length&&(u=e.data.viz.filter(function(t){return t[e.id.value]==e.focus.value[0]}));var c,f=e.aggs.value[s]||"sum";if(f.constructor===Function?c=f(u):(u=u.reduce(function(t,n){var r=a(e,n,s);return r instanceof Array?t=t.concat(r):t.push(r),t},[]),c=d3[f](u)),0!==c&&null!==c&&void 0!==c||(c=!1),"number"==typeof c){var d="";if(e.data.mute.length||e.data.solo.length||e.focus.value.length){var p=d3.sum(e.data.value,function(t){if(e.time.solo.value.length>0)var n=e.time.solo.value.indexOf(a(e,t,e.time.value))>=0;else if(e.time.mute.value.length>0)var n=e.time.solo.value.indexOf(a(e,t,e.time.value))<0;else var n=!0;if(n)return a(e,t,s)});if(p>c){var d=c/p*100,h=e.format.value(p,{key:e.size.value,vars:e});d=" ("+e.format.value(d,{key:"share",vars:e})+" of "+h+")"}}c=e.format.value(c,{key:e.size.value,vars:e});var v=e.title.total.value,g=v.prefix||e.format.value(e.format.locale.value.ui.total)+": ";c=g+c,v.suffix?c+=v.suffix:null,c+=d}e.dev.value&&i.timeEnd("calculating total value")}else var c=!1;else var c=!1;var m=[];if(e.footer.value&&m.push({link:e.footer.link,style:e.footer,type:"footer",value:e.footer.value}),!e.small){if(e.title.value){var y=e.title.value;"function"==typeof y&&(y=y(e.self)),m.push({link:e.title.link,style:e.title,type:"title",value:y})}if(e.title.sub.value){var y=e.title.sub.value;"function"==typeof y&&(y=y(e.self)),m.push({link:e.title.sub.link,style:e.title.sub,type:"sub",value:y})}e.title.total.value&&c&&m.push({link:e.title.total.link,style:e.title.total,type:"total",value:c})}e.dev.value&&i.time("drawing titles");var x=e.svg.selectAll("g.d3plus_title").data(m,function(e){return e.type}),b=e.title.width||e.width.value-e.margin.left-e.margin.right;x.enter().append("g").attr("class",function(e){return"d3plus_title "+e.type}).attr("opacity",0).append("text").attr("stroke","none").call(t),x.each(function(r){var a=d3.select(this).select("text").call(t),i=n(r);l().align(i).container(a).height(e.height.value/2).size(!1).text(r.value).width(b).draw(),r.y=e.margin[r.style.position],e.margin[r.style.position]+=this.getBBox().height+2*r.style.padding}).on(r.over,function(t){t.link&&d3.select(this).transition().duration(e.timing.mouseevents).style("cursor","pointer").select("text").attr("fill",e.links.hover.color).attr("font-family",e.links.hover.family.value).attr("font-weight",e.links.hover.weight).style("text-decoration",e.links.hover.decoration.value).style("text-transform",e.links.hover.transform.value)}).on(r.out,function(n){n.link&&d3.select(this).transition().duration(e.timing.mouseevents).style("cursor","auto").select("text").call(t)}).on(r.click,function(e){if(e.link){var t="/"!=e.link.charAt(0)?"_blank":"_self";window.open(e.link,t)}}).attr("opacity",1).attr("transform",function(t){var r=t.style.position,a="top"==r?0+t.y:e.height.value-t.y;"bottom"==r?a-=this.getBBox().height+t.style.padding:a+=t.style.padding;var i=n(t);if("start"===i)var o=e.margin.left+e.title.padding;else{d3.select(this).select("text").node().getBBox().width;o="middle"===i?e.width.value/2-b/2:e.width.value-b-e.margin.right-e.title.padding}return"translate("+o+","+a+")"}),x.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),e.margin.top>0&&(e.margin.top+=e.title.padding),e.margin.bottom>0&&(e.margin.bottom+=e.title.padding);var w=e.title.height;w&&e.margin[e.title.position]s&&(f=s),e.zoom.scale=f,d=[e.width.viz/2-e.zoom.size.width*f/2-t[0][0]*f,e.height.viz/2-e.zoom.size.height*f/2-t[0][1]*f],e.zoom.translate=d,e.zoom.behavior.translate(d).scale(f),e.zoom.size={height:e.zoom.bounds[1][1]-e.zoom.bounds[0][1],width:e.zoom.bounds[1][0]-e.zoom.bounds[0][0]},e.zoom.reset=!1,(e.labels.value||e.labels.changed)&&r(e),a(e,n)}},{"./labels.coffee":254,"./transform.coffee":257}],253:[function(e,t,n){t.exports=function(e,t){var n,r,a;return r=t.id.nesting.length-1,n=t.depth.value,a=t.id.nesting[n+1],t.types[t.type.value].nesting===!1?0:(e.d3plus.merged||a in e&&n0||e&&a&&!(a in e))||!t.small&&t.tooltip.html.value?0:-1}},{}],254:[function(e,t,n){var r;r=e("../../../core/console/print.coffee"),t.exports=function(e){var t,n;if(e.dev.value&&r.time("determining label visibility"),n=e.zoom.behavior.scaleExtent(),t=function(t){return t.attr("opacity",function(t){var r;return t||(t={}),r=parseFloat(d3.select(this).attr("font-size"),10),t.visible=r*(e.zoom.scale/n[1])>=2,t.visible?1:0})},e.draw.timing?e.g.viz.selectAll("text.d3plus_label").transition().duration(e.draw.timing).call(t):e.g.viz.selectAll("text.d3plus_label").call(t),e.dev.value)return r.timeEnd("determining label visibility")}},{"../../../core/console/print.coffee":54}],255:[function(e,t,n){var r,a,i;r=e("./labels.coffee"),a=e("../../../tooltip/remove.coffee"),i=e("./transform.coffee"),t.exports=function(e){var t,n,o,l,s,u,c,f,d,p,h;return n=d3.event.sourceEvent?d3.event.sourceEvent.type:null,s=d3.event.translate,l=d3.event.scale,o=e.zoom.bounds,f=(e.width.viz-e.zoom.size.width*l)/2,c=f>0?f:0,u=f>0?e.width.viz-f:e.width.viz,h=(e.height.viz-e.zoom.size.height*l)/2,p=h>0?h:0,d=h>0?e.height.viz-h:e.height.viz,s[0]+o[0][0]*l>c?s[0]=-o[0][0]*l+c:s[0]+o[1][0]*lp?s[1]=-o[0][1]*l+p:s[1]+o[1][1]*lr.behavior.scaleExtent()[0],n=e.types[e.type.value].zoom&&r.value&&r.scroll.value,a=t.touches&&t.touches.length>1&&n,a||i||t.stopPropagation()}},{}],257:[function(e,t,n){t.exports=function(e,t){var n;return"number"!=typeof t&&(t=e.timing.transitions),n="translate("+e.zoom.translate+")",n+="scale("+e.zoom.scale+")",t?e.g.viz.transition().duration(t).attr("transform",n):e.g.viz.attr("transform",n)}},{}],258:[function(e,t,n){var r;r=e("../../core/methods/filter.coffee"),t.exports={accepted:[!1,Function,Object,String],deprecates:"active_var",mute:r(!0),solo:r(!0),spotlight:{accepted:[Boolean],deprecates:"spotlight",value:!1},value:!1}},{"../../core/methods/filter.coffee":83}],259:[function(e,t,n){t.exports={accepted:[Object],deprecated:"nesting_aggs",objectAccess:!1,value:{}}},{}],260:[function(e,t,n){var r;r=e("../../core/methods/process/data.coffee"),t.exports={accepted:[!1,Array,Object,String],delimiter:{accepted:String,value:"|"},filetype:{accepted:[!1,"json","xml","html","csv","dsv","tsv","txt"],value:!1},keys:{},process:r,value:!1}},{"../../core/methods/process/data.coffee":89}],261:[function(e,t,n){var r,a;r=e("../../core/methods/process/margin.coffee"),a=e("../../core/methods/rendering.coffee"),t.exports={background:{color:"#fafafa",rendering:a(),stroke:{color:"#ccc",width:1}},margin:{accepted:[Number,Object,String],process:function(e){var t;return void 0===e&&(e=this.value),t=e,r(e,this),t},value:10},mirror:{accepted:[Boolean],deprecates:["mirror_axis","mirror_axes"],value:!1},ticks:{accepted:[Boolean],value:!0}}},{"../../core/methods/process/margin.coffee":92,"../../core/methods/rendering.coffee":94}],262:[function(e,t,n){t.exports={accepted:[String],value:"#ffffff"}},{}],263:[function(e,t,n){t.exports={accepted:[Function,String],value:!1}},{}],264:[function(e,t,n){var r,a;r=e("../../core/methods/filter.coffee"),a=e("../../color/scale.coffee"),t.exports={accepted:[!1,Array,Function,Object,String],deprecates:"color_var",domain:{accepted:[!1,Array],value:!1},focus:"#444444",heatmap:["#282F6B","#419391","#AFD5E8","#EACE3F","#B35C1E","#B22200"],missing:"#eeeeee",mute:r(!0),primary:"#d74b03",range:["#B22200","#FFEE8D","#759143"],scale:{accepted:[Array,Function,"d3plus","category10","category20","category20b","category20c"],process:function(e){return e instanceof Array?d3.scale.ordinal().range(e):"d3plus"===e?a:"string"==typeof e?d3.scale[e]():e},value:"d3plus"},solo:r(!0),secondary:"#e5b3bb",value:!1}},{"../../color/scale.coffee":50,"../../core/methods/filter.coffee":83}],265:[function(e,t,n){t.exports={accepted:[Array,Function,String],index:{accepted:[Boolean],value:!0},process:function(e,t){return"string"==typeof e&&(e=[e]),e},value:!1}},{}],266:[function(e,t,n){arguments[4][110][0].apply(n,arguments)},{dup:110}],267:[function(e,t,n){var r;r=e("../../util/d3selection.coffee"),t.exports={accepted:[!1,Array,Object,String],id:"default",process:function(e,t){return e!==!1&&("default"===t.container.id&&t.self.container({id:"d3plus_"+ +new Date}),r(e)?e.append("div"):e instanceof Array?d3.select(e[0][0]).append("div"):(this.selector=e,d3.select(e).append("div")))},value:!1}},{"../../util/d3selection.coffee":211}],268:[function(e,t,n){var r,a;r=e("../../core/methods/filter.coffee"),a=e("../../core/methods/process/data.coffee"),t.exports={accepted:[!1,Array,Function,Object,String],center:[0,0],filetype:{accepted:["json"],value:"json"},fit:{accepted:["auto","height","width"],value:"auto"},key:!1,mute:r(!1),padding:20,process:a,projection:{accepted:["albers","albersUsa","azimuthalEqualArea","azimuthalEquidistant","conicConformal","conicEqualArea","conicEquidistant","equirectangular","gnomonic","mercator","orthographic","stereographic","transverseMercator",Function],value:"mercator"},simplify:{accepted:[Boolean],value:!0},solo:r(!1),threshold:{accepted:[Number],value:.9},value:!1}},{"../../core/methods/filter.coffee":83,"../../core/methods/process/data.coffee":89}],269:[function(e,t,n){var r,a,i;r=e("../../core/fetch/value.coffee"),a=e("../../client/ie.js"),i=e("../../string/strip.js"),t.exports={accepted:[void 0,!0,Array,String],chainable:!1,data:[],process:function(e,t){var n,o,l,s,u,c,f,d,p,h,v,g,m,y,x,b,w,_,k,z,M,A,j,E,S,O,N,F,C,T,q,P,B,D,R,I;if(void 0===t.returned)return[];if(e=e||t.cols.value,e instanceof Array?s=e:"string"==typeof e&&(s=[e]),c=[],R=[],t.title.value?(D=t.title.value,"function"==typeof D&&(D=D(t.self)),D=i(D),E=250,D=D.substr(0,E)):D="D3plus Visualization Data",e===!0)for(s=d3.keys(t.data.keys),c.push(s),T=t.data.value,v=0,y=T.length;v=0&&(e=this.accepted[t]),e},value:"middle"},color:{accepted:[!1,String],value:!1},font:{decoration:r(),family:a(),size:11,transform:i(),weight:200},padding:7,resize:{accepted:[Boolean],value:!0},text:{accepted:[!1,Function,String],value:!1},segments:2,valign:{accepted:[!1,"top","middle","bottom"],value:"middle"},value:!0}},{"../../core/methods/font/decoration.coffee":85,"../../core/methods/font/family.coffee":86,"../../core/methods/font/transform.coffee":88}],287:[function(e,t,n){var r;r=e("../../core/methods/font/family.coffee"),t.exports={accepted:[Boolean],align:"middle",data:{accepted:[Boolean],value:!0},filters:{accepted:[Boolean],value:!1},font:{align:"middle",color:"#444444",family:r(),size:[8,14],weight:200},gradient:{height:10},icons:{accepted:[Boolean],value:!0},labels:{accepted:[Boolean],value:!0},order:{accepted:["color","id","size","text",Function],sort:{accepted:["asc","desc"],value:"asc"},value:"color"},size:[8,30],tooltip:{accepted:[Boolean],value:!0},text:{accepted:[!1,Function,String],value:!1},title:{accepted:[!1,Function,String],value:!1},value:!0}},{"../../core/methods/font/family.coffee":86}],288:[function(e,t,n){var r,a,i;r=e("../../core/methods/font/decoration.coffee"),a=e("../../core/methods/font/family.coffee"),i=e("../../core/methods/font/transform.coffee"),t.exports={font:{color:"#444444",decoration:r(),family:a(),transform:i(),weight:200},hover:{color:"#444444",decoration:r(),family:a(),transform:i(),weight:200}}},{"../../core/methods/font/decoration.coffee":85,"../../core/methods/font/family.coffee":86,"../../core/methods/font/transform.coffee":88}],289:[function(e,t,n){arguments[4][125][0].apply(n,arguments)},{"../../core/methods/process/margin.coffee":92,dup:125}],290:[function(e,t,n){var r,a,i;r=e("../../core/methods/font/decoration.coffee"),a=e("../../core/methods/font/family.coffee"),i=e("../../core/methods/font/transform.coffee"),t.exports={accepted:[Boolean,String],background:{accepted:[!1,String],value:!1},branding:{accepted:[Boolean],image:{dark:"http://d3plus.org/assets/img/icon-transparent-invert.png",light:"http://d3plus.org/assets/img/icon-transparent.png"},value:!1},font:{color:"#444",decoration:r(),family:a(),size:16,transform:i(),weight:200},padding:5,style:{accepted:[!1,"small","large"],value:!1},value:!0}},{"../../core/methods/font/decoration.coffee":85,"../../core/methods/font/family.coffee":86,"../../core/methods/font/transform.coffee":88}],291:[function(e,t,n){t.exports={accepted:[Boolean],click:{accepted:[Boolean,Function],value:!0},move:{accepted:[Boolean,Function],value:!0},out:{accepted:[Boolean,Function],value:!0},over:{accepted:[Boolean,Function],value:!0},value:!0}},{}],292:[function(e,t,n){var r;r=e("../../core/methods/process/data.coffee"),t.exports={accepted:[!1,Array,Function,String],delimiter:{accepted:[String],value:"|"},filetype:{accepted:[!1,"json","xml","html","csv","dsv","tsv","txt"],value:!1},overlap:.6,process:r,value:!1}},{"../../core/methods/process/data.coffee":89}],293:[function(e,t,n){t.exports={accepted:[Boolean,Function,String],agg:{accepted:[!1,Function,"sum","min","max","mean","median"],value:!1},deprecates:["sort"],sort:{accepted:["asc","desc"],value:"desc"},value:!1}},{}],294:[function(e,t,n){t.exports={accepted:[Boolean],value:!1,timeout:400,process:function(e,t){var n,r;return!!e&&(n=null,r=function(){var e,n,r;if(n=t.container.value.node().parentNode.getBoundingClientRect(),r=n.width,e=n.height,t.self.width(r),t.self.height(e),t.width.changed||t.height.changed)return t.self.draw()},d3.select(window).on("resize."+t.container.id,function(e){return function(t){return clearTimeout(n),n=setTimeout(r,e.timeout)}}(this)),e)}}},{}],295:[function(e,t,n){var r;r=e("../../core/methods/rendering.coffee"),t.exports={accepted:function(e){var t;return t=e.types[e.type.value].shapes,!t||t instanceof Array||(t=[t]),t.length?t:["square"]},interpolate:{accepted:["basis","basis-open","cardinal","cardinal-open","linear","monotone","step","step-before","step-after"],deprecates:"stack_type",value:"linear"},rendering:r(),value:!1}},{"../../core/methods/rendering.coffee":94}],296:[function(e,t,n){var r;r=e("../../core/methods/filter.coffee"),t.exports={accepted:[!1,Function,Number,Object,String],dataFilter:!0,deprecates:["value","value_var"],mute:r(!0),scale:{accepted:[Function],deprecates:"size_scale",domain:{min:{accepted:[!1,Number],value:!1},max:{accepted:[!1,Number],value:!1}},range:{max:{accepted:[Function,Number],value:function(e){return Math.floor(d3.max([d3.min([e.width.viz,e.height.viz])/15,6]))}},min:{accepted:[Function,Number],value:3}},value:d3.scale.sqrt()},solo:r(!0),threshold:{accepted:[Boolean,Function,Number],value:!1},value:!1}},{"../../core/methods/filter.coffee":83}],297:[function(e,t,n){t.exports={value:!1}},{}],298:[function(e,t,n){var r;r=e("../../core/methods/filter.coffee"),t.exports={accepted:[!1,Function,Object,String],deprecates:["else_var","else"],mute:r(!0),solo:r(!0),value:!1}},{"../../core/methods/filter.coffee":83}],299:[function(e,t,n){var r;r=e("../../core/methods/filter.coffee"),t.exports={accepted:[Array,Boolean,Function,Object,String],deprecates:["name_array","text_var"],nesting:!0,mute:r(!0),solo:r(!0),value:!1}},{"../../core/methods/filter.coffee":83}],300:[function(e,t,n){var r;r=e("../../core/methods/filter.coffee"),t.exports={accepted:[Array,Boolean,Function,Object,String],dataFilter:!0,deprecates:["year","year_var"],fixed:{accepted:[Boolean],deprecates:["static_axis","static_axes"],value:!0},format:{accepted:[!1,Array,Function,String],value:!1},mute:r(!1),solo:r(!1),value:!1}},{"../../core/methods/filter.coffee":83}],301:[function(e,t,n){t.exports={accepted:[Boolean],align:"middle",hover:{accepted:["all-scroll","col-resize","crosshair","default","grab","grabbing","move","pointer"],value:"pointer"},handles:{accepted:[Boolean],color:"#666",opacity:1,size:3,stroke:"#666",value:!0},height:{accepted:[!1,Number],value:!1},play:{accepted:[Boolean],icon:{accepted:[!1,String],awesome:"",fallback:"►"},pause:{accepted:[!1,String],awesome:"",fallback:"❚❚"},timing:{accepted:[Number],value:1500},value:!0},value:!0}},{}],302:[function(e,t,n){t.exports={mouseevents:60,transitions:600,ui:200}},{}],303:[function(e,t,n){var r,a,i,o;r=e("../../core/methods/font/decoration.coffee"),a=e("../../core/methods/font/family.coffee"),o=e("../../core/methods/font/transform.coffee"),i=e("../../string/strip.js"),t.exports={accepted:[!1,Function,String],font:{align:"center",color:"#444444",decoration:r(),family:a(),size:16,transform:o(),weight:400},height:!1,link:!1,padding:2,position:"top",process:function(e,t){var n;return 0===t.container.id.indexOf("default")&&e&&(n=i(e).toLowerCase(),t.self.container({id:n})),e},sub:{accepted:[!1,Function,String],deprecates:"sub_title",font:{align:"center",color:"#444444",decoration:r(),family:a(),size:12,transform:o(),weight:200},link:!1,padding:1,position:"top",value:!1},total:{accepted:[Boolean,Object],deprecates:"total_bar",font:{align:"center",color:"#444444",decoration:r(),family:a(),size:12,transform:o(),weight:200,value:!1},link:!1,padding:1,position:"top",value:!1},width:!1,value:!1}},{"../../core/methods/font/decoration.coffee":85,"../../core/methods/font/family.coffee":86,"../../core/methods/font/transform.coffee":88,"../../string/strip.js":178}],304:[function(e,t,n){var r,a;r=e("../../core/methods/font/family.coffee"),a=e("../../core/methods/font/transform.coffee"),t.exports={accepted:[Boolean,Array,Function,Object,String],anchor:"top center",background:"#ffffff",children:{accepted:[Boolean,Number],value:!0},connections:{accepted:[Boolean],value:!0},curtain:{color:"#ffffff",opacity:.8},deprecates:"tooltip_info",extent:{accepted:[Boolean],value:!0},font:{color:"#444",family:r(),size:12,transform:a(),weight:200},fullscreen:{accepted:[Boolean],value:!1},html:{accepted:[!1,Function,Object,String],deprecates:"click_function",value:!1},iqr:{accepted:[Boolean],value:!0},large:250,share:{accepted:[Boolean],value:!0},size:{accepted:[Boolean],value:!0},small:225,stacked:{accepted:[Boolean],value:!1},sub:{accepted:[!1,Function,String],value:!1},value:!0}},{"../../core/methods/font/family.coffee":86,"../../core/methods/font/transform.coffee":88}],305:[function(e,t,n){var r;r=e("../../core/methods/filter.coffee"),t.exports={accepted:[!1,Function,Object,String],deprecates:["total_var"],mute:r(!0),solo:r(!0),value:!1}},{"../../core/methods/filter.coffee":83}],306:[function(e,t,n){t.exports={accepted:function(e){return d3.keys(e.types)},mode:{accepted:function(e){return e.types[e.type.value].modes||[!1]},value:!1},value:"tree_map"}},{}],307:[function(e,t,n){var r,a,i,o;i=e("../../core/methods/font/family.coffee"),r=e("../../core/methods/font/align.coffee"),a=e("../../core/methods/font/decoration.coffee"),o=e("../../core/methods/font/transform.coffee"),t.exports={accepted:[Array,Boolean],align:r("center"),border:1,color:{primary:{process:function(e,t){var n;return n=this.value,t.ui.color.secondary.value||(t.ui.color.secondary.value=d3.rgb(n).darker(.75).toString()),e},value:"#ffffff"},secondary:{value:!1}},display:{acceped:["block","inline-block"],value:"inline-block"},font:{align:"center",color:"#444",decoration:a(),family:i(),size:11,transform:o(),weight:200},margin:5,padding:5,position:{accepted:["top","right","bottom","left"],value:"bottom"},value:!1}},{"../../core/methods/font/align.coffee":84,"../../core/methods/font/decoration.coffee":85,"../../core/methods/font/family.coffee":86,"../../core/methods/font/transform.coffee":88}],308:[function(e,t,n){t.exports={accepted:[!1,Number],secondary:!1,small:200,value:!1}},{}],309:[function(e,t,n){t.exports={accepted:[Boolean],behavior:d3.behavior.zoom().scaleExtent([1,1]).duration(0),click:{accepted:[Boolean],value:!0},pan:{accepted:[Boolean],value:!0},scroll:{accepted:[Boolean],deprecates:"scroll_zoom",value:!0},value:!0}},{}],310:[function(e,t,n){var r,a,i,o,l,s,u,c;a=e("../../util/closest.coffee"),i=e("../../core/fetch/value.coffee"),o=e("./helpers/graph/draw.coffee"),l=e("./helpers/graph/nest.coffee"),s=e("../../array/sort.coffee"),u=e("./helpers/graph/stack.coffee"),c=e("../../core/data/threshold.js"),r=function(e){var t,n,r,a,l,c,f,d,p,h,v;if(o(e,{buffer:e.axes.opposite,zero:!0}),a=e.x.domain.viz.concat(e.y.domain.viz),a.indexOf(void 0)>=0)return[];for(n=s(e.data.viz,null,null,null,e),r=e[e.axes.discrete],p=e[e.axes.opposite],l=0,f=n.length;l=0)return[];if(S=e.data.viz,e.axes.stacked)for(x=0,_=S.length;x<_;x++)R=S[x],s(e,R.values);for(V=e.axes[Y]/e[e.axes.discrete].ticks.values.length,D=e[e.axes.discrete].padding.value,D<1&&(D*=V),2*D>V&&(D=.1*V),j=V-2*D,e.axes.stacked||(e[d].persist.position.value?(I=e[d].value,h=c.call(e.id.nesting,I)>=0?d3.max(S,function(e){return e.values.length}):u(S,e.id.value,i,e).length,j/=h,F=V/2-j/2-D,H=d3.scale.ordinal(),1===h?H.domain([0]).range([0]):H.domain([0,h-1]).range([-F,F])):H=d3.scale.linear()),f=[],T=e[P],C=T.scale.viz.domain().slice(),0===P.indexOf("y")&&(C=C.reverse()),C[0]<=0&&C[1]>=0?X=0:C[0]<0?X(d3.max(C)):X=d3.min(C),e[d].persist.position.value&&!e.axes.stacked&&(y=u(d3.merge(S.map(function(e){return e.values})),e.id.value,i,e,e.id.value,!1),H.domain(y),1===y.length?H.range([0]):H.range(a(H.range(),y.length))),A=d3.max(S,function(e){return e.values.length}),b=0,k=S.length;b=0?[]:(r=e.axes.discrete,b=e.axes.opposite,n="x"===r?e.axes.margin.viz.left:e.axes.margin.viz.top,x="x"===b?e.axes.margin.viz.left:e.axes.margin.viz.top,c="x"===r?"height":"width",E="x"===r?"width":"height",A=e.axes[E]/e[r].ticks.values.length,M=e.size.value,M="number"==typeof M?M:100,A=d3.min([A-2*e.labels.padding,M]),m=e.type.mode.value,m instanceof Array||(m=[m,m]),v=function(t){var n,r,i;r={};for(n in e.data.keys)i=s(t,n,a,e),r[n]=1===i.length?i[0]:i;return r},y=!1,p=[],f=e.format.value(e.format.locale.value.ui.iqr),d=e.format.value(e.format.locale.value.ui.max),g=e.format.value(e.format.locale.value.ui.min),w=e.format.value(e.format.locale.value.ui.percentile),t=e.format.value(e.format.locale.value.ui.tukey_bottom),j=e.format.value(e.format.locale.value.ui.tukey_top),_=e.format.value(e.format.locale.value.ui.quartile_first),k=e.format.value(e.format.locale.value.ui.quartile_third),h=e.format.value(e.format.locale.value.ui.median),z=[],d3.nest().key(function(t){return a(e,t,e[r].value)}).rollup(function(i){var u,M,S,O,N,F,C,T,q,P,B,D,R,I,L,V,U,Y,H,X,G,Z,W,J,Q,K,$,ee,te,ne,re,ae;for(Z=e[b].scale.viz,ne=i.map(function(t){return a(e,t,e[b].value)}),ne.sort(function(e,t){return e-t}),ee=s(ne),T=d3.quantile(ne,.25),V=d3.quantile(ne,.5),W=d3.quantile(ne,.75),J={},"tukey"===m[1]?(P=T-W,Q=W-1.5*P,K=j):"extent"===m[1]?(Q=d3.max(ne),K=d):"number"==typeof m[1]&&(Q=d3.quantile(ne,(100-m[1])/100),K=o(w,m[1])),Q=d3.min([d3.max(ne),Q]),e.tooltip.extent.value&&(J[K]={key:e[b].value,value:Q}),e.tooltip.iqr.value&&(J[k]={key:e[b].value,value:W},J[h]={key:e[b].value,value:V},J[_]={key:e[b].value,value:T}),"tukey"===m[0]?(P=T-W,u=T+1.5*P,M=t):"extent"===m[0]?(u=d3.min(ne),M=g):"number"==typeof m[0]&&(u=d3.quantile(ne,m[0]/100),K=o(w,m[0])),u=d3.max([d3.min(ne),u]),e.tooltip.extent.value&&(J[M]={key:e[b].value,value:u}),O=[],S=[],$=[],G=[],q=0,I=i.length;q=T&&te<=W?O.push(N):te>=u&&teW?$.push(N):G.push(N);for(D=a(e,i[0],e[r].value),re=e[r].scale.viz(D),re+=n,R=e.format.value(D,{key:e[r].value,vars:e}),D.constructor===Date&&(D=D.getTime()),D=l(D),O=v(O),O.d3plus={color:"white",id:"box_"+D,init:{},label:!1,shape:"square",stroke:"#444",text:o(f,R)},O.d3plus[E]=A,O.d3plus.init[E]=A,O.d3plus[c]=Math.abs(Z(T)-Z(W)),O.d3plus[r]=re,ae=d3.min([Z(T),Z(W)])+O.d3plus[c]/2,ae+=x,O.d3plus[b]=ae,O.d3plus.tooltip=J,z.push(O),Y={d3plus:{id:"median_line_"+D,position:"height"===c?"top":"right",shape:"whisker",static:!0}},X=e.format.value(V,{key:e[b].value,vars:e}),R={background:"#fff",names:[X],padding:0,resize:!1,x:0,y:0},F=Math.abs(Z(V)-Z(T)),C=Math.abs(Z(V)-Z(W)),H=2*d3.min([F,C]),U=2*e.data.stroke.width+2*e.labels.padding,R["width"===E?"w":"h"]=A-U,R["width"===c?"w":"h"]=H-U,Y.d3plus.label=R,Y.d3plus[E]=A,Y.d3plus[r]=re,Y.d3plus[b]=Z(V)+x,z.push(Y),S=v(S),S.d3plus={id:"bottom_whisker_line_"+D,offset:O.d3plus[c]/2,position:"height"===c?"bottom":"left",shape:"whisker",static:!0},"x"===b&&(S.d3plus.offset*=-1),S.d3plus[c]=Math.abs(Z(u)-Z(T)),S.d3plus[E]=A,S.d3plus[r]=re,S.d3plus[b]=ae,z.push(S),$=v($),$.d3plus={id:"top_whisker_line_"+D,offset:O.d3plus[c]/2,position:"height"===c?"top":"right",shape:"whisker",static:!0},"y"===b&&($.d3plus.offset*=-1),$.d3plus[c]=Math.abs(Z(Q)-Z(W)),$.d3plus[E]=A,$.d3plus[r]=re,$.d3plus[b]=ae,z.push($),B=0,L=G.length;B0)for(;(O-1)*a>=d;)O--;for(n=e.width.viz/a,t=e.height.viz/O,e.size.value?(D=e.size.scale.domain.min.value,B=e.size.scale.domain.max.value,v="number"==typeof D?D:d3.min(e.data.viz,function(t){return l(e,t,e.size.value,e.id.value,"min")}),h="number"==typeof B?B:d3.max(e.data.viz,function(t){return l(e,t,e.size.value,e.id.value)}),p=[v,h]):p=[0,0],E=5,C=d3.min([n,t])/2-2*E,_=e.labels.value&&!e.small&&C>=40?d3.max([20,d3.min([.25*C,50])]):0,C-=_,T=d3.min([C,e.size.scale.range.min.value]),F=e.size.scale.value.domain(p).rangeRound([T,C]),j=d3.layout.pack().children(function(e){return e.values}).padding(E).radius(function(e){return F(e)}).size([n-2*E,t-2*E-_]).value(function(e){return e.value}),f=[],S=0,y=x=0,k=m.length;x3*e.labels.padding?e.labels.padding:0,c.d3plus.label={x:0,y:-(C+L+_/2),w:2*C,h:_-L,padding:0,resize:!0,color:u(i(e,c,c.d3plus.depth)),force:!0});return f.sort(function(e,t){return e.d3plus.depth-t.d3plus.depth})},a.fill=!0,a.requirements=["data"],a.scale=1.05,a.shapes=["circle","donut"],t.exports=a},{"../../array/sort.coffee":36,"../../color/legible.coffee":46,"../../core/data/group.coffee":59,"../../core/fetch/color.coffee":65,"../../core/fetch/text.js":68,"../../core/fetch/value.coffee":69}],314:[function(e,t,n){var r,a;a=e("../../../core/console/print.coffee"),r=function(e){var t,n;n={circle:"scatter",donut:"scatter",line:"line",square:"scatter",area:"stacked"},t=n[e.shape.value],a.warning('The "chart" visualization type has been deprecated and will be removed in version 2.0. Please use the "'+t+'" visualization type.'),e.self.type(t).draw()},r.shapes=["circle","donut","line","square","area"],t.exports=r},{"../../../core/console/print.coffee":54}],315:[function(e,t,n){var r;r=function(e){var t,n,r,a,i,o;return t=e.coords.value,r=e.coords.key||d3.keys(t.objects)[0],o=topojson.feature(t,t.objects[r]),n=o.features,i=e.coords.solo.value,a=e.coords.mute.value,n=n.filter(function(t){return t[e.id.value]=t.id,i.length?i.indexOf(t.id)>=0:!a.length||a.indexOf(t.id)<0})},r.libs=["topojson"],r.nesting=!1,r.requirements=["coords"],r.scale=1,r.shapes=["coordinates"],r.zoom=!0,t.exports=r},{}],316:[function(e,t,n){var r,a,i;r=e("../../../../core/fetch/color.coffee"),a=e("../../../../color/legible.coffee"),i=e("../../../../core/console/print.coffee"),t.exports=function(e){var t,n,o,l,s,u,c,f,d,p,h,v;for(t=e.axes,c=e.axes.margin.viz,l=t.stacked||!t.ticks.value?[]:e.data.viz,v=2*l.length>e.data.large?0:e.draw.timing,d=function(n,i){return 0===i.indexOf("y")?n.attr("x1",-2).attr("x2",-8).attr("y1",function(e){return e.d3plus.y-c.top}).attr("y2",function(e){return e.d3plus.y-c.top}):n.attr("x1",function(e){return e.d3plus.x-c.left}).attr("x2",function(e){return e.d3plus.x-c.left}).attr("y1",t.height+2).attr("y2",t.height+8),n.style("stroke",function(t){return a(r(e,t))}).style("stroke-width",e.data.stroke.width).attr("shape-rendering",e.shape.rendering.value)},e.dev.value&&i.time("creating axis tick groups"),h=e.group.select("g#d3plus_graph_plane").selectAll("g.d3plus_data_tick").data(l,function(n){var r;return r=t.discrete?"_"+n.d3plus[t.discrete]:"","tick_"+n[e.id.value]+"_"+n.d3plus.depth+r}),h.enter().append("g").attr("class","d3plus_data_tick").attr("opacity",0),e.dev.value&&i.timeEnd("creating axis tick groups"),f=["x","y"],s=0,u=f.length;s0?p.transition().duration(v).call(d,n):p.call(d,n),p.enter().append("line").attr("class","d3plus_data_"+n).call(d,n),e.dev.value&&v&&i.timeEnd("styling "+n+" ticks");v>0?(h.transition().duration(v).attr("opacity",1),h.exit().transition().duration(v).attr("opacity",0).remove()):(h.attr("opacity",1),h.exit().remove())}},{"../../../../color/legible.coffee":46,"../../../../core/console/print.coffee":54,"../../../../core/fetch/color.coffee":65}],317:[function(e,t,n){var r,a,i,o;r=e("./includes/axes.coffee"),a=e("./includes/svg.coffee"),i=e("./includes/mouse.coffee"),o=e("./includes/plot.coffee"),t.exports=function(e,t){void 0===t&&(t={}),r(e,t),o(e,t),a(e,t),e.mouse.viz=t.mouse===!0&&i}},{"./includes/axes.coffee":318,"./includes/mouse.coffee":320,"./includes/plot.coffee":321,"./includes/svg.coffee":322}],318:[function(e,t,n){var r,a,i,o,l,s,u,c,f,d,p,h;r=e("../../../../../array/sort.coffee"),o=e("./buffer.coffee"), +i=e("../../../../../util/buckets.coffee"),s=e("../../../../../core/fetch/data.js"),u=e("../../../../../core/fetch/value.coffee"),d=e("../../../../../core/console/print.coffee"),h=e("../../../../../util/uniques.coffee"),t.exports=function(e,t){var n,r,i,s,v,g,m,y,x,b,w,_;for(i=l(e),!i&&e.axes.dataset||(e.axes.dataset=c(e)),e.axes.scale=!(!t.buffer||t.buffer===!0)&&p(e,t.buffer),n=e.width.viz>e.height.viz?["y","y2","x","x2"]:["x","x2","y","y2"],v=0,m=n.length;v0?r:0}),r=d3.sum(n,function(n){var r;return r=u(e,n,e[t].value),r<0?r:0}),[r,a]}).entries(F),q=d3.merge(c.map(function(e){return e.values})),d3.extent(q)}if(e[t].value===e.time.value)return e.time.solo.value.length?d3.extent(e.time.solo.value).map(function(e){return e.constructor!==Date?(e+="",4===e.length&&parseInt(e)+""===e&&(e+="/01/01"),new Date(e)):e}):d3.extent(e.data.time.ticks);for(q=[],j=e.axes.dataset,g=0,b=j.length;g0}),l=q.every(function(e){return e<0}),(s||l)&&(z=s?1:-1,q.push("log"===e[t].scale.value?z:0))),d3.extent(q)},f=function(e,t,n){var r,a,o,l,s;return a=0===t.indexOf("x")?e.width.viz:e.height.viz,l=e[t].scale.value,["discrete","share"].indexOf(l)>=0&&(l="linear"),s=10,"string"==typeof n[0]?(l="ordinal",r=i([0,a],n.length)):(r=[0,a],"linear"===e[t].scale.value&&(s=Math.floor(a/(4*e[t].ticks.font.size)))),e[t].scale.ticks=s,o=d3.scale[l]().domain(n).range(r),"clamp"in o&&o.clamp(!0),o},p=function(e,t){var n,r,a;return t===!0&&(t="size"),t in e&&(t=e[t].value),a=e.size.scale.range.min.value,"function"==typeof a&&(a=a(e)),r=e.size.scale.range.max.value,"function"==typeof r&&(r=r(e)),t===!1?e.size.scale.value.domain([0,1]).rangeRound([r,r]):"number"==typeof t?e.size.scale.value.domain([0,1]).rangeRound([t,t]):t?(e.dev.value&&d.time("calculating buffer scale"),n=d3.extent(e.axes.dataset,function(n){var r;return r=u(e,n,t),r?r:0}),n[0]===n[1]&&(a=r),e.dev.value&&d.timeEnd("calculating buffer scale"),e.size.scale.value.domain(n).rangeRound([a,r])):void 0}},{"../../../../../array/sort.coffee":36,"../../../../../core/console/print.coffee":54,"../../../../../core/fetch/data.js":66,"../../../../../core/fetch/value.coffee":69,"../../../../../util/buckets.coffee":207,"../../../../../util/uniques.coffee":213,"./buffer.coffee":319}],319:[function(e,t,n){var r,a;r=e("../../../../../util/buckets.coffee"),a=e("../../../../../util/closest.coffee"),t.exports=function(e,t,n){var i,o,l,s,u,c,f,d,p,h,v,g,m,y,x,b,w,_,k,z,M,A,j,E,S,O,N,F,C,T,q,P;if("share"!==e[t].scale.value&&!e[t].range.value&&e[t].reset){if(O=e[t].scale.viz.copy(),"clamp"in O&&O.clamp(!1),t===e.axes.discrete){if(h=O.domain(),"string"==typeof h[0]){for(y=h.length;y>=0;)h.splice(y,0,"d3plus_buffer_"+y),y--;return A=O.range(),A=r(d3.extent(A),h.length),e[t].scale.viz.domain(h).range(A)}if(0===t.indexOf("y")&&(h=h.slice().reverse()),1===e[t].ticks.values.length)h=[h[0],h[0]],e[t].value===e.time.value&&1!==e.data.time.ticks.length?(u=a(e.data.time.ticks,h[0]),N=e.data.time.ticks.indexOf(u),N>0?h[0]=e.data.time.ticks[N-1]:(d=e.data.time.ticks[N+1]-u,h[0]=new Date(u.getTime()-d)),N=0;)f=y?M[y-1]+i:M[y]-i,h.splice(y,0,f),y--;A=O.range(),A=r(d3.extent(A),h.length),e[t].scale.viz.domain(h).range(A)}return 0===t.indexOf("y")&&(h=h.reverse()),e[t].scale.viz.domain(h)}if("x"===n&&0===t.indexOf("x")||"y"===n&&0===t.indexOf("y")||n===!0)return h=O.domain(),s=h[0]>=0&&h[1]>=0,l=h[0]<=0&&h[1]<=0,"log"===e[t].scale.value?(P=s?1:-1,s&&0===t.indexOf("y")&&(h=h.slice().reverse()),w=Math.pow(10,parseInt(Math.abs(h[0])).toString().length-1)*P,b=h[0]%w,x=b,b&&x/w<=.1&&(x+=w*P),_=0===b?w:x,h[0]-=_,0===h[0]&&(h[0]=P),T=Math.pow(10,parseInt(Math.abs(h[1])).toString().length-1)*P,C=h[1]%T,F=Math.abs(T-C),C&&F/T<=.1&&(F+=T*P),q=0===C?T:F,h[1]+=q,0===h[1]&&(h[1]=P),s&&0===t.indexOf("y")&&(h=h.reverse())):(P=0,0===t.indexOf("y")&&(h=h.slice().reverse()),S=h.filter(function(e){return e.constructor===String}),o=.05*Math.abs(h[1]-h[0])||1,S.length||(h[0]=h[0]-o,h[1]=h[1]+o,(s&&h[0]P)&&(h[0]=P),(s&&h[1]P)&&(h[1]=P)),0===t.indexOf("y")&&(h=h.reverse())),e[t].scale.viz.domain(h);if(e.axes.scale)return c=!1,e.axes.mirror.value&&(z=0===t.indexOf("y")?"x":"y",c=e[z].scale.viz,E=e.width.viz>e.height.viz?"x":"y"),t===E&&c?h=c.domain().slice().reverse():(j=O.range()[1],k=e.axes.scale.range()[1],m=O.invert(1.5*-k),g=O.invert(j+1.5*k),h=[m,g],0===t.indexOf("y")&&(h=h.reverse()),v=O.domain(),v=v[1]-v[0],v||(h[0]-=1,h[1]+=1),0===t.indexOf("y")&&(h=h.reverse())),e[t].scale.viz.domain(h)}}},{"../../../../../util/buckets.coffee":207,"../../../../../util/closest.coffee":209}],320:[function(e,t,n){var r,a,i,o,l,s;r=e("../../../../../util/copy.coffee"),a=e("../../../../../client/pointer.coffee"),i=e("../../../../../core/fetch/color.coffee"),o=e("../../../../../core/fetch/value.coffee"),l=e("../../../../../color/legible.coffee"),s=e("../../../../../color/text.coffee"),t.exports=function(e,t){var n,r,u,c,f,d,p,h,v,g,m,y,x,b,w,_,k,z,M;return n=d3.event.type===a.click&&(t.tooltip.value.long||t.tooltip.html.value),u=[a.over,a.move].indexOf(d3.event.type)>=0,z=e.d3plus.x,M=e.d3plus.y,m=e.d3plus.r||0,b=t.types[t.type.value].scale||1,m*=b,c=t.axes,g=t.axes.margin.viz,k=t.draw.timing?t.timing.mouseevents:0,!n&&u?(r=l(i(t,e)),f=["x","y","x2","y2"].filter(function(n){var r;return r=o(t,e,t[n].value),r&&!(r instanceof Array)&&n!==t.axes.stacked&&t[n].mouse.value})):f=[],d=function(e){return e.attr("x1",function(e){return 0===e.indexOf("x")?z:z-m}).attr("y1",function(e){return 0===e.indexOf("y")?M:M+m}).attr("x2",function(e){return 0===e.indexOf("x")?z:z-m}).attr("y2",function(e){return 0===e.indexOf("y")?M:M+m}).attr("opacity",0)},p=function(e){return e.style("stroke",function(e){return"area"===t.shape.value?"white":r}).attr("stroke-dasharray",function(e){return t[e].mouse.dasharray.value}).attr("shape-rendering",function(e){return t[e].mouse.rendering.value}).style("stroke-width",function(e){return t[e].mouse.width})},h=function(n){return n.attr("x1",function(e){return 0===e.indexOf("x")?z:z-m}).attr("y1",function(e){return 0===e.indexOf("y")?M:M+m}).attr("x2",function(n){return 0===n.indexOf("x")?z:e.d3plus.x0?e.d3plus.x0:"y"===n?g.left-t[n].ticks.size:g.left+c.width+t[n].ticks.size}).attr("y2",function(n){return 0===n.indexOf("y")?M:e.d3plus.y0?e.d3plus.y0:"x"===n?c.height+g.top+t[n].ticks.size:g.top-t[n].ticks.size}).style("opacity",1)},v=t.g.labels.selectAll("line.d3plus_mouse_axis_label").data(f),k?(v.enter().append("line").attr("class","d3plus_mouse_axis_label").attr("pointer-events","none").call(d).call(p),v.transition().duration(k).call(h).call(p),v.exit().transition().duration(k).call(d).remove()):(v.call(h).call(p),v.enter().append("line").attr("class","d3plus_mouse_axis_label").attr("pointer-events","none").call(d).call(p),v.exit().remove()),w=function(n){return n.attr("font-size",function(e){return t[e].ticks.font.size+"px"}).attr("font-family",function(e){return t[e].ticks.font.family.value}).attr("font-weight",function(e){return t[e].ticks.font.weight}).attr("x",function(e){return 0===e.indexOf("x")?z:"y"===e?g.left-5-t[e].ticks.size:g.left+c.width+5+t[e].ticks.size}).attr("y",function(n){return 0===n.indexOf("y")?M:e.d3plus.y0?e.d3plus.y+(e.d3plus.y0-e.d3plus.y)/2+g.top-6:"x"===n?c.height+g.top+5+t[n].ticks.size:g.top-5-t[n].ticks.size-1.35*t[n].ticks.font.size}).attr("fill","area"===t.shape.value?"white":s(r))},_=t.g.labels.selectAll("text.d3plus_mouse_axis_label").data(f),_.enter().append("text").attr("class","d3plus_mouse_axis_label").attr("id",function(e){return e+"_d3plusmouseaxislabel"}).attr("dy",function(e){return 0===e.indexOf("y")?.35*t[e].ticks.font.size:t[e].ticks.font.size}).style("text-anchor",function(e){return"y"===e?"end":"y2"===e?"start":"middle"}).attr("opacity",0).attr("pointer-events","none").call(w),_.text(function(n){var r,a;return r=t.axes.stacked||n,a=o(t,e,t[r].value),t.format.value(a,{key:t[r].value,vars:t,labels:t[r].affixes.value})}),k?(_.transition().duration(k).delay(k).attr("opacity",1).call(w),_.exit().transition().duration(k).attr("opacity",0).remove()):(_.attr("opacity",1).call(w),_.exit().remove()),y=function(n){var a;return a=function(e){var t;return t=d3.select("text#"+e+"_d3plusmouseaxislabel"),t.size()?t.node().getBBox():{width:0,height:0}},n.attr("x",function(e){var n;return n=a(e).width,0===e.indexOf("x")?z-n/2-5:"y"===e?g.left-t[e].ticks.size-n-10:g.left+c.width+t[e].ticks.size}).attr("y",function(n){var r;return r=a(n).height,0===n.indexOf("y")?M-(r/2+5):e.d3plus.y0?e.d3plus.y+(e.d3plus.y0-e.d3plus.y)/2+g.top-(r/2+5):"x"===n?c.height+g.top+t[n].ticks.size:g.top-t[n].ticks.size-r-10}).attr("width",function(e){return a(e).width+10}).attr("height",function(e){return a(e).height+10}).style("stroke","area"===t.shape.value?"transparent":r).attr("fill",r).attr("shape-rendering",function(e){return t[e].mouse.rendering.value}).style("stroke-width",function(e){return t[e].mouse.width})},x=t.g.labels.selectAll("rect.d3plus_mouse_axis_label").data(f),k?(x.enter().insert("rect","text.d3plus_mouse_axis_label").attr("class","d3plus_mouse_axis_label").attr("pointer-events","none").attr("opacity",0).call(y),x.transition().duration(k).delay(k).attr("opacity",1).call(y),x.exit().transition().duration(k).attr("opacity",0).remove()):(x.attr("opacity",1).call(y),x.enter().insert("rect","text.d3plus_mouse_axis_label").attr("class","d3plus_mouse_axis_label").attr("pointer-events","none").call(y),x.exit().remove())}},{"../../../../../client/pointer.coffee":40,"../../../../../color/legible.coffee":46,"../../../../../color/text.coffee":52,"../../../../../core/fetch/color.coffee":65,"../../../../../core/fetch/value.coffee":69,"../../../../../util/copy.coffee":210}],321:[function(e,t,n){var r,a,i,o,l,s,u,c,f,d,p;r=e("../../../../../util/buckets.coffee"),a=e("./buffer.coffee"),o=e("../../../../../core/fetch/value.coffee"),l=e("../../../../../font/sizes.coffee"),f=e("../../../../../textwrap/textwrap.coffee"),d=e("../../../../../core/data/time.coffee"),p=e("../../../../../util/uniques.coffee"),t.exports=function(e,t){var n,r,l,s,c,f,p,h,v,g,m,y,x,b,w,_,k,z,M,A;for(e.axes.margin.viz={top:e.axes.margin.top,right:e.axes.margin.right,bottom:e.axes.margin.bottom,left:e.axes.margin.left},e.axes.height=e.height.viz,e.axes.width=e.width.viz,n=e.width.viz>e.height.viz?["y","y2","x","x2"]:["x","x2","y","y2"],c=0,h=n.length;c4?e:(e+="",4===e.length&&parseInt(e)+""===e&&(e+="/01/01"),new Date(e).getTime())}))}if(e.small)for(e.axes.width-=e.axes.margin.viz.left+e.axes.margin.viz.right,e.axes.height-=e.axes.margin.viz.top+e.axes.margin.viz.bottom,f=0,v=n.length;fk&&M.join("").indexOf(" ")>0?(e[t].ticks.wrap=!0,z=l(M,m,{mod:function(t){return f().container(d3.select(t)).height(e.axes.height/2).width(k).draw()}}),x=d3.max(z,function(e){return e.width}),y=d3.max(z,function(e){return e.height})):e[t].ticks.wrap=!1,e[t].ticks.baseline="auto",x<=k?e[t].ticks.rotate=0:xe.width.value&&(v=h-e.width.value+e.axes.margin.viz.right,e.axes.width-=v,e.axes.margin.viz.right+=v)):e[t].ticks.hidden=!0,w=e[t].label.fetch(e),w?(_={"font-family":e[t].label.font.family.value,"font-weight":e[t].label.font.weight,"font-size":e[t].label.font.size+"px","text-transform":e[t].label.font.transform.value,"letter-spacing":e[t].label.font.spacing+"px"},e[t].label.height=l([w],_)[0].height):e[t].label.height=0,e[t].label.value&&(e.axes.margin.viz[c]+=e[t].label.height,e.axes.margin.viz[c]+=2*e[t].label.padding));if(e.axes.height-=e.axes.margin.viz.top+e.axes.margin.viz.bottom,e.x.scale.viz.range(r([0,e.axes.width],b.length)),g&&e.x2.scale.viz.range(r([0,e.axes.width],g.length)),e.y.scale.viz.range(r([0,e.axes.height],O.length)),j)return e.y2.scale.viz.range(r([0,e.axes.height],j.length))},i=function(e,t){return d3.svg.axis().tickSize(e[t].ticks.size).tickPadding(5).orient(e[t].orient.value).scale(e[t].scale.viz).tickValues(e[t].ticks.values).tickFormat(function(n,r){var a,i;return e[t].ticks.hidden?null:(i=e[t].scale.value,a=n.constructor===Date?+n:n,e[t].ticks.visible.indexOf(a)>=0?"share"===i?e.format.value(100*n,{key:"share",vars:e,labels:e[t].affixes.value,output:t}):n.constructor===Date?e[t].ticks.format(n):"log"===i?s(n):e.format.value(n,{key:e[t].value,vars:e,labels:e[t].affixes.value,output:t}):null)})},c="⁰¹²³⁴⁵⁶⁷⁸⁹",s=function(e){var t,n,r;return n=Math.round(Math.log(Math.abs(e))/Math.LN10),r=Math.abs(e).toString().charAt(0),t="10 "+(n+"").split("").map(function(e){return c[e]}).join(""),"1"!==r&&(t=r+" x "+t),e<0?"-"+t:t}},{"../../../../../core/data/time.coffee":64,"../../../../../core/fetch/value.coffee":69,"../../../../../font/sizes.coffee":104,"../../../../../textwrap/textwrap.coffee":203,"../../../../../util/buckets.coffee":207,"../../../../../util/uniques.coffee":213,"./buffer.coffee":319}],322:[function(e,t,n){var r,a,i;r=e("../../../../../color/mix.coffee"),a=e("../../../../../textwrap/textwrap.coffee"),i=e("../../../../../object/validate.coffee"),t.exports=function(e){var t,n,o,l,s,u,c,f,d,p,h,v,g,m,y,x,b,w,_,k,z,M,A,j,E,S,O,N,F,C,T,q,P,B,D,R,I,L,V,U,Y,H,X,G,Z,W,J,Q,K,$,ee,te,ne,re,ae,ie,oe,le,se,ue,ce;if(h=e.x.domain.viz.concat(e.y.domain.viz),h.indexOf(void 0)>=0)return null;for(f={width:e.axes.width,height:e.axes.height,fill:e.axes.background.color,stroke:e.axes.background.stroke.color,"stroke-width":e.axes.background.stroke.width,"shape-rendering":e.axes.background.rendering.value},n={left:"start",center:"middle",right:"end"},l=e.small?[]:[0],ie=function(t,n){return t.attr("x1",function(t){return 0===n.indexOf("x")?e.x.scale.viz(t):0}).attr("x2",function(t){return 0===n.indexOf("x")?e.x.scale.viz(t):e.axes.width}).attr("y1",function(t){return 0===n.indexOf("y")?e.y.scale.viz(t):0}).attr("y2",function(t){return 0===n.indexOf("y")?e.y.scale.viz(t):e.axes.height})},oe=function(t,n,a){var i,o,l;return i=a?e[n].grid.color:e[n].ticks.color,o="log"===e[n].scale.value,l=e[n].ticks.visible||[],t.attr("stroke",function(t){var s;return 0===t?e[n].axis.color:(t.constructor===Date&&(t=+t),s=l.indexOf(t)>=0,!s||o&&"1"!==Math.abs(t).toString().charAt(0)?a&&"transparent"!==e.axes.background.color?r(i,e.axes.background.color,.4,1):"transparent"!==e.background.value?r(i,e.background.value,.4,1):r(i,"white",.4,1):i)}).attr("stroke-width",e[n].ticks.width).attr("shape-rendering",e[n].ticks.rendering.value)},v=function(t,n,r){var a;return a=0===n?"axis":"ticks",n=e[t][a].font[r],n&&(n.length||"number"==typeof n)?n:e[t].ticks.font[r]},ae=function(t,n){var a;return a="log"===e[n].scale.value,t.attr("font-size",function(e){return v(n,e,"size")+"px"}).attr("stroke","none").attr("fill",function(t){var i;return i=v(n,t,"color"),a&&"1"!==Math.abs(t).toString().charAt(0)?r(i,e.background.value,.4,1):i}).attr("font-family",function(e){return v(n,e,"family").value}).attr("font-weight",function(e){return v(n,e,"weight")}).style("text-transform",function(e){return v(n,e,"transform").value}).style("letter-spacing",function(e){return v(n,e,"spacing")+"px"})},q=function(t,n){var r,a;return r=0===n.indexOf("x")?"height":"width",a=0===n.indexOf("x")?"y":"x",t.attr(a+"1",0).attr(a+"2",e.axes[r]).attr(n+"1",function(e){return e.coords.line}).attr(n+"2",function(e){return e.coords.line}).attr("stroke",function(t){return t.color||e[n].lines.color}).attr("stroke-width",e[n].lines.width).attr("shape-rendering",e[n].lines.rendering.value).attr("stroke-dasharray",e[n].lines.dasharray.value)},F=function(t,r){var a;return a=0===r.indexOf("x")?"y":"x",t.attr(a,function(e){return e.coords.text[a]+"px"}).attr(r,function(e){return e.coords.text[r]+"px"}).attr("dy",e[r].lines.font.position.value).attr("text-anchor",n[e[r].lines.font.align.value]).attr("transform",function(e){return e.transform}).attr("font-size",e[r].lines.font.size+"px").attr("fill",function(t){return t.color||e[r].lines.color}).attr("font-family",e[r].lines.font.family.value).attr("font-weight",e[r].lines.font.weight)},U="translate("+e.axes.margin.viz.left+","+e.axes.margin.viz.top+")",V=e.group.selectAll("g#d3plus_graph_plane").data([0]),V.transition().duration(e.draw.timing).attr("transform",U),V.enter().append("g").attr("id","d3plus_graph_plane").attr("transform",U),c=V.selectAll("rect#d3plus_graph_background").data([0]),c.transition().duration(e.draw.timing).attr(f),c.enter().append("rect").attr("id","d3plus_graph_background").attr("x",0).attr("y",0).attr(f),R=V.selectAll("path#d3plus_graph_mirror").data([0]),R.enter().append("path").attr("id","d3plus_graph_mirror").attr("fill","#000").attr("fill-opacity",.03).attr("stroke-width",1).attr("stroke","#ccc").attr("stroke-dasharray","10,10").attr("opacity",0),R.transition().duration(e.draw.timing).attr("opacity",function(){return e.axes.mirror.value?1:0}).attr("d",function(){var e,t;return t=f.width,e=f.height,"M "+t+" "+e+" L 0 "+e+" L "+t+" 0 Z"}),K=0!==e.x.ticks.rotate,ue=function(t,n){var r,i;return i="x"===n?e.axes.height:0,r=t.attr("transform","translate(0,"+i+")").call(e[n].axis.svg.scale(e[n].scale.viz)).selectAll("g.tick"),r.selectAll("line").attr("y2",function(t){var r;return t.constructor===Date&&(t=+t),r=d3.select(this).attr("y2"),e[n].ticks.visible.indexOf(t)>=0?r:r/2}),r.select("text").style("text-anchor",K&&"x"===n?"end":K?"start":"middle").call(ae,n).each(function(t){if(d3.select(this).attr("dy","0px").attr("font-size",function(e){return v(n,e,"size")+"px"}),t.constructor===Date&&(t=+t),!e[n].ticks.hidden&&e[n].ticks.visible.indexOf(t)>=0)return a().container(d3.select(this)).rotate(e[n].ticks.rotate).align(K?"end":"center").valign(K?"middle":"x"===n?"top":"bottom").width(e[n].ticks.maxWidth+2).height(e[n].ticks.maxHeight).padding(0).x(-e[n].ticks.maxWidth/2).y("x2"===n?-(e[n].ticks.maxHeight+2*e.labels.padding):0).draw()})},ce=function(t,n){var r,a;return a="y2"===n?e.axes.width:0,r=t.attr("transform","translate("+a+", 0)").call(e[n].axis.svg.scale(e[n].scale.viz)).selectAll("g.tick"),r.selectAll("line").attr("y2",function(t){var n;return t.constructor===Date&&(t=+t),n=d3.select(this).attr("y2"),e.x.ticks.visible.indexOf(t)>=0?n:n/2}),r.select("text").call(ae,n)},Z=["x","x2","y","y2"],x=0,M=Z.length;x=0&&e[L].axis.value&&(m=[0])),e[o].value===e.time.value&&(m=m.map(function(e){return e+="",4===e.length&&parseInt(e)+""===e&&(e+="/01/01"),new Date(e).getTime()})),g=V.selectAll("g#d3plus_graph_"+o+"grid").data([0]),g.enter().append("g").attr("id","d3plus_graph_"+o+"grid"),P=g.selectAll("line").data(m,function(e,t){return e.constructor===Date?e.getTime():e}),P.transition().duration(e.draw.timing).call(ie,o).call(oe,o,!0),P.enter().append("line").style("opacity",0).call(ie,o).call(oe,o,!0).transition().duration(e.draw.timing).delay(e.draw.timing/2).style("opacity",1),P.exit().transition().duration(e.draw.timing/2).style("opacity",0).remove();for(J=["x","x2","y","y2"],w=0,j=J.length;w=0:d>=p[0]&&d<=p[1],se&&(d=i(O)?O:{position:d},d.coords={line:e[o].scale.viz(d.position)},N.push(d),d.text&&(d.axis=o,d.padding=.5*e[o].lines.font.padding.value,d.align=e[o].lines.font.align.value,Y=e[o].lines.font.position.text,ne="middle"===Y?0:2*d.padding,"top"===Y&&(ne=-ne),0===o.indexOf("x")?(re="left"===d.align?e.axes.height:"center"===d.align?e.axes.height/2:0,"left"===d.align&&(re-=2*d.padding),"right"===d.align&&(re+=2*d.padding)):(re="left"===d.align?0:"center"===d.align?e.axes.width/2:e.axes.width,"right"===d.align&&(re-=2*d.padding),"left"===d.align&&(re+=2*d.padding)),d.coords.text={},d.coords.text[0===o.indexOf("x")?"y":"x"]=re,d.coords.text[o]=e[o].scale.viz(d.position)+ne,d.transform=0===o.indexOf("x")?"rotate(-90,"+d.coords.text.x+","+d.coords.text.y+")":null,te.push(d)));P=C.selectAll("line.d3plus_graph_"+o+"line").data(N,function(e){return e.position}),P.enter().append("line").attr("class","d3plus_graph_"+o+"line").attr("opacity",0).call(q,o),P.transition().duration(e.draw.timing).attr("opacity",1).call(q,o),P.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),B=C.selectAll("text.d3plus_graph_"+o+"line_text").data(te,function(e){return e.position}),B.enter().append("text").attr("class","d3plus_graph_"+o+"line_text").attr("id",function(e){var t;return t=e.position+"",t=t.replace("-","neg"),t=t.replace(".","p"),"d3plus_graph_"+o+"line_text_"+t}).attr("opacity",0).call(F,o),B.text(function(e){return e.text}).transition().duration(e.draw.timing).attr("opacity",1).call(F,o),B.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),G=function(t){var n;return n=function(e){var t;return t=e.position+"",t=t.replace("-","neg"),t=t.replace(".","p"),V.select("text#d3plus_graph_"+e.axis+"line_text_"+t).node().getBBox()},t.attr("x",function(e){return n(e).x-e.padding}).attr("y",function(e){return n(e).y-e.padding}).attr("transform",function(e){return e.transform; +}).attr("width",function(e){return n(e).width+2*e.padding}).attr("height",function(e){return n(e).height+2*e.padding}).attr("fill","transparent"!==e.axes.background.color?e.axes.background.color:"white")},X=e[o].lines.font.background.value?te:[],T=C.selectAll("rect.d3plus_graph_"+o+"line_rect").data(X,function(e){return e.position}),T.enter().insert("rect","text.d3plus_graph_"+o+"line_text").attr("class","d3plus_graph_"+o+"line_rect").attr("pointer-events","none").attr("opacity",0).call(G),T.transition().delay(e.draw.timing).each("end",function(t){return d3.select(this).transition().duration(e.draw.timing).attr("opacity",1).call(G)}),T.exit().transition().duration(e.draw.timing).attr("opacity",0).remove()}}},{"../../../../../color/mix.coffee":48,"../../../../../object/validate.coffee":175,"../../../../../textwrap/textwrap.coffee":203}],323:[function(e,t,n){var r,a,i;r=e("../../../../core/fetch/value.coffee"),a=e("../../../../string/strip.js"),i=e("../../../../util/uniques.coffee"),t.exports=function(e,t,n){var o,l,s,u,c,f,d;return void 0===n?n=e.id.nesting.slice(0,e.depth.value+1):n.constructor!==Array&&(n=[n]),void 0===l&&(l=[]),t||(t=e.data.viz),o=e[e.axes.discrete],u=e[e.axes.opposite],d=o.value===e.time.value,d?(f=e.data.time.ticks,s=e.time.solo.value.length?"solo":"mute",e.time[s].value.length&&(c=e.time[s].value.slice().map(function(e){return e.constructor!==Date&&(e+="",4===e.length&&parseInt(e)+""===e&&(e+="/01/01"),e=new Date(e)),+e}),f=f.filter(function(e){return"solo"===s?c.indexOf(+e)>=0:c.indexOf(+e)<0}))):f=o.ticks.values?o.ticks.values:i(t,o.value,r,e),d3.nest().key(function(t){var i,o,l,s,u;for(s="nesting",o=0,l=n.length;o=0){c=!1;break}c?f.push(n):h.push(n)}else x>=0&&h.push(n),x<0&&f.push(n);return 0===h.length||0===f.length?g(t):(h.length&&(h=g(h)),f.length&&(f=g(f)),h.concat(f))}},{"../../../../core/fetch/value.coffee":69}],325:[function(e,t,n){var r,a,i,o,l,s;r=e("../../core/fetch/value.coffee"),a=e("./helpers/graph/draw.coffee"),o=e("./helpers/graph/nest.coffee"),l=e("../../array/sort.coffee"),s=e("./helpers/graph/stack.coffee"),i=function(e){var t,n,i,o,u,c,f,d,p,h,v;if(a(e,{buffer:e.axes.opposite,mouse:!0}),i=e.x.domain.viz.concat(e.y.domain.viz),i.indexOf(void 0)>=0)return[];for(n=l(e.data.viz,null,null,null,e),o=0,c=n.length;oh)var g=e.height.viz/p;else var g=e.width.viz/d;var u=.25*s;u*g<2&&(u=2/g)}}var m=e.size.scale.value.domain(l).range([u,s]);e.zoom.bounds=[[i[0]-1.1*s,o[0]-1.1*s],[i[1]+1.1*s,o[1]+1.1*s]];var y=[],x={};return t.forEach(function(t){var n=e.data.viz.filter(function(n){return n[e.id.value]==t[e.id.value]})[0],r=n||{};r[e.id.value]=t[e.id.value],r.d3plus={},r.d3plus.x=t.x,r.d3plus.y=t.y;var i=a(e,r,e.size.value);r.d3plus.r=i?m(i):m.range()[0],x[r[e.id.value]]={x:r.d3plus.x,y:r.d3plus.y,r:r.d3plus.r},y.push(r)}),y.sort(function(e,t){return t.d3plus.r-e.d3plus.r}),n.forEach(function(t,n){t.d3plus&&delete t.d3plus.spline,t[e.edges.source].d3plus={};var r=x[t[e.edges.source][e.id.value]];void 0!==r?(t[e.edges.source].d3plus.r=r.r,t[e.edges.source].d3plus.x=r.x,t[e.edges.source].d3plus.y=r.y):delete t[e.edges.source].d3plus,t[e.edges.target].d3plus={};var a=x[t[e.edges.target][e.id.value]];void 0!==a?(t[e.edges.target].d3plus.r=a.r,t[e.edges.target].d3plus.x=a.x,t[e.edges.target].d3plus.y=a.y):delete t[e.edges.target].d3plus}),{nodes:y,edges:n}};i.nesting=!1,i.requirements=["nodes","edges"],i.scale=1.05,i.shapes=["circle","square","donut"],i.tooltip="static",i.zoom=!0,t.exports=i},{"../../core/fetch/value.coffee":69,"../../network/smallestGap.coffee":171}],327:[function(e,t,n){var r,a,i,o,l=[].indexOf||function(e){for(var t=0,n=this.length;t=0&&(Z=u),l.call(s,P)>=0&&(R=u);null!==Z&&null===R?Z+1===X.all.length-1?X.all.splice(Z+1,0,[g]):X.all[Z+1].push(g):R-Z===1?X.all.splice(R,0,[g]):R-Z>1&&X.all[R-1].push(g)}ie+=q}for(ae=Math.floor(e.height.viz/ie),de=[],v=0;v=0&&(I.d3plus.x=ue(u));I.d3plus.y=fe(H[I[e.id.value]]),e.size.value?(se=r(e,I,e.size.value),I.d3plus.r=se?oe(se):C):I.d3plus.r=F,I.d3plus.r<.1*c&&!e.small?I.d3plus.label={x:0,y:I.d3plus.r+2*e.labels.padding,w:.6*c,h:b+F-I.d3plus.r,resize:!1}:delete I.d3plus.label}for(ne=o.paths,Y=V=0,S=ne.length;V1?r(t.d3plus,n.d3plus,e.id.nesting.concat([e.size.value]),void 0,[],e):r(t.d3plus,n.d3plus,[e.size.value],"desc",[],e)}),n=i(e,e.data.viz,[]),s=u(n),f=[],c=d3.min([e.width.viz,e.height.viz])/2-2*e.labels.padding,a=0,l=s.length;a=20){z=w;break}for(Q=r([L/z,L],z-1).reverse(),Q.length===z&&Q.shift(),$=e.group.selectAll(".d3plus_radar_rings").data(Q,function(e,t){return t}),K=function(t){return t.attr("fill",function(t,n){return 0===n?e.axes.background.color:"transparent"}).attr("cx",e.width.viz/2+e.margin.top).attr("cy",e.height.viz/2+e.margin.left).attr("stroke",e.x.grid.value?e.x.grid.color:"transparent")},$.enter().append("circle").attr("class","d3plus_radar_rings").call(K).attr("r",0),$.transition().duration(e.draw.timing).call(K).attr("r",function(e){return e}),$.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),N=d3.scale.ordinal().domain(T).range(d3.range(0,T.length)),E=[],V=0,D=T.length;V90?(t-=180,c=-(L+2*e.labels.padding+C),a="end"):(c=L+2*e.labels.padding,a="start"),ae=n<0||n>Math.PI,J=n=0,h&&(oe-=C/2),E.push({text:j,angle:t,x:c,anchor:a,offset:H});return S=e.group.selectAll("g.d3plus_radar_label_group").data([0]),S.enter().append("g").attr("class","d3plus_radar_label_group").attr("transform","translate("+e.width.viz/2+","+e.height.viz/2+")"),S.transition().duration(e.draw.timing).attr("transform","translate("+e.width.viz/2+","+e.height.viz/2+")"),ne=S.selectAll(".d3plus_radar_labels").data(e.labels.value?E:[],function(e,t){return t}),F=function(e){return e.attr(re).each(function(e,t){return d().container(d3.select(this)).height(O).width(C).align(e.anchor).text(e.text).padding(0).valign("middle").x(e.x).y(-O/2).draw()}).attr("transform",function(e){var t;return t=d3.select(this).attr("transform")||"",t.length&&(t=t.split(")").slice(-3).join(")")),"rotate("+e.angle+")"+t})},ne.call(F),ne.enter().append("text").attr("class","d3plus_radar_labels").attr("opacity",0).call(F).transition().duration(e.draw.timing).attr("opacity",1),ne.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),x=e.group.selectAll(".d3plus_radar_lines").data(E,function(e,t){return t}),b=function(t){return t.attr("stroke",e.x.grid.color).attr("x1",e.width.viz/2+e.margin.left).attr("y1",e.height.viz/2+e.margin.top)},x.enter().append("line").attr("class","d3plus_radar_lines").call(b).attr("x2",e.width.viz/2+e.margin.left).attr("y2",e.height.viz/2+e.margin.top),x.transition().duration(e.draw.timing).call(b).attr("x2",function(t){return e.width.viz/2+e.margin.left+t.offset.x}).attr("y2",function(t){return e.height.viz/2+e.margin.top+t.offset.y}),x.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),e.mouse.viz={click:!1},m},c.requirements=["data","size"],c.shapes=["radial"],t.exports=c},{"../../array/comparator.coffee":34,"../../array/sort.coffee":36,"../../core/data/threshold.js":63,"../../core/fetch/text.js":68,"../../core/fetch/value.coffee":69,"../../font/sizes.coffee":104,"../../geom/offset.coffee":163,"../../textwrap/textwrap.coffee":203,"../../util/buckets.coffee":207,"../../util/uniques.coffee":213}],330:[function(e,t,n){var r=e("../../array/sort.coffee"),i=e("../../client/pointer.coffee"),o=e("../../core/fetch/value.coffee"),l=e("../../core/fetch/color.coffee"),s=e("../../color/legible.coffee"),u=e("../../tooltip/remove.coffee"),c=e("../../network/smallestGap.coffee"),f=e("../../color/text.coffee"),d=e("../../util/uniques.coffee"),p=function(e){var t=d3.min([e.height.viz,e.width.viz])/2,n=e.small||!e.labels.value?(t-2*e.labels.padding)/2:t/3,p=e.small||!e.labels.value?1.4*n:n,h=2*n,v=[],g=[],m=e.data.viz.filter(function(t){return t[e.id.value]===e.focus.value[0]})[0];m||(m={d3plus:{}},m[e.id.value]=e.focus.value[0]),m.d3plus.x=e.width.viz/2,m.d3plus.y=e.height.viz/2,m.d3plus.r=.65*p;var y=[],x=[e.focus.value[0]];e.edges.connections(e.focus.value[0],e.id.value).forEach(function(t){var n=t[e.edges.source][e.id.value]==e.focus.value[0]?t[e.edges.target]:t[e.edges.source],r=e.data.viz.filter(function(t){return t[e.id.value]===n[e.id.value]})[0];r||(r={d3plus:{}},r[e.id.value]=n[e.id.value]),r.d3plus.edges=e.edges.connections(r[e.id.value],e.id.value).filter(function(t){return t[e.edges.source][e.id.value]!=e.focus.value[0]&&t[e.edges.target][e.id.value]!=e.focus.value[0]}),r.d3plus.edge=t,x.push(r[e.id.value]),y.push(r)});var b=e.order.value||e.color.value||e.size.value||e.id.value;y.sort(function(t,n){var a=t.d3plus.edges.length-n.d3plus.edges.length;return a?a:r([t,n],b,e.order.sort.value,e.color.value||[],e)}),"number"==typeof e.edges.limit.value?y=y.slice(0,e.edges.limit.value):"function"==typeof e.edges.limit.value&&(y=e.edges.limit.value(y));var w=[],_=0;y.forEach(function(t){var n=t[e.id.value];t.d3plus.edges=t.d3plus.edges.filter(function(t){var r=t[e.edges.source][e.id.value],a=t[e.edges.target][e.id.value];return x.indexOf(r)<0&&a==n||x.indexOf(a)<0&&r==n}),_+=t.d3plus.edges.length||1,t.d3plus.edges.forEach(function(t){var r=t[e.edges.source],a=t[e.edges.target],i=a[e.id.value]==n?r:a;x.push(i[e.id.value])})}),r(y,b,e.order.sort.value,e.color.value||[],e);var k=0,z=2*Math.PI,M=0;y.forEach(function(t,n){var i=t.d3plus.edges.length||1,o=z/_*i;0==n&&(M=l,k-=o/2);var l=k+o/2;l-=z/4,t.d3plus.radians=l,t.d3plus.x=e.width.viz/2+p*Math.cos(l),t.d3plus.y=e.height.viz/2+p*Math.sin(l),k+=o,t.d3plus.edges.sort(function(n,a){var n=n[e.edges.source][e.id.value]==t[e.id.value]?n[e.edges.target]:n[e.edges.source],a=a[e.edges.source][e.id.value]==t[e.id.value]?a[e.edges.target]:a[e.edges.source];return r([n,a],b,e.order.sort.value,e.color.value||[],e)}),t.d3plus.edges.forEach(function(n,r){var o=n[e.edges.source][e.id.value]==t[e.id.value]?n[e.edges.target]:n[e.edges.source],s=z/_,u=e.data.viz.filter(function(t){return t[e.id.value]===o[e.id.value]})[0];u||(u={d3plus:{}},u[e.id.value]=o[e.id.value]),a=l-s*i/2+s/2+s*r,u.d3plus.radians=a,u.d3plus.x=e.width.viz/2+h*Math.cos(a),u.d3plus.y=e.height.viz/2+h*Math.sin(a),w.push(u)})});var A=c(y,{accessor:function(e){return[e.d3plus.x,e.d3plus.y]}}),j=c(w,{accessor:function(e){return[e.d3plus.x,e.d3plus.y]}});if(A||(A=n/2),j||(j=n/4),A/2-4<8)var E=d3.min([A/2,8]);else var E=A/2-4;if(j/2-4<4)var S=d3.min([j/2,4]);else var S=j/2-4;S>n/10&&(S=n/10),S>E&&S>10&&(S=.75*E),E>1.5*S&&(E=1.5*S),E=Math.floor(E),S=Math.floor(S);var O=d(y,e.id.value,o,e);O=O.concat(d(w,e.id.value,o,e)),O.push(e.focus.value[0]);var N=e.data.viz.filter(function(t){return O.indexOf(t[e.id.value])>=0});if(e.size.value){var F=d3.extent(N,function(t){return o(e,t,e.size.value)});F[0]==F[1]&&(F[0]=0);var t=d3.scale.linear().domain(F).rangeRound([3,d3.min([E,S])]),C=o(e,m,e.size.value);m.d3plus.r=t(C)}else{var t=d3.scale.linear().domain([1,2]).rangeRound([E,S]);e.edges.label&&(m.d3plus.r=1.5*t(1))}w.forEach(function(n){n.d3plus.ring=2;var r=e.size.value?o(e,n,e.size.value):2;n.d3plus.r=t(r)}),y.forEach(function(n){n.d3plus.ring=1;var r=e.size.value?o(e,n,e.size.value):1;n.d3plus.r=t(r)}),g=[m].concat(y).concat(w),y.forEach(function(t,r){var a=[e.edges.source,e.edges.target],i=t.d3plus.edge;a.forEach(function(t){i[t]=g.filter(function(n){return n[e.id.value]==i[t][e.id.value]})[0]}),delete i.d3plus,v.push(i),e.edges.connections(t[e.id.value],e.id.value).forEach(function(r){var a=r[e.edges.source][e.id.value]==t[e.id.value]?r[e.edges.target]:r[e.edges.source];if(a[e.id.value]!=m[e.id.value]){var i=w.filter(function(t){return t[e.id.value]==a[e.id.value]})[0];if(i);else{i=y.filter(function(t){return t[e.id.value]==a[e.id.value]})[0]}if(i){r.d3plus={spline:!0,translate:{x:e.width.viz/2,y:e.height.viz/2}};var o=[e.edges.source,e.edges.target];o.forEach(function(a,o){r[a]=g.filter(function(t){return t[e.id.value]==r[a][e.id.value]})[0],void 0===r[a].d3plus.edges&&(r[a].d3plus.edges={});var l=0===o?r[e.edges.target][e.id.value]:r[e.edges.source][e.id.value];r[a][e.id.value]==t[e.id.value]?r[a].d3plus.edges[l]={angle:t.d3plus.radians+Math.PI,radius:n/2}:r[a].d3plus.edges[l]={angle:i.d3plus.radians,radius:n/2}}),v.push(r)}}})});var T=!1;return e.background.value&&["transparent","none"].indexOf(e.background.value)<0&&d3.hsl(e.background.value).l<.5&&(T=f(e.background.value)),g.forEach(function(t){if(!e.small&&e.labels.value)if(t[e.id.value]!=e.focus.value[0]){t.d3plus.rotate=t.d3plus.radians*(180/Math.PI);var r=t.d3plus.rotate,a=n-3*e.labels.padding-t.d3plus.r;if(r<-90||r>90){r-=180;var i=-(t.d3plus.r+a/2+e.labels.padding),o="end"}else var i=t.d3plus.r+a/2+e.labels.padding,o="start";var u=y.indexOf(t)>=0,c=1==t.d3plus.ring?A:j;t.d3plus.label={x:i,y:0,w:a,h:c,angle:r,anchor:o,valign:"center",color:T||s(l(e,t)),resize:[8,e.labels.font.size],background:u,mouse:!0}}else if(e.size.value||e.edges.label){var c=p-2*t.d3plus.r-2*e.labels.padding;t.d3plus.label={x:0,y:t.d3plus.r+c/2,w:p,h:c,color:T||s(l(e,t)),resize:[10,40],background:!0,mouse:!0}}else delete t.d3plus.rotate,delete t.d3plus.label;else delete t.d3plus.rotate,delete t.d3plus.label}),e.mouse.viz={},e.mouse.viz[i.click]=function(t){if(t[e.id.value]!=e.focus.value[0]){u(e.type.value);var n=e.focus.value[0];e.history.states.push(function(){e.self.focus(n).draw()}),e.self.focus(t[e.id.value]).draw()}},{edges:v,nodes:g,data:N}};p.filter=function(e,t){var n=e.edges.connections(e.focus.value[0],e.id.value,!0),r=[];n.forEach(function(t){r=r.concat(e.edges.connections(t[e.id.value],e.id.value,!0))});var a=n.concat(r),i=d(a,e.id.value,o,e),l=[];return i.forEach(function(n){var r=t.filter(function(t){return t[e.id.value]==n})[0];if(r)l.push(r);else{var a={d3plus:{}};a[e.id.value]=n,l.push(a)}}),l},p.nesting=!1,p.scale=1,p.shapes=["circle","square","donut"],p.requirements=["edges","focus"],p.tooltip="static",t.exports=p},{"../../array/sort.coffee":36,"../../client/pointer.coffee":40,"../../color/legible.coffee":46,"../../color/text.coffee":52,"../../core/fetch/color.coffee":65,"../../core/fetch/value.coffee":69,"../../network/smallestGap.coffee":171,"../../tooltip/remove.coffee":206,"../../util/uniques.coffee":213}],331:[function(e,t,n){var r,a,i,o,l;r=e("./sankey.js"),a=e("../../client/pointer.coffee"),i=e("../../tooltip/remove.coffee"),l=e("../../util/uniques.coffee"),o=function(e){var t,n,o,l,s,u,c,f,d,p,h,v,g,m,y;for(l=e.focus.value[0],v=2*e.data.stroke.width,y=e.size.value.constructor===Number?e.size.value:20,o=e.edges.connections(l,e.id.value).filter(function(t){return t[e.edges.source][e.id.value]!==l||t[e.edges.target][e.id.value]!==l}),h=[],g=[],o=o.map(function(t){var n,r;return t[e.edges.target][e.id.value]===l?(n={id:"left_"+t[e.edges.source][e.id.value],dupe:"left",data:t[e.edges.source],value:t[e.edges.strength.value]},r=t[e.edges.target]):(n=t[e.edges.source],r={id:"right_"+t[e.edges.target][e.id.value],dupe:"right",data:t[e.edges.target],value:t[e.edges.strength.value]}),g.indexOf(n.id)<0&&h.push(n),g.indexOf(r.id)<0&&h.push(r),g.push(n.id),g.push(r.id),{source:n,target:r,value:t[e.edges.strength.value]||1}}),c=r().nodeWidth(y).nodePadding(e.data.padding.value).size([e.width.viz-2*v,e.height.viz-2*v]).nodes(h).links(o).layout(2),m=[],s=0,f=h.length;s0&&(t.y+=n),a=t.y+t.dy+f;if(n=a-f-d[1],n>0)for(a=t.y-=n,r=o-2;r>=0;--r)t=e[r],n=t.y+t.dy+f-a,n>0&&(t.y-=n),a=t.y})}function i(e,t){return e.y-t.y}var o=d3.nest().key(function(e){return e.x}).sortKeys(d3.ascending).entries(p).map(function(e){return e.values});t(),a();for(var u=1;e>0;--e)r(u*=.99),a(),n(u),a()}function o(){function e(e,t){return e.source.y-t.source.y}function t(e,t){return e.target.y-t.target.y}p.forEach(function(n){n.sourceLinks.sort(t),n.targetLinks.sort(e)}),p.forEach(function(e){var t=0,n=0;e.sourceLinks.forEach(function(e){e.sy=t,t+=e.dy}),e.targetLinks.forEach(function(e){e.ty=n,n+=e.dy})})}function l(e){return e.y+e.dy/2}function s(e){return e.value}var u={},c=24,f=8,d=[1,1],p=[],h=[];return u.nodeWidth=function(e){return arguments.length?(c=+e,u):c},u.nodePadding=function(e){return arguments.length?(f=+e,u):f},u.nodes=function(e){return arguments.length?(p=e,u):p},u.links=function(e){return arguments.length?(h=e,u):h},u.size=function(e){return arguments.length?(d=e,u):d},u.layout=function(r){return e(),t(),n(),i(r),o(),u},u.relayout=function(){return o(),u},u.link=function(){function e(e){var n=e.source.x+e.source.dx,r=e.target.x,a=d3.interpolateNumber(n,r),i=a(t),o=a(1-t),l=e.source.y+e.sy+e.dy/2,s=e.target.y+e.ty+e.dy/2;return"M"+n+","+l+"C"+i+","+l+" "+o+","+s+" "+r+","+s}var t=.5;return e.curvature=function(n){return arguments.length?(t=+n,e):t},e},u}},{}],333:[function(e,t,n){var r,a,i,o,l,s;r=e("../../core/fetch/value.coffee"),a=e("./helpers/graph/draw.coffee"),i=e("../../core/console/print.coffee"),l=e("../../array/sort.coffee"),s=e("./helpers/graph/dataTicks.coffee"),o=function(e){var t,n,i,o,u;if(a(e,{buffer:"size",mouse:!0}),n=e.x.domain.viz.concat(e.y.domain.viz),n.indexOf(void 0)>=0)return[];for(u=e.data.viz,i=0,o=u.length;i=0&&n in t&&(d[n]&&(o.d3plus.color=d[n](o[n])),o.d3plus.text=e.format.value(o[n]),"boolean"==e.data.keys[n]?o.d3plus.label=!1:"string"==e.data.keys[n]&&(o.d3plus.color=e.color.missing, +o.d3plus.stroke="#fff",o.d3plus.shape="square"),f.push(o))})}),f};l.shapes=["check","cross","diamond","square","triangle","triangle_up","triangle_down"],l.requirements=["data","cols"],t.exports=l},{"../../color/random.coffee":49,"../../core/fetch/value.coffee":69,"../../util/copy.coffee":210,"../../util/uniques.coffee":213}],335:[function(e,t,n){var r,a,i,o;r=e("../../core/data/threshold.js"),a=e("../../core/data/group.coffee"),i=e("../../object/merge.coffee"),o=function(e){var t,n,r,o,l,s,u;if(r=a(e,e.data.viz),n=d3.layout.treemap().mode(e.type.mode.value).round(!0).size([e.width.viz,e.height.viz]).children(function(e){return e.values}).padding(e.data.padding.value).sort(function(e,t){var n;return n=e.value-t.value,0===n?e.id 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len + + var L = 0 + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' + } + + parts.push(output) + + return parts.join('') +} + +},{}],2:[function(require,module,exports){ +(function (global){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') +var isArray = require('isarray') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + +/* + * Export kMaxLength after typed array support is determined. + */ +exports.kMaxLength = kMaxLength() + +function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } +} + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr +} + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +} + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +} + +function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0 + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +} + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + var actual = that.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual) + } + + return that +} + +function fromArrayLike (that, array) { + var length = checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that +} + +function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start] + } + } + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 +} + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"base64-js":1,"ieee754":5,"isarray":6}],3:[function(require,module,exports){ +module.exports = require('./lib/heap'); + +},{"./lib/heap":4}],4:[function(require,module,exports){ +// Generated by CoffeeScript 1.8.0 +(function() { + var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup; + + floor = Math.floor, min = Math.min; + + + /* + Default comparison function to be used + */ + + defaultCmp = function(x, y) { + if (x < y) { + return -1; + } + if (x > y) { + return 1; + } + return 0; + }; + + + /* + Insert item x in list a, and keep it sorted assuming a is sorted. + + If x is already in a, insert it to the right of the rightmost x. + + Optional args lo (default 0) and hi (default a.length) bound the slice + of a to be searched. + */ + + insort = function(a, x, lo, hi, cmp) { + var mid; + if (lo == null) { + lo = 0; + } + if (cmp == null) { + cmp = defaultCmp; + } + if (lo < 0) { + throw new Error('lo must be non-negative'); + } + if (hi == null) { + hi = a.length; + } + while (lo < hi) { + mid = floor((lo + hi) / 2); + if (cmp(x, a[mid]) < 0) { + hi = mid; + } else { + lo = mid + 1; + } + } + return ([].splice.apply(a, [lo, lo - lo].concat(x)), x); + }; + + + /* + Push item onto heap, maintaining the heap invariant. + */ + + heappush = function(array, item, cmp) { + if (cmp == null) { + cmp = defaultCmp; + } + array.push(item); + return _siftdown(array, 0, array.length - 1, cmp); + }; + + + /* + Pop the smallest item off the heap, maintaining the heap invariant. + */ + + heappop = function(array, cmp) { + var lastelt, returnitem; + if (cmp == null) { + cmp = defaultCmp; + } + lastelt = array.pop(); + if (array.length) { + returnitem = array[0]; + array[0] = lastelt; + _siftup(array, 0, cmp); + } else { + returnitem = lastelt; + } + return returnitem; + }; + + + /* + Pop and return the current smallest value, and add the new item. + + This is more efficient than heappop() followed by heappush(), and can be + more appropriate when using a fixed size heap. Note that the value + returned may be larger than item! That constrains reasonable use of + this routine unless written as part of a conditional replacement: + if item > array[0] + item = heapreplace(array, item) + */ + + heapreplace = function(array, item, cmp) { + var returnitem; + if (cmp == null) { + cmp = defaultCmp; + } + returnitem = array[0]; + array[0] = item; + _siftup(array, 0, cmp); + return returnitem; + }; + + + /* + Fast version of a heappush followed by a heappop. + */ + + heappushpop = function(array, item, cmp) { + var _ref; + if (cmp == null) { + cmp = defaultCmp; + } + if (array.length && cmp(array[0], item) < 0) { + _ref = [array[0], item], item = _ref[0], array[0] = _ref[1]; + _siftup(array, 0, cmp); + } + return item; + }; + + + /* + Transform list into a heap, in-place, in O(array.length) time. + */ + + heapify = function(array, cmp) { + var i, _i, _j, _len, _ref, _ref1, _results, _results1; + if (cmp == null) { + cmp = defaultCmp; + } + _ref1 = (function() { + _results1 = []; + for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); } + return _results1; + }).apply(this).reverse(); + _results = []; + for (_i = 0, _len = _ref1.length; _i < _len; _i++) { + i = _ref1[_i]; + _results.push(_siftup(array, i, cmp)); + } + return _results; + }; + + + /* + Update the position of the given item in the heap. + This function should be called every time the item is being modified. + */ + + updateItem = function(array, item, cmp) { + var pos; + if (cmp == null) { + cmp = defaultCmp; + } + pos = array.indexOf(item); + if (pos === -1) { + return; + } + _siftdown(array, 0, pos, cmp); + return _siftup(array, pos, cmp); + }; + + + /* + Find the n largest elements in a dataset. + */ + + nlargest = function(array, n, cmp) { + var elem, result, _i, _len, _ref; + if (cmp == null) { + cmp = defaultCmp; + } + result = array.slice(0, n); + if (!result.length) { + return result; + } + heapify(result, cmp); + _ref = array.slice(n); + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + elem = _ref[_i]; + heappushpop(result, elem, cmp); + } + return result.sort(cmp).reverse(); + }; + + + /* + Find the n smallest elements in a dataset. + */ + + nsmallest = function(array, n, cmp) { + var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results; + if (cmp == null) { + cmp = defaultCmp; + } + if (n * 10 <= array.length) { + result = array.slice(0, n).sort(cmp); + if (!result.length) { + return result; + } + los = result[result.length - 1]; + _ref = array.slice(n); + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + elem = _ref[_i]; + if (cmp(elem, los) < 0) { + insort(result, elem, 0, null, cmp); + result.pop(); + los = result[result.length - 1]; + } + } + return result; + } + heapify(array, cmp); + _results = []; + for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) { + _results.push(heappop(array, cmp)); + } + return _results; + }; + + _siftdown = function(array, startpos, pos, cmp) { + var newitem, parent, parentpos; + if (cmp == null) { + cmp = defaultCmp; + } + newitem = array[pos]; + while (pos > startpos) { + parentpos = (pos - 1) >> 1; + parent = array[parentpos]; + if (cmp(newitem, parent) < 0) { + array[pos] = parent; + pos = parentpos; + continue; + } + break; + } + return array[pos] = newitem; + }; + + _siftup = function(array, pos, cmp) { + var childpos, endpos, newitem, rightpos, startpos; + if (cmp == null) { + cmp = defaultCmp; + } + endpos = array.length; + startpos = pos; + newitem = array[pos]; + childpos = 2 * pos + 1; + while (childpos < endpos) { + rightpos = childpos + 1; + if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) { + childpos = rightpos; + } + array[pos] = array[childpos]; + pos = childpos; + childpos = 2 * pos + 1; + } + array[pos] = newitem; + return _siftdown(array, startpos, pos, cmp); + }; + + Heap = (function() { + Heap.push = heappush; + + Heap.pop = heappop; + + Heap.replace = heapreplace; + + Heap.pushpop = heappushpop; + + Heap.heapify = heapify; + + Heap.updateItem = updateItem; + + Heap.nlargest = nlargest; + + Heap.nsmallest = nsmallest; + + function Heap(cmp) { + this.cmp = cmp != null ? cmp : defaultCmp; + this.nodes = []; + } + + Heap.prototype.push = function(x) { + return heappush(this.nodes, x, this.cmp); + }; + + Heap.prototype.pop = function() { + return heappop(this.nodes, this.cmp); + }; + + Heap.prototype.peek = function() { + return this.nodes[0]; + }; + + Heap.prototype.contains = function(x) { + return this.nodes.indexOf(x) !== -1; + }; + + Heap.prototype.replace = function(x) { + return heapreplace(this.nodes, x, this.cmp); + }; + + Heap.prototype.pushpop = function(x) { + return heappushpop(this.nodes, x, this.cmp); + }; + + Heap.prototype.heapify = function() { + return heapify(this.nodes, this.cmp); + }; + + Heap.prototype.updateItem = function(x) { + return updateItem(this.nodes, x, this.cmp); + }; + + Heap.prototype.clear = function() { + return this.nodes = []; + }; + + Heap.prototype.empty = function() { + return this.nodes.length === 0; + }; + + Heap.prototype.size = function() { + return this.nodes.length; + }; + + Heap.prototype.clone = function() { + var heap; + heap = new Heap(); + heap.nodes = this.nodes.slice(0); + return heap; + }; + + Heap.prototype.toArray = function() { + return this.nodes.slice(0); + }; + + Heap.prototype.insert = Heap.prototype.push; + + Heap.prototype.top = Heap.prototype.peek; + + Heap.prototype.front = Heap.prototype.peek; + + Heap.prototype.has = Heap.prototype.contains; + + Heap.prototype.copy = Heap.prototype.clone; + + return Heap; + + })(); + + (function(root, factory) { + if (typeof define === 'function' && define.amd) { + return define([], factory); + } else if (typeof exports === 'object') { + return module.exports = factory(); + } else { + return root.Heap = factory(); + } + })(this, function() { + return Heap; + }); + +}).call(this); + +},{}],5:[function(require,module,exports){ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}],6:[function(require,module,exports){ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +},{}],7:[function(require,module,exports){ +(function (global){ +"use strict"; + +var numeric = (typeof exports === "undefined")?(function numeric() {}):(exports); +if(typeof global !== "undefined") { global.numeric = numeric; } + +numeric.version = "1.2.6"; + +// 1. Utility functions +numeric.bench = function bench (f,interval) { + var t1,t2,n,i; + if(typeof interval === "undefined") { interval = 15; } + n = 0.5; + t1 = new Date(); + while(1) { + n*=2; + for(i=n;i>3;i-=4) { f(); f(); f(); f(); } + while(i>0) { f(); i--; } + t2 = new Date(); + if(t2-t1 > interval) break; + } + for(i=n;i>3;i-=4) { f(); f(); f(); f(); } + while(i>0) { f(); i--; } + t2 = new Date(); + return 1000*(3*n-1)/(t2-t1); +} + +numeric._myIndexOf = (function _myIndexOf(w) { + var n = this.length,k; + for(k=0;k numeric.largeArray) { ret.push('...Large Array...'); return true; } + var flag = false; + ret.push('['); + for(k=0;k0) { ret.push(','); if(flag) ret.push('\n '); } flag = foo(x[k]); } + ret.push(']'); + return true; + } + ret.push('{'); + var flag = false; + for(k in x) { if(x.hasOwnProperty(k)) { if(flag) ret.push(',\n'); flag = true; ret.push(k); ret.push(': \n'); foo(x[k]); } } + ret.push('}'); + return true; + } + foo(x); + return ret.join(''); +} + +numeric.parseDate = function parseDate(d) { + function foo(d) { + if(typeof d === 'string') { return Date.parse(d.replace(/-/g,'/')); } + if(!(d instanceof Array)) { throw new Error("parseDate: parameter must be arrays of strings"); } + var ret = [],k; + for(k=0;k0) { + ret[count] = []; + for(j=0;j> 2; + q = ((x & 3) << 4) + (y >> 4); + r = ((y & 15) << 2) + (z >> 6); + s = z & 63; + if(i+1>=n) { r = s = 64; } + else if(i+2>=n) { s = 64; } + ret += key.charAt(p) + key.charAt(q) + key.charAt(r) + key.charAt(s); + } + return ret; + } + function crc32Array (a,from,to) { + if(typeof from === "undefined") { from = 0; } + if(typeof to === "undefined") { to = a.length; } + var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, + 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, + 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, + 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, + 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, + 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, + 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, + 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, + 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, + 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, + 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, + 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, + 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, + 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, + 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, + 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, + 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, + 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, + 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, + 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, + 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, + 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, + 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, + 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, + 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, + 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, + 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, + 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, + 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, + 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, + 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, + 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; + + var crc = -1, y = 0, n = a.length,i; + + for (i = from; i < to; i++) { + y = (crc ^ a[i]) & 0xFF; + crc = (crc >>> 8) ^ table[y]; + } + + return crc ^ (-1); + } + + var h = img[0].length, w = img[0][0].length, s1, s2, next,k,length,a,b,i,j,adler32,crc32; + var stream = [ + 137, 80, 78, 71, 13, 10, 26, 10, // 0: PNG signature + 0,0,0,13, // 8: IHDR Chunk length + 73, 72, 68, 82, // 12: "IHDR" + (w >> 24) & 255, (w >> 16) & 255, (w >> 8) & 255, w&255, // 16: Width + (h >> 24) & 255, (h >> 16) & 255, (h >> 8) & 255, h&255, // 20: Height + 8, // 24: bit depth + 2, // 25: RGB + 0, // 26: deflate + 0, // 27: no filter + 0, // 28: no interlace + -1,-2,-3,-4, // 29: CRC + -5,-6,-7,-8, // 33: IDAT Chunk length + 73, 68, 65, 84, // 37: "IDAT" + // RFC 1950 header starts here + 8, // 41: RFC1950 CMF + 29 // 42: RFC1950 FLG + ]; + crc32 = crc32Array(stream,12,29); + stream[29] = (crc32>>24)&255; + stream[30] = (crc32>>16)&255; + stream[31] = (crc32>>8)&255; + stream[32] = (crc32)&255; + s1 = 1; + s2 = 0; + for(i=0;i>8)&255; + stream.push(a); stream.push(b); + stream.push((~a)&255); stream.push((~b)&255); + if(i===0) stream.push(0); + for(j=0;j255) a = 255; + else if(a<0) a=0; + else a = Math.round(a); + s1 = (s1 + a )%65521; + s2 = (s2 + s1)%65521; + stream.push(a); + } + } + stream.push(0); + } + adler32 = (s2<<16)+s1; + stream.push((adler32>>24)&255); + stream.push((adler32>>16)&255); + stream.push((adler32>>8)&255); + stream.push((adler32)&255); + length = stream.length - 41; + stream[33] = (length>>24)&255; + stream[34] = (length>>16)&255; + stream[35] = (length>>8)&255; + stream[36] = (length)&255; + crc32 = crc32Array(stream,37); + stream.push((crc32>>24)&255); + stream.push((crc32>>16)&255); + stream.push((crc32>>8)&255); + stream.push((crc32)&255); + stream.push(0); + stream.push(0); + stream.push(0); + stream.push(0); +// a = stream.length; + stream.push(73); // I + stream.push(69); // E + stream.push(78); // N + stream.push(68); // D + stream.push(174); // CRC1 + stream.push(66); // CRC2 + stream.push(96); // CRC3 + stream.push(130); // CRC4 + return 'data:image/png;base64,'+base64(stream); +} + +// 2. Linear algebra with Arrays. +numeric._dim = function _dim(x) { + var ret = []; + while(typeof x === "object") { ret.push(x.length); x = x[0]; } + return ret; +} + +numeric.dim = function dim(x) { + var y,z; + if(typeof x === "object") { + y = x[0]; + if(typeof y === "object") { + z = y[0]; + if(typeof z === "object") { + return numeric._dim(x); + } + return [x.length,y.length]; + } + return [x.length]; + } + return []; +} + +numeric.mapreduce = function mapreduce(body,init) { + return Function('x','accum','_s','_k', + 'if(typeof accum === "undefined") accum = '+init+';\n'+ + 'if(typeof x === "number") { var xi = x; '+body+'; return accum; }\n'+ + 'if(typeof _s === "undefined") _s = numeric.dim(x);\n'+ + 'if(typeof _k === "undefined") _k = 0;\n'+ + 'var _n = _s[_k];\n'+ + 'var i,xi;\n'+ + 'if(_k < _s.length-1) {\n'+ + ' for(i=_n-1;i>=0;i--) {\n'+ + ' accum = arguments.callee(x[i],accum,_s,_k+1);\n'+ + ' }'+ + ' return accum;\n'+ + '}\n'+ + 'for(i=_n-1;i>=1;i-=2) { \n'+ + ' xi = x[i];\n'+ + ' '+body+';\n'+ + ' xi = x[i-1];\n'+ + ' '+body+';\n'+ + '}\n'+ + 'if(i === 0) {\n'+ + ' xi = x[i];\n'+ + ' '+body+'\n'+ + '}\n'+ + 'return accum;' + ); +} +numeric.mapreduce2 = function mapreduce2(body,setup) { + return Function('x', + 'var n = x.length;\n'+ + 'var i,xi;\n'+setup+';\n'+ + 'for(i=n-1;i!==-1;--i) { \n'+ + ' xi = x[i];\n'+ + ' '+body+';\n'+ + '}\n'+ + 'return accum;' + ); +} + + +numeric.same = function same(x,y) { + var i,n; + if(!(x instanceof Array) || !(y instanceof Array)) { return false; } + n = x.length; + if(n !== y.length) { return false; } + for(i=0;i=0;i-=2) { ret[i+1] = v; ret[i] = v; } + if(i===-1) { ret[0] = v; } + return ret; + } + for(i=n-1;i>=0;i--) { ret[i] = numeric.rep(s,v,k+1); } + return ret; +} + + +numeric.dotMMsmall = function dotMMsmall(x,y) { + var i,j,k,p,q,r,ret,foo,bar,woo,i0,k0,p0,r0; + p = x.length; q = y.length; r = y[0].length; + ret = Array(p); + for(i=p-1;i>=0;i--) { + foo = Array(r); + bar = x[i]; + for(k=r-1;k>=0;k--) { + woo = bar[q-1]*y[q-1][k]; + for(j=q-2;j>=1;j-=2) { + i0 = j-1; + woo += bar[j]*y[j][k] + bar[i0]*y[i0][k]; + } + if(j===0) { woo += bar[0]*y[0][k]; } + foo[k] = woo; + } + ret[i] = foo; + } + return ret; +} +numeric._getCol = function _getCol(A,j,x) { + var n = A.length, i; + for(i=n-1;i>0;--i) { + x[i] = A[i][j]; + --i; + x[i] = A[i][j]; + } + if(i===0) x[0] = A[0][j]; +} +numeric.dotMMbig = function dotMMbig(x,y){ + var gc = numeric._getCol, p = y.length, v = Array(p); + var m = x.length, n = y[0].length, A = new Array(m), xj; + var VV = numeric.dotVV; + var i,j,k,z; + --p; + --m; + for(i=m;i!==-1;--i) A[i] = Array(n); + --n; + for(i=n;i!==-1;--i) { + gc(y,i,v); + for(j=m;j!==-1;--j) { + z=0; + xj = x[j]; + A[j][i] = VV(xj,v); + } + } + return A; +} + +numeric.dotMV = function dotMV(x,y) { + var p = x.length, q = y.length,i; + var ret = Array(p), dotVV = numeric.dotVV; + for(i=p-1;i>=0;i--) { ret[i] = dotVV(x[i],y); } + return ret; +} + +numeric.dotVM = function dotVM(x,y) { + var i,j,k,p,q,r,ret,foo,bar,woo,i0,k0,p0,r0,s1,s2,s3,baz,accum; + p = x.length; q = y[0].length; + ret = Array(q); + for(k=q-1;k>=0;k--) { + woo = x[p-1]*y[p-1][k]; + for(j=p-2;j>=1;j-=2) { + i0 = j-1; + woo += x[j]*y[j][k] + x[i0]*y[i0][k]; + } + if(j===0) { woo += x[0]*y[0][k]; } + ret[k] = woo; + } + return ret; +} + +numeric.dotVV = function dotVV(x,y) { + var i,n=x.length,i1,ret = x[n-1]*y[n-1]; + for(i=n-2;i>=1;i-=2) { + i1 = i-1; + ret += x[i]*y[i] + x[i1]*y[i1]; + } + if(i===0) { ret += x[0]*y[0]; } + return ret; +} + +numeric.dot = function dot(x,y) { + var d = numeric.dim; + switch(d(x).length*1000+d(y).length) { + case 2002: + if(y.length < 10) return numeric.dotMMsmall(x,y); + else return numeric.dotMMbig(x,y); + case 2001: return numeric.dotMV(x,y); + case 1002: return numeric.dotVM(x,y); + case 1001: return numeric.dotVV(x,y); + case 1000: return numeric.mulVS(x,y); + case 1: return numeric.mulSV(x,y); + case 0: return x*y; + default: throw new Error('numeric.dot only works on vectors and matrices'); + } +} + +numeric.diag = function diag(d) { + var i,i1,j,n = d.length, A = Array(n), Ai; + for(i=n-1;i>=0;i--) { + Ai = Array(n); + i1 = i+2; + for(j=n-1;j>=i1;j-=2) { + Ai[j] = 0; + Ai[j-1] = 0; + } + if(j>i) { Ai[j] = 0; } + Ai[i] = d[i]; + for(j=i-1;j>=1;j-=2) { + Ai[j] = 0; + Ai[j-1] = 0; + } + if(j===0) { Ai[0] = 0; } + A[i] = Ai; + } + return A; +} +numeric.getDiag = function(A) { + var n = Math.min(A.length,A[0].length),i,ret = Array(n); + for(i=n-1;i>=1;--i) { + ret[i] = A[i][i]; + --i; + ret[i] = A[i][i]; + } + if(i===0) { + ret[0] = A[0][0]; + } + return ret; +} + +numeric.identity = function identity(n) { return numeric.diag(numeric.rep([n],1)); } +numeric.pointwise = function pointwise(params,body,setup) { + if(typeof setup === "undefined") { setup = ""; } + var fun = []; + var k; + var avec = /\[i\]$/,p,thevec = ''; + var haveret = false; + for(k=0;k=0;i--) ret[i] = arguments.callee('+params.join(',')+',_s,_k+1);\n'+ + ' return ret;\n'+ + '}\n'+ + setup+'\n'+ + 'for(i=_n-1;i!==-1;--i) {\n'+ + ' '+body+'\n'+ + '}\n'+ + 'return ret;' + ); + return Function.apply(null,fun); +} +numeric.pointwise2 = function pointwise2(params,body,setup) { + if(typeof setup === "undefined") { setup = ""; } + var fun = []; + var k; + var avec = /\[i\]$/,p,thevec = ''; + var haveret = false; + for(k=0;k=0;i--) { _biforeach(typeof x==="object"?x[i]:x,typeof y==="object"?y[i]:y,s,k+1,f); } +}); +numeric._biforeach2 = (function _biforeach2(x,y,s,k,f) { + if(k === s.length-1) { return f(x,y); } + var i,n=s[k],ret = Array(n); + for(i=n-1;i>=0;--i) { ret[i] = _biforeach2(typeof x==="object"?x[i]:x,typeof y==="object"?y[i]:y,s,k+1,f); } + return ret; +}); +numeric._foreach = (function _foreach(x,s,k,f) { + if(k === s.length-1) { f(x); return; } + var i,n=s[k]; + for(i=n-1;i>=0;i--) { _foreach(x[i],s,k+1,f); } +}); +numeric._foreach2 = (function _foreach2(x,s,k,f) { + if(k === s.length-1) { return f(x); } + var i,n=s[k], ret = Array(n); + for(i=n-1;i>=0;i--) { ret[i] = _foreach2(x[i],s,k+1,f); } + return ret; +}); + +/*numeric.anyV = numeric.mapreduce('if(xi) return true;','false'); +numeric.allV = numeric.mapreduce('if(!xi) return false;','true'); +numeric.any = function(x) { if(typeof x.length === "undefined") return x; return numeric.anyV(x); } +numeric.all = function(x) { if(typeof x.length === "undefined") return x; return numeric.allV(x); }*/ + +numeric.ops2 = { + add: '+', + sub: '-', + mul: '*', + div: '/', + mod: '%', + and: '&&', + or: '||', + eq: '===', + neq: '!==', + lt: '<', + gt: '>', + leq: '<=', + geq: '>=', + band: '&', + bor: '|', + bxor: '^', + lshift: '<<', + rshift: '>>', + rrshift: '>>>' +}; +numeric.opseq = { + addeq: '+=', + subeq: '-=', + muleq: '*=', + diveq: '/=', + modeq: '%=', + lshifteq: '<<=', + rshifteq: '>>=', + rrshifteq: '>>>=', + bandeq: '&=', + boreq: '|=', + bxoreq: '^=' +}; +numeric.mathfuns = ['abs','acos','asin','atan','ceil','cos', + 'exp','floor','log','round','sin','sqrt','tan', + 'isNaN','isFinite']; +numeric.mathfuns2 = ['atan2','pow','max','min']; +numeric.ops1 = { + neg: '-', + not: '!', + bnot: '~', + clone: '' +}; +numeric.mapreducers = { + any: ['if(xi) return true;','var accum = false;'], + all: ['if(!xi) return false;','var accum = true;'], + sum: ['accum += xi;','var accum = 0;'], + prod: ['accum *= xi;','var accum = 1;'], + norm2Squared: ['accum += xi*xi;','var accum = 0;'], + norminf: ['accum = max(accum,abs(xi));','var accum = 0, max = Math.max, abs = Math.abs;'], + norm1: ['accum += abs(xi)','var accum = 0, abs = Math.abs;'], + sup: ['accum = max(accum,xi);','var accum = -Infinity, max = Math.max;'], + inf: ['accum = min(accum,xi);','var accum = Infinity, min = Math.min;'] +}; + +(function () { + var i,o; + for(i=0;iv0) { i0 = i; v0 = k; } } + Aj = A[i0]; A[i0] = A[j]; A[j] = Aj; + Ij = I[i0]; I[i0] = I[j]; I[j] = Ij; + x = Aj[j]; + for(k=j;k!==n;++k) Aj[k] /= x; + for(k=n-1;k!==-1;--k) Ij[k] /= x; + for(i=m-1;i!==-1;--i) { + if(i!==j) { + Ai = A[i]; + Ii = I[i]; + x = Ai[j]; + for(k=j+1;k!==n;++k) Ai[k] -= Aj[k]*x; + for(k=n-1;k>0;--k) { Ii[k] -= Ij[k]*x; --k; Ii[k] -= Ij[k]*x; } + if(k===0) Ii[0] -= Ij[0]*x; + } + } + } + return I; +} + +numeric.det = function det(x) { + var s = numeric.dim(x); + if(s.length !== 2 || s[0] !== s[1]) { throw new Error('numeric: det() only works on square matrices'); } + var n = s[0], ret = 1,i,j,k,A = numeric.clone(x),Aj,Ai,alpha,temp,k1,k2,k3; + for(j=0;j Math.abs(A[k][j])) { k = i; } } + if(k !== j) { + temp = A[k]; A[k] = A[j]; A[j] = temp; + ret *= -1; + } + Aj = A[j]; + for(i=j+1;i=1;i-=2) { + A1 = x[i]; + A0 = x[i-1]; + for(j=n-1;j>=1;--j) { + Bj = ret[j]; Bj[i] = A1[j]; Bj[i-1] = A0[j]; + --j; + Bj = ret[j]; Bj[i] = A1[j]; Bj[i-1] = A0[j]; + } + if(j===0) { + Bj = ret[0]; Bj[i] = A1[0]; Bj[i-1] = A0[0]; + } + } + if(i===0) { + A0 = x[0]; + for(j=n-1;j>=1;--j) { + ret[j][0] = A0[j]; + --j; + ret[j][0] = A0[j]; + } + if(j===0) { ret[0][0] = A0[0]; } + } + return ret; +} +numeric.negtranspose = function negtranspose(x) { + var i,j,m = x.length,n = x[0].length, ret=Array(n),A0,A1,Bj; + for(j=0;j=1;i-=2) { + A1 = x[i]; + A0 = x[i-1]; + for(j=n-1;j>=1;--j) { + Bj = ret[j]; Bj[i] = -A1[j]; Bj[i-1] = -A0[j]; + --j; + Bj = ret[j]; Bj[i] = -A1[j]; Bj[i-1] = -A0[j]; + } + if(j===0) { + Bj = ret[0]; Bj[i] = -A1[0]; Bj[i-1] = -A0[0]; + } + } + if(i===0) { + A0 = x[0]; + for(j=n-1;j>=1;--j) { + ret[j][0] = -A0[j]; + --j; + ret[j][0] = -A0[j]; + } + if(j===0) { ret[0][0] = -A0[0]; } + } + return ret; +} + +numeric._random = function _random(s,k) { + var i,n=s[k],ret=Array(n), rnd; + if(k === s.length-1) { + rnd = Math.random; + for(i=n-1;i>=1;i-=2) { + ret[i] = rnd(); + ret[i-1] = rnd(); + } + if(i===0) { ret[0] = rnd(); } + return ret; + } + for(i=n-1;i>=0;i--) ret[i] = _random(s,k+1); + return ret; +} +numeric.random = function random(s) { return numeric._random(s,0); } + +numeric.norm2 = function norm2(x) { return Math.sqrt(numeric.norm2Squared(x)); } + +numeric.linspace = function linspace(a,b,n) { + if(typeof n === "undefined") n = Math.max(Math.round(b-a)+1,1); + if(n<2) { return n===1?[a]:[]; } + var i,ret = Array(n); + n--; + for(i=n;i>=0;i--) { ret[i] = (i*b+(n-i)*a)/n; } + return ret; +} + +numeric.getBlock = function getBlock(x,from,to) { + var s = numeric.dim(x); + function foo(x,k) { + var i,a = from[k], n = to[k]-a, ret = Array(n); + if(k === s.length-1) { + for(i=n;i>=0;i--) { ret[i] = x[i+a]; } + return ret; + } + for(i=n;i>=0;i--) { ret[i] = foo(x[i+a],k+1); } + return ret; + } + return foo(x,0); +} + +numeric.setBlock = function setBlock(x,from,to,B) { + var s = numeric.dim(x); + function foo(x,y,k) { + var i,a = from[k], n = to[k]-a; + if(k === s.length-1) { for(i=n;i>=0;i--) { x[i+a] = y[i]; } } + for(i=n;i>=0;i--) { foo(x[i+a],y[i],k+1); } + } + foo(x,B,0); + return x; +} + +numeric.getRange = function getRange(A,I,J) { + var m = I.length, n = J.length; + var i,j; + var B = Array(m), Bi, AI; + for(i=m-1;i!==-1;--i) { + B[i] = Array(n); + Bi = B[i]; + AI = A[I[i]]; + for(j=n-1;j!==-1;--j) Bi[j] = AI[J[j]]; + } + return B; +} + +numeric.blockMatrix = function blockMatrix(X) { + var s = numeric.dim(X); + if(s.length<4) return numeric.blockMatrix([X]); + var m=s[0],n=s[1],M,N,i,j,Xij; + M = 0; N = 0; + for(i=0;i=0;i--) { + Ai = Array(n); + xi = x[i]; + for(j=n-1;j>=3;--j) { + Ai[j] = xi * y[j]; + --j; + Ai[j] = xi * y[j]; + --j; + Ai[j] = xi * y[j]; + --j; + Ai[j] = xi * y[j]; + } + while(j>=0) { Ai[j] = xi * y[j]; --j; } + A[i] = Ai; + } + return A; +} + +// 3. The Tensor type T +numeric.T = function T(x,y) { this.x = x; this.y = y; } +numeric.t = function t(x,y) { return new numeric.T(x,y); } + +numeric.Tbinop = function Tbinop(rr,rc,cr,cc,setup) { + var io = numeric.indexOf; + if(typeof setup !== "string") { + var k; + setup = ''; + for(k in numeric) { + if(numeric.hasOwnProperty(k) && (rr.indexOf(k)>=0 || rc.indexOf(k)>=0 || cr.indexOf(k)>=0 || cc.indexOf(k)>=0) && k.length>1) { + setup += 'var '+k+' = numeric.'+k+';\n'; + } + } + } + return Function(['y'], + 'var x = this;\n'+ + 'if(!(y instanceof numeric.T)) { y = new numeric.T(y); }\n'+ + setup+'\n'+ + 'if(x.y) {'+ + ' if(y.y) {'+ + ' return new numeric.T('+cc+');\n'+ + ' }\n'+ + ' return new numeric.T('+cr+');\n'+ + '}\n'+ + 'if(y.y) {\n'+ + ' return new numeric.T('+rc+');\n'+ + '}\n'+ + 'return new numeric.T('+rr+');\n' + ); +} + +numeric.T.prototype.add = numeric.Tbinop( + 'add(x.x,y.x)', + 'add(x.x,y.x),y.y', + 'add(x.x,y.x),x.y', + 'add(x.x,y.x),add(x.y,y.y)'); +numeric.T.prototype.sub = numeric.Tbinop( + 'sub(x.x,y.x)', + 'sub(x.x,y.x),neg(y.y)', + 'sub(x.x,y.x),x.y', + 'sub(x.x,y.x),sub(x.y,y.y)'); +numeric.T.prototype.mul = numeric.Tbinop( + 'mul(x.x,y.x)', + 'mul(x.x,y.x),mul(x.x,y.y)', + 'mul(x.x,y.x),mul(x.y,y.x)', + 'sub(mul(x.x,y.x),mul(x.y,y.y)),add(mul(x.x,y.y),mul(x.y,y.x))'); + +numeric.T.prototype.reciprocal = function reciprocal() { + var mul = numeric.mul, div = numeric.div; + if(this.y) { + var d = numeric.add(mul(this.x,this.x),mul(this.y,this.y)); + return new numeric.T(div(this.x,d),div(numeric.neg(this.y),d)); + } + return new T(div(1,this.x)); +} +numeric.T.prototype.div = function div(y) { + if(!(y instanceof numeric.T)) y = new numeric.T(y); + if(y.y) { return this.mul(y.reciprocal()); } + var div = numeric.div; + if(this.y) { return new numeric.T(div(this.x,y.x),div(this.y,y.x)); } + return new numeric.T(div(this.x,y.x)); +} +numeric.T.prototype.dot = numeric.Tbinop( + 'dot(x.x,y.x)', + 'dot(x.x,y.x),dot(x.x,y.y)', + 'dot(x.x,y.x),dot(x.y,y.x)', + 'sub(dot(x.x,y.x),dot(x.y,y.y)),add(dot(x.x,y.y),dot(x.y,y.x))' + ); +numeric.T.prototype.transpose = function transpose() { + var t = numeric.transpose, x = this.x, y = this.y; + if(y) { return new numeric.T(t(x),t(y)); } + return new numeric.T(t(x)); +} +numeric.T.prototype.transjugate = function transjugate() { + var t = numeric.transpose, x = this.x, y = this.y; + if(y) { return new numeric.T(t(x),numeric.negtranspose(y)); } + return new numeric.T(t(x)); +} +numeric.Tunop = function Tunop(r,c,s) { + if(typeof s !== "string") { s = ''; } + return Function( + 'var x = this;\n'+ + s+'\n'+ + 'if(x.y) {'+ + ' '+c+';\n'+ + '}\n'+ + r+';\n' + ); +} + +numeric.T.prototype.exp = numeric.Tunop( + 'return new numeric.T(ex)', + 'return new numeric.T(mul(cos(x.y),ex),mul(sin(x.y),ex))', + 'var ex = numeric.exp(x.x), cos = numeric.cos, sin = numeric.sin, mul = numeric.mul;'); +numeric.T.prototype.conj = numeric.Tunop( + 'return new numeric.T(x.x);', + 'return new numeric.T(x.x,numeric.neg(x.y));'); +numeric.T.prototype.neg = numeric.Tunop( + 'return new numeric.T(neg(x.x));', + 'return new numeric.T(neg(x.x),neg(x.y));', + 'var neg = numeric.neg;'); +numeric.T.prototype.sin = numeric.Tunop( + 'return new numeric.T(numeric.sin(x.x))', + 'return x.exp().sub(x.neg().exp()).div(new numeric.T(0,2));'); +numeric.T.prototype.cos = numeric.Tunop( + 'return new numeric.T(numeric.cos(x.x))', + 'return x.exp().add(x.neg().exp()).div(2);'); +numeric.T.prototype.abs = numeric.Tunop( + 'return new numeric.T(numeric.abs(x.x));', + 'return new numeric.T(numeric.sqrt(numeric.add(mul(x.x,x.x),mul(x.y,x.y))));', + 'var mul = numeric.mul;'); +numeric.T.prototype.log = numeric.Tunop( + 'return new numeric.T(numeric.log(x.x));', + 'var theta = new numeric.T(numeric.atan2(x.y,x.x)), r = x.abs();\n'+ + 'return new numeric.T(numeric.log(r.x),theta.x);'); +numeric.T.prototype.norm2 = numeric.Tunop( + 'return numeric.norm2(x.x);', + 'var f = numeric.norm2Squared;\n'+ + 'return Math.sqrt(f(x.x)+f(x.y));'); +numeric.T.prototype.inv = function inv() { + var A = this; + if(typeof A.y === "undefined") { return new numeric.T(numeric.inv(A.x)); } + var n = A.x.length, i, j, k; + var Rx = numeric.identity(n),Ry = numeric.rep([n,n],0); + var Ax = numeric.clone(A.x), Ay = numeric.clone(A.y); + var Aix, Aiy, Ajx, Ajy, Rix, Riy, Rjx, Rjy; + var i,j,k,d,d1,ax,ay,bx,by,temp; + for(i=0;i d) { k=j; d = d1; } + } + if(k!==i) { + temp = Ax[i]; Ax[i] = Ax[k]; Ax[k] = temp; + temp = Ay[i]; Ay[i] = Ay[k]; Ay[k] = temp; + temp = Rx[i]; Rx[i] = Rx[k]; Rx[k] = temp; + temp = Ry[i]; Ry[i] = Ry[k]; Ry[k] = temp; + } + Aix = Ax[i]; Aiy = Ay[i]; + Rix = Rx[i]; Riy = Ry[i]; + ax = Aix[i]; ay = Aiy[i]; + for(j=i+1;j0;i--) { + Rix = Rx[i]; Riy = Ry[i]; + for(j=i-1;j>=0;j--) { + Rjx = Rx[j]; Rjy = Ry[j]; + ax = Ax[j][i]; ay = Ay[j][i]; + for(k=n-1;k>=0;k--) { + bx = Rix[k]; by = Riy[k]; + Rjx[k] -= ax*bx - ay*by; + Rjy[k] -= ax*by + ay*bx; + } + } + } + return new numeric.T(Rx,Ry); +} +numeric.T.prototype.get = function get(i) { + var x = this.x, y = this.y, k = 0, ik, n = i.length; + if(y) { + while(k= 0 ? 1 : -1; + var alpha = s*numeric.norm2(x); + v[0] += alpha; + var foo = numeric.norm2(v); + if(foo === 0) { /* this should not happen */ throw new Error('eig: internal error'); } + return numeric.div(v,foo); +} + +numeric.toUpperHessenberg = function toUpperHessenberg(me) { + var s = numeric.dim(me); + if(s.length !== 2 || s[0] !== s[1]) { throw new Error('numeric: toUpperHessenberg() only works on square matrices'); } + var m = s[0], i,j,k,x,v,A = numeric.clone(me),B,C,Ai,Ci,Q = numeric.identity(m),Qi; + for(j=0;j0) { + v = numeric.house(x); + B = numeric.getBlock(A,[j+1,j],[m-1,m-1]); + C = numeric.tensor(v,numeric.dot(v,B)); + for(i=j+1;i=4*det) { + var s1,s2; + s1 = 0.5*(tr+Math.sqrt(tr*tr-4*det)); + s2 = 0.5*(tr-Math.sqrt(tr*tr-4*det)); + Hloc = numeric.add(numeric.sub(numeric.dot(Hloc,Hloc), + numeric.mul(Hloc,s1+s2)), + numeric.diag(numeric.rep([3],s1*s2))); + } else { + Hloc = numeric.add(numeric.sub(numeric.dot(Hloc,Hloc), + numeric.mul(Hloc,tr)), + numeric.diag(numeric.rep([3],det))); + } + x = [Hloc[0][0],Hloc[1][0],Hloc[2][0]]; + v = numeric.house(x); + B = [H[0],H[1],H[2]]; + C = numeric.tensor(v,numeric.dot(v,B)); + for(i=0;i<3;i++) { Hi = H[i]; Ci = C[i]; for(k=0;k=0) { + if(p1<0) x = -0.5*(p1-sqrt(disc)); + else x = -0.5*(p1+sqrt(disc)); + n1 = (a-x)*(a-x)+b*b; + n2 = c*c+(d-x)*(d-x); + if(n1>n2) { + n1 = sqrt(n1); + p = (a-x)/n1; + q = b/n1; + } else { + n2 = sqrt(n2); + p = c/n2; + q = (d-x)/n2; + } + Q0 = new T([[q,-p],[p,q]]); + Q.setRows(i,j,Q0.dot(Q.getRows(i,j))); + } else { + x = -0.5*p1; + y = 0.5*sqrt(-disc); + n1 = (a-x)*(a-x)+b*b; + n2 = c*c+(d-x)*(d-x); + if(n1>n2) { + n1 = sqrt(n1+y*y); + p = (a-x)/n1; + q = b/n1; + x = 0; + y /= n1; + } else { + n2 = sqrt(n2+y*y); + p = c/n2; + q = (d-x)/n2; + x = y/n2; + y = 0; + } + Q0 = new T([[q,-p],[p,q]],[[x,y],[y,-x]]); + Q.setRows(i,j,Q0.dot(Q.getRows(i,j))); + } + } + } + var R = Q.dot(A).dot(Q.transjugate()), n = A.length, E = numeric.T.identity(n); + for(j=0;j0) { + for(k=j-1;k>=0;k--) { + var Rk = R.get([k,k]), Rj = R.get([j,j]); + if(numeric.neq(Rk.x,Rj.x) || numeric.neq(Rk.y,Rj.y)) { + x = R.getRow(k).getBlock([k],[j-1]); + y = E.getRow(j).getBlock([k],[j-1]); + E.set([j,k],(R.get([k,j]).neg().sub(x.dot(y))).div(Rk.sub(Rj))); + } else { + E.setRow(j,E.getRow(k)); + continue; + } + } + } + } + for(j=0;j=counts.length) counts[counts.length] = 0; + if(foo[j]!==0) counts[j]++; + } + } + var n = counts.length; + var Ai = Array(n+1); + Ai[0] = 0; + for(i=0;i= k11) { + xj[n] = j[m]; + if(m===0) return; + ++n; + --m; + km = k[m]; + k11 = k1[m]; + } else { + foo = Pinv[Aj[km]]; + if(x[foo] === 0) { + x[foo] = 1; + k[m] = km; + ++m; + j[m] = foo; + km = Ai[foo]; + k1[m] = k11 = Ai[foo+1]; + } else ++km; + } + } +} +numeric.ccsLPSolve = function ccsLPSolve(A,B,x,xj,I,Pinv,dfs) { + var Ai = A[0], Aj = A[1], Av = A[2],m = Ai.length-1, n=0; + var Bi = B[0], Bj = B[1], Bv = B[2]; + + var i,i0,i1,j,J,j0,j1,k,l,l0,l1,a; + i0 = Bi[I]; + i1 = Bi[I+1]; + xj.length = 0; + for(i=i0;i a) { e = k; a = c; } + } + if(abs(x[i])= k11) { + xj[n] = Pinv[j[m]]; + if(m===0) return; + ++n; + --m; + km = k[m]; + k11 = k1[m]; + } else { + foo = Aj[km]; + if(x[foo] === 0) { + x[foo] = 1; + k[m] = km; + ++m; + j[m] = foo; + foo = Pinv[foo]; + km = Ai[foo]; + k1[m] = k11 = Ai[foo+1]; + } else ++km; + } + } +} +numeric.ccsLPSolve0 = function ccsLPSolve0(A,B,y,xj,I,Pinv,P,dfs) { + var Ai = A[0], Aj = A[1], Av = A[2],m = Ai.length-1, n=0; + var Bi = B[0], Bj = B[1], Bv = B[2]; + + var i,i0,i1,j,J,j0,j1,k,l,l0,l1,a; + i0 = Bi[I]; + i1 = Bi[I+1]; + xj.length = 0; + for(i=i0;i a) { e = k; a = c; } + } + if(abs(y[P[i]]) ret[k]) ret[k] = A.length; + var i; + for(i in A) { + if(A.hasOwnProperty(i)) dim(A[i],ret,k+1); + } + return ret; +}; + +numeric.sclone = function clone(A,k,n) { + if(typeof k === "undefined") { k=0; } + if(typeof n === "undefined") { n = numeric.sdim(A).length; } + var i,ret = Array(A.length); + if(k === n-1) { + for(i in A) { if(A.hasOwnProperty(i)) ret[i] = A[i]; } + return ret; + } + for(i in A) { + if(A.hasOwnProperty(i)) ret[i] = clone(A[i],k+1,n); + } + return ret; +} + +numeric.sdiag = function diag(d) { + var n = d.length,i,ret = Array(n),i1,i2,i3; + for(i=n-1;i>=1;i-=2) { + i1 = i-1; + ret[i] = []; ret[i][i] = d[i]; + ret[i1] = []; ret[i1][i1] = d[i1]; + } + if(i===0) { ret[0] = []; ret[0][0] = d[i]; } + return ret; +} + +numeric.sidentity = function identity(n) { return numeric.sdiag(numeric.rep([n],1)); } + +numeric.stranspose = function transpose(A) { + var ret = [], n = A.length, i,j,Ai; + for(i in A) { + if(!(A.hasOwnProperty(i))) continue; + Ai = A[i]; + for(j in Ai) { + if(!(Ai.hasOwnProperty(j))) continue; + if(typeof ret[j] !== "object") { ret[j] = []; } + ret[j][i] = Ai[j]; + } + } + return ret; +} + +numeric.sLUP = function LUP(A,tol) { + throw new Error("The function numeric.sLUP had a bug in it and has been removed. Please use the new numeric.ccsLUP function instead."); +}; + +numeric.sdotMM = function dotMM(A,B) { + var p = A.length, q = B.length, BT = numeric.stranspose(B), r = BT.length, Ai, BTk; + var i,j,k,accum; + var ret = Array(p),reti; + for(i=p-1;i>=0;i--) { + reti = []; + Ai = A[i]; + for(k=r-1;k>=0;k--) { + accum = 0; + BTk = BT[k]; + for(j in Ai) { + if(!(Ai.hasOwnProperty(j))) continue; + if(j in BTk) { accum += Ai[j]*BTk[j]; } + } + if(accum) reti[k] = accum; + } + ret[i] = reti; + } + return ret; +} + +numeric.sdotMV = function dotMV(A,x) { + var p = A.length, Ai, i,j; + var ret = Array(p), accum; + for(i=p-1;i>=0;i--) { + Ai = A[i]; + accum = 0; + for(j in Ai) { + if(!(Ai.hasOwnProperty(j))) continue; + if(x[j]) accum += Ai[j]*x[j]; + } + if(accum) ret[i] = accum; + } + return ret; +} + +numeric.sdotVM = function dotMV(x,A) { + var i,j,Ai,alpha; + var ret = [], accum; + for(i in x) { + if(!x.hasOwnProperty(i)) continue; + Ai = A[i]; + alpha = x[i]; + for(j in Ai) { + if(!Ai.hasOwnProperty(j)) continue; + if(!ret[j]) { ret[j] = 0; } + ret[j] += alpha*Ai[j]; + } + } + return ret; +} + +numeric.sdotVV = function dotVV(x,y) { + var i,ret=0; + for(i in x) { if(x[i] && y[i]) ret+= x[i]*y[i]; } + return ret; +} + +numeric.sdot = function dot(A,B) { + var m = numeric.sdim(A).length, n = numeric.sdim(B).length; + var k = m*1000+n; + switch(k) { + case 0: return A*B; + case 1001: return numeric.sdotVV(A,B); + case 2001: return numeric.sdotMV(A,B); + case 1002: return numeric.sdotVM(A,B); + case 2002: return numeric.sdotMM(A,B); + default: throw new Error('numeric.sdot not implemented for tensors of order '+m+' and '+n); + } +} + +numeric.sscatter = function scatter(V) { + var n = V[0].length, Vij, i, j, m = V.length, A = [], Aj; + for(i=n-1;i>=0;--i) { + if(!V[m-1][i]) continue; + Aj = A; + for(j=0;j=0;--i) ret[i] = []; + } + for(i=n;i>=0;--i) ret[i].push(k[i]); + ret[n+1].push(Ai); + } + } else gather(Ai,ret,k); + } + } + if(k.length>n) k.pop(); + return ret; +} + +// 6. Coordinate matrices +numeric.cLU = function LU(A) { + var I = A[0], J = A[1], V = A[2]; + var p = I.length, m=0, i,j,k,a,b,c; + for(i=0;im) m=I[i]; + m++; + var L = Array(m), U = Array(m), left = numeric.rep([m],Infinity), right = numeric.rep([m],-Infinity); + var Ui, Uj,alpha; + for(k=0;kright[i]) right[i] = j; + } + for(i=0;i right[i+1]) right[i+1] = right[i]; } + for(i=m-1;i>=1;i--) { if(left[i]=0;i--) { + while(Uj[k] > i) { + ret[i] -= Uv[k]*ret[Uj[k]]; + k--; + } + ret[i] /= Uv[k]; + k--; + } + return ret; +}; + +numeric.cgrid = function grid(n,shape) { + if(typeof n === "number") n = [n,n]; + var ret = numeric.rep(n,-1); + var i,j,count; + if(typeof shape !== "function") { + switch(shape) { + case 'L': + shape = function(i,j) { return (i>=n[0]/2 || jN) N = Ai[k]; } + N++; + ret = numeric.rep([N],0); + for(k=0;k1) { + mid = floor((p+q)/2); + if(x[mid] <= x0) p = mid; + else q = mid; + } + return this._at(x0,p); + } + var n = x0.length, i, ret = Array(n); + for(i=n-1;i!==-1;--i) ret[i] = this.at(x0[i]); + return ret; +} +numeric.Spline.prototype.diff = function diff() { + var x = this.x; + var yl = this.yl; + var yr = this.yr; + var kl = this.kl; + var kr = this.kr; + var n = yl.length; + var i,dx,dy; + var zl = kl, zr = kr, pl = Array(n), pr = Array(n); + var add = numeric.add, mul = numeric.mul, div = numeric.div, sub = numeric.sub; + for(i=n-1;i!==-1;--i) { + dx = x[i+1]-x[i]; + dy = sub(yr[i+1],yl[i]); + pl[i] = div(add(mul(dy, 6),mul(kl[i],-4*dx),mul(kr[i+1],-2*dx)),dx*dx); + pr[i+1] = div(add(mul(dy,-6),mul(kl[i], 2*dx),mul(kr[i+1], 4*dx)),dx*dx); + } + return new numeric.Spline(x,zl,zr,pl,pr); +} +numeric.Spline.prototype.roots = function roots() { + function sqr(x) { return x*x; } + function heval(y0,y1,k0,k1,x) { + var A = k0*2-(y1-y0); + var B = -k1*2+(y1-y0); + var t = (x+1)*0.5; + var s = t*(1-t); + return (1-t)*y0+t*y1+A*s*(1-t)+B*s*t; + } + var ret = []; + var x = this.x, yl = this.yl, yr = this.yr, kl = this.kl, kr = this.kr; + if(typeof yl[0] === "number") { + yl = [yl]; + yr = [yr]; + kl = [kl]; + kr = [kr]; + } + var m = yl.length,n=x.length-1,i,j,k,y,s,t; + var ai,bi,ci,di, ret = Array(m),ri,k0,k1,y0,y1,A,B,D,dx,cx,stops,z0,z1,zm,t0,t1,tm; + var sqrt = Math.sqrt; + for(i=0;i!==m;++i) { + ai = yl[i]; + bi = yr[i]; + ci = kl[i]; + di = kr[i]; + ri = []; + for(j=0;j!==n;j++) { + if(j>0 && bi[j]*ai[j]<0) ri.push(x[j]); + dx = (x[j+1]-x[j]); + cx = x[j]; + y0 = ai[j]; + y1 = bi[j+1]; + k0 = ci[j]/dx; + k1 = di[j+1]/dx; + D = sqr(k0-k1+3*(y0-y1)) + 12*k1*y0; + A = k1+3*y0+2*k0-3*y1; + B = 3*(k1+k0+2*(y0-y1)); + if(D<=0) { + z0 = A/B; + if(z0>x[j] && z0x[j] && z0x[j] && z10) { + t0 = t1; + z0 = z1; + continue; + } + var side = 0; + while(1) { + tm = (z0*t1-z1*t0)/(z0-z1); + if(tm <= t0 || tm >= t1) { break; } + zm = this._at(tm,j); + if(zm*z1>0) { + t1 = tm; + z1 = zm; + if(side === -1) z0*=0.5; + side = -1; + } else if(zm*z0>0) { + t0 = tm; + z0 = zm; + if(side === 1) z1*=0.5; + side = 1; + } else break; + } + ri.push(tm); + t0 = stops[k+1]; + z0 = this._at(t0, j); + } + if(z1 === 0) ri.push(t1); + } + ret[i] = ri; + } + if(typeof this.yl[0] === "number") return ret[0]; + return ret; +} +numeric.spline = function spline(x,y,k1,kn) { + var n = x.length, b = [], dx = [], dy = []; + var i; + var sub = numeric.sub,mul = numeric.mul,add = numeric.add; + for(i=n-2;i>=0;i--) { dx[i] = x[i+1]-x[i]; dy[i] = sub(y[i+1],y[i]); } + if(typeof k1 === "string" || typeof kn === "string") { + k1 = kn = "periodic"; + } + // Build sparse tridiagonal system + var T = [[],[],[]]; + switch(typeof k1) { + case "undefined": + b[0] = mul(3/(dx[0]*dx[0]),dy[0]); + T[0].push(0,0); + T[1].push(0,1); + T[2].push(2/dx[0],1/dx[0]); + break; + case "string": + b[0] = add(mul(3/(dx[n-2]*dx[n-2]),dy[n-2]),mul(3/(dx[0]*dx[0]),dy[0])); + T[0].push(0,0,0); + T[1].push(n-2,0,1); + T[2].push(1/dx[n-2],2/dx[n-2]+2/dx[0],1/dx[0]); + break; + default: + b[0] = k1; + T[0].push(0); + T[1].push(0); + T[2].push(1); + break; + } + for(i=1;i20) { throw new Error("Numerical gradient fails"); } + x0[i] = x[i]+h; + f1 = f(x0); + x0[i] = x[i]-h; + f2 = f(x0); + x0[i] = x[i]; + if(isNaN(f1) || isNaN(f2)) { h/=16; continue; } + J[i] = (f1-f2)/(2*h); + t0 = x[i]-h; + t1 = x[i]; + t2 = x[i]+h; + d1 = (f1-f0)/h; + d2 = (f0-f2)/h; + N = max(abs(J[i]),abs(f0),abs(f1),abs(f2),abs(t0),abs(t1),abs(t2),1e-8); + errest = min(max(abs(d1-J[i]),abs(d2-J[i]),abs(d1-d2))/N,h/N); + if(errest>eps) { h/=16; } + else break; + } + } + return J; +} + +numeric.uncmin = function uncmin(f,x0,tol,gradient,maxit,callback,options) { + var grad = numeric.gradient; + if(typeof options === "undefined") { options = {}; } + if(typeof tol === "undefined") { tol = 1e-8; } + if(typeof gradient === "undefined") { gradient = function(x) { return grad(f,x); }; } + if(typeof maxit === "undefined") maxit = 1000; + x0 = numeric.clone(x0); + var n = x0.length; + var f0 = f(x0),f1,df0; + if(isNaN(f0)) throw new Error('uncmin: f(x0) is a NaN!'); + var max = Math.max, norm2 = numeric.norm2; + tol = max(tol,numeric.epsilon); + var step,g0,g1,H1 = options.Hinv || numeric.identity(n); + var dot = numeric.dot, inv = numeric.inv, sub = numeric.sub, add = numeric.add, ten = numeric.tensor, div = numeric.div, mul = numeric.mul; + var all = numeric.all, isfinite = numeric.isFinite, neg = numeric.neg; + var it=0,i,s,x1,y,Hy,Hs,ys,i0,t,nstep,t1,t2; + var msg = ""; + g0 = gradient(x0); + while(it= 0.1*t*df0 || isNaN(f1)) { + t *= 0.5; + ++it; + continue; + } + break; + } + if(t*nstep < tol) { msg = "Line search step size smaller than tol"; break; } + if(it === maxit) { msg = "maxit reached during line search"; break; } + g1 = gradient(x1); + y = sub(g1,g0); + ys = dot(y,s); + Hy = dot(H1,y); + H1 = sub(add(H1, + mul( + (ys+dot(y,Hy))/(ys*ys), + ten(s,s) )), + div(add(ten(Hy,s),ten(s,Hy)),ys)); + x0 = x1; + f0 = f1; + g0 = g1; + ++it; + } + return {solution: x0, f: f0, gradient: g0, invHessian: H1, iterations:it, message: msg}; +} + +// 10. Ode solver (Dormand-Prince) +numeric.Dopri = function Dopri(x,y,f,ymid,iterations,msg,events) { + this.x = x; + this.y = y; + this.f = f; + this.ymid = ymid; + this.iterations = iterations; + this.events = events; + this.message = msg; +} +numeric.Dopri.prototype._at = function _at(xi,j) { + function sqr(x) { return x*x; } + var sol = this; + var xs = sol.x; + var ys = sol.y; + var k1 = sol.f; + var ymid = sol.ymid; + var n = xs.length; + var x0,x1,xh,y0,y1,yh,xi; + var floor = Math.floor,h; + var c = 0.5; + var add = numeric.add, mul = numeric.mul,sub = numeric.sub, p,q,w; + x0 = xs[j]; + x1 = xs[j+1]; + y0 = ys[j]; + y1 = ys[j+1]; + h = x1-x0; + xh = x0+c*h; + yh = ymid[j]; + p = sub(k1[j ],mul(y0,1/(x0-xh)+2/(x0-x1))); + q = sub(k1[j+1],mul(y1,1/(x1-xh)+2/(x1-x0))); + w = [sqr(xi - x1) * (xi - xh) / sqr(x0 - x1) / (x0 - xh), + sqr(xi - x0) * sqr(xi - x1) / sqr(x0 - xh) / sqr(x1 - xh), + sqr(xi - x0) * (xi - xh) / sqr(x1 - x0) / (x1 - xh), + (xi - x0) * sqr(xi - x1) * (xi - xh) / sqr(x0-x1) / (x0 - xh), + (xi - x1) * sqr(xi - x0) * (xi - xh) / sqr(x0-x1) / (x1 - xh)]; + return add(add(add(add(mul(y0,w[0]), + mul(yh,w[1])), + mul(y1,w[2])), + mul( p,w[3])), + mul( q,w[4])); +} +numeric.Dopri.prototype.at = function at(x) { + var i,j,k,floor = Math.floor; + if(typeof x !== "number") { + var n = x.length, ret = Array(n); + for(i=n-1;i!==-1;--i) { + ret[i] = this.at(x[i]); + } + return ret; + } + var x0 = this.x; + i = 0; j = x0.length-1; + while(j-i>1) { + k = floor(0.5*(i+j)); + if(x0[k] <= x) i = k; + else j = k; + } + return this._at(x,i); +} + +numeric.dopri = function dopri(x0,x1,y0,f,tol,maxit,event) { + if(typeof tol === "undefined") { tol = 1e-6; } + if(typeof maxit === "undefined") { maxit = 1000; } + var xs = [x0], ys = [y0], k1 = [f(x0,y0)], k2,k3,k4,k5,k6,k7, ymid = []; + var A2 = 1/5; + var A3 = [3/40,9/40]; + var A4 = [44/45,-56/15,32/9]; + var A5 = [19372/6561,-25360/2187,64448/6561,-212/729]; + var A6 = [9017/3168,-355/33,46732/5247,49/176,-5103/18656]; + var b = [35/384,0,500/1113,125/192,-2187/6784,11/84]; + var bm = [0.5*6025192743/30085553152, + 0, + 0.5*51252292925/65400821598, + 0.5*-2691868925/45128329728, + 0.5*187940372067/1594534317056, + 0.5*-1776094331/19743644256, + 0.5*11237099/235043384]; + var c = [1/5,3/10,4/5,8/9,1,1]; + var e = [-71/57600,0,71/16695,-71/1920,17253/339200,-22/525,1/40]; + var i = 0,er,j; + var h = (x1-x0)/10; + var it = 0; + var add = numeric.add, mul = numeric.mul, y1,erinf; + var max = Math.max, min = Math.min, abs = Math.abs, norminf = numeric.norminf,pow = Math.pow; + var any = numeric.any, lt = numeric.lt, and = numeric.and, sub = numeric.sub; + var e0, e1, ev; + var ret = new numeric.Dopri(xs,ys,k1,ymid,-1,""); + if(typeof event === "function") e0 = event(x0,y0); + while(x0x1) h = x1-x0; + k2 = f(x0+c[0]*h, add(y0,mul( A2*h,k1[i]))); + k3 = f(x0+c[1]*h, add(add(y0,mul(A3[0]*h,k1[i])),mul(A3[1]*h,k2))); + k4 = f(x0+c[2]*h, add(add(add(y0,mul(A4[0]*h,k1[i])),mul(A4[1]*h,k2)),mul(A4[2]*h,k3))); + k5 = f(x0+c[3]*h, add(add(add(add(y0,mul(A5[0]*h,k1[i])),mul(A5[1]*h,k2)),mul(A5[2]*h,k3)),mul(A5[3]*h,k4))); + k6 = f(x0+c[4]*h,add(add(add(add(add(y0,mul(A6[0]*h,k1[i])),mul(A6[1]*h,k2)),mul(A6[2]*h,k3)),mul(A6[3]*h,k4)),mul(A6[4]*h,k5))); + y1 = add(add(add(add(add(y0,mul(k1[i],h*b[0])),mul(k3,h*b[2])),mul(k4,h*b[3])),mul(k5,h*b[4])),mul(k6,h*b[5])); + k7 = f(x0+h,y1); + er = add(add(add(add(add(mul(k1[i],h*e[0]),mul(k3,h*e[2])),mul(k4,h*e[3])),mul(k5,h*e[4])),mul(k6,h*e[5])),mul(k7,h*e[6])); + if(typeof er === "number") erinf = abs(er); + else erinf = norminf(er); + if(erinf > tol) { // reject + h = 0.2*h*pow(tol/erinf,0.25); + if(x0+h === x0) { + ret.msg = "Step size became too small"; + break; + } + continue; + } + ymid[i] = add(add(add(add(add(add(y0, + mul(k1[i],h*bm[0])), + mul(k3 ,h*bm[2])), + mul(k4 ,h*bm[3])), + mul(k5 ,h*bm[4])), + mul(k6 ,h*bm[5])), + mul(k7 ,h*bm[6])); + ++i; + xs[i] = x0+h; + ys[i] = y1; + k1[i] = k7; + if(typeof event === "function") { + var yi,xl = x0,xr = x0+0.5*h,xi; + e1 = event(xr,ymid[i-1]); + ev = and(lt(e0,0),lt(0,e1)); + if(!any(ev)) { xl = xr; xr = x0+h; e0 = e1; e1 = event(xr,y1); ev = and(lt(e0,0),lt(0,e1)); } + if(any(ev)) { + var xc, yc, en,ei; + var side=0, sl = 1.0, sr = 1.0; + while(1) { + if(typeof e0 === "number") xi = (sr*e1*xl-sl*e0*xr)/(sr*e1-sl*e0); + else { + xi = xr; + for(j=e0.length-1;j!==-1;--j) { + if(e0[j]<0 && e1[j]>0) xi = min(xi,(sr*e1[j]*xl-sl*e0[j]*xr)/(sr*e1[j]-sl*e0[j])); + } + } + if(xi <= xl || xi >= xr) break; + yi = ret._at(xi, i-1); + ei = event(xi,yi); + en = and(lt(e0,0),lt(0,ei)); + if(any(en)) { + xr = xi; + e1 = ei; + ev = en; + sr = 1.0; + if(side === -1) sl *= 0.5; + else sl = 1.0; + side = -1; + } else { + xl = xi; + e0 = ei; + sl = 1.0; + if(side === 1) sr *= 0.5; + else sr = 1.0; + side = 1; + } + } + y1 = ret._at(0.5*(x0+xi),i-1); + ret.f[i] = f(xi,yi); + ret.x[i] = xi; + ret.y[i] = yi; + ret.ymid[i-1] = y1; + ret.events = ev; + ret.iterations = it; + return ret; + } + } + x0 += h; + y0 = y1; + e0 = e1; + h = min(0.8*h*pow(tol/erinf,0.25),4*h); + } + ret.iterations = it; + return ret; +} + +// 11. Ax = b +numeric.LU = function(A, fast) { + fast = fast || false; + + var abs = Math.abs; + var i, j, k, absAjk, Akk, Ak, Pk, Ai; + var max; + var n = A.length, n1 = n-1; + var P = new Array(n); + if(!fast) A = numeric.clone(A); + + for (k = 0; k < n; ++k) { + Pk = k; + Ak = A[k]; + max = abs(Ak[k]); + for (j = k + 1; j < n; ++j) { + absAjk = abs(A[j][k]); + if (max < absAjk) { + max = absAjk; + Pk = j; + } + } + P[k] = Pk; + + if (Pk != k) { + A[k] = A[Pk]; + A[Pk] = Ak; + Ak = A[k]; + } + + Akk = Ak[k]; + + for (i = k + 1; i < n; ++i) { + A[i][k] /= Akk; + } + + for (i = k + 1; i < n; ++i) { + Ai = A[i]; + for (j = k + 1; j < n1; ++j) { + Ai[j] -= Ai[k] * Ak[j]; + ++j; + Ai[j] -= Ai[k] * Ak[j]; + } + if(j===n1) Ai[j] -= Ai[k] * Ak[j]; + } + } + + return { + LU: A, + P: P + }; +} + +numeric.LUsolve = function LUsolve(LUP, b) { + var i, j; + var LU = LUP.LU; + var n = LU.length; + var x = numeric.clone(b); + var P = LUP.P; + var Pi, LUi, LUii, tmp; + + for (i=n-1;i!==-1;--i) x[i] = b[i]; + for (i = 0; i < n; ++i) { + Pi = P[i]; + if (P[i] !== i) { + tmp = x[i]; + x[i] = x[Pi]; + x[Pi] = tmp; + } + + LUi = LU[i]; + for (j = 0; j < i; ++j) { + x[i] -= x[j] * LUi[j]; + } + } + + for (i = n - 1; i >= 0; --i) { + LUi = LU[i]; + for (j = i + 1; j < n; ++j) { + x[i] -= x[j] * LUi[j]; + } + + x[i] /= LUi[i]; + } + + return x; +} + +numeric.solve = function solve(A,b,fast) { return numeric.LUsolve(numeric.LU(A,fast), b); } + +// 12. Linear programming +numeric.echelonize = function echelonize(A) { + var s = numeric.dim(A), m = s[0], n = s[1]; + var I = numeric.identity(m); + var P = Array(m); + var i,j,k,l,Ai,Ii,Z,a; + var abs = Math.abs; + var diveq = numeric.diveq; + A = numeric.clone(A); + for(i=0;ia1) alpha = a1; + g = add(c,mul(alpha,p)); + H = dot(A1,A0); + for(i=m-1;i!==-1;--i) H[i][i] += 1; + d = solve(H,div(g,alpha),true); + var t0 = div(z,dot(A,d)); + var t = 1.0; + for(i=n-1;i!==-1;--i) if(t0[i]<0) t = min(t,-0.999*t0[i]); + y = sub(x,mul(d,t)); + z = sub(b,dot(A,y)); + if(!all(gt(z,0))) return { solution: x, message: "", iterations: count }; + x = y; + if(alpha=0) unbounded = false; + else unbounded = true; + } + if(unbounded) return { solution: y, message: "Unbounded", iterations: count }; + } + return { solution: x, message: "maximum iteration count exceeded", iterations:count }; +} + +numeric._solveLP = function _solveLP(c,A,b,tol,maxit) { + var m = c.length, n = b.length,y; + var sum = numeric.sum, log = numeric.log, mul = numeric.mul, sub = numeric.sub, dot = numeric.dot, div = numeric.div, add = numeric.add; + var c0 = numeric.rep([m],0).concat([1]); + var J = numeric.rep([n,1],-1); + var A0 = numeric.blockMatrix([[A , J ]]); + var b0 = b; + var y = numeric.rep([m],0).concat(Math.max(0,numeric.sup(numeric.neg(b)))+1); + var x0 = numeric.__solveLP(c0,A0,b0,tol,maxit,y,false); + var x = numeric.clone(x0.solution); + x.length = m; + var foo = numeric.inf(sub(b,dot(A,x))); + if(foo<0) { return { solution: NaN, message: "Infeasible", iterations: x0.iterations }; } + var ret = numeric.__solveLP(c, A, b, tol, maxit-x0.iterations, x, true); + ret.iterations += x0.iterations; + return ret; +}; + +numeric.solveLP = function solveLP(c,A,b,Aeq,beq,tol,maxit) { + if(typeof maxit === "undefined") maxit = 1000; + if(typeof tol === "undefined") tol = numeric.epsilon; + if(typeof Aeq === "undefined") return numeric._solveLP(c,A,b,tol,maxit); + var m = Aeq.length, n = Aeq[0].length, o = A.length; + var B = numeric.echelonize(Aeq); + var flags = numeric.rep([n],0); + var P = B.P; + var Q = []; + var i; + for(i=P.length-1;i!==-1;--i) flags[P[i]] = 1; + for(i=n-1;i!==-1;--i) if(flags[i]===0) Q.push(i); + var g = numeric.getRange; + var I = numeric.linspace(0,m-1), J = numeric.linspace(0,o-1); + var Aeq2 = g(Aeq,I,Q), A1 = g(A,J,P), A2 = g(A,J,Q), dot = numeric.dot, sub = numeric.sub; + var A3 = dot(A1,B.I); + var A4 = sub(A2,dot(A3,Aeq2)), b4 = sub(b,dot(A3,beq)); + var c1 = Array(P.length), c2 = Array(Q.length); + for(i=P.length-1;i!==-1;--i) c1[i] = c[P[i]]; + for(i=Q.length-1;i!==-1;--i) c2[i] = c[Q[i]]; + var c4 = sub(c2,dot(c1,dot(B.I,Aeq2))); + var S = numeric._solveLP(c4,A4,b4,tol,maxit); + var x2 = S.solution; + if(x2!==x2) return S; + var x1 = dot(B.I,sub(beq,dot(Aeq2,x2))); + var x = Array(c.length); + for(i=P.length-1;i!==-1;--i) x[P[i]] = x1[i]; + for(i=Q.length-1;i!==-1;--i) x[Q[i]] = x2[i]; + return { solution: x, message:S.message, iterations: S.iterations }; +} + +numeric.MPStoLP = function MPStoLP(MPS) { + if(MPS instanceof String) { MPS.split('\n'); } + var state = 0; + var states = ['Initial state','NAME','ROWS','COLUMNS','RHS','BOUNDS','ENDATA']; + var n = MPS.length; + var i,j,z,N=0,rows = {}, sign = [], rl = 0, vars = {}, nv = 0; + var name; + var c = [], A = [], b = []; + function err(e) { throw new Error('MPStoLP: '+e+'\nLine '+i+': '+MPS[i]+'\nCurrent state: '+states[state]+'\n'); } + for(i=0;i +// +// Math.seedrandom('yipee'); Sets Math.random to a function that is +// initialized using the given explicit seed. +// +// Math.seedrandom(); Sets Math.random to a function that is +// seeded using the current time, dom state, +// and other accumulated local entropy. +// The generated seed string is returned. +// +// Math.seedrandom('yowza', true); +// Seeds using the given explicit seed mixed +// together with accumulated entropy. +// +// +// Seeds using physical random bits downloaded +// from random.org. +// +// Seeds using urandom bits from call.jsonlib.com, +// which is faster than random.org. +// +// Examples: +// +// Math.seedrandom("hello"); // Use "hello" as the seed. +// document.write(Math.random()); // Always 0.5463663768140734 +// document.write(Math.random()); // Always 0.43973793770592234 +// var rng1 = Math.random; // Remember the current prng. +// +// var autoseed = Math.seedrandom(); // New prng with an automatic seed. +// document.write(Math.random()); // Pretty much unpredictable. +// +// Math.random = rng1; // Continue "hello" prng sequence. +// document.write(Math.random()); // Always 0.554769432473455 +// +// Math.seedrandom(autoseed); // Restart at the previous seed. +// document.write(Math.random()); // Repeat the 'unpredictable' value. +// +// Notes: +// +// Each time seedrandom('arg') is called, entropy from the passed seed +// is accumulated in a pool to help generate future seeds for the +// zero-argument form of Math.seedrandom, so entropy can be injected over +// time by calling seedrandom with explicit data repeatedly. +// +// On speed - This javascript implementation of Math.random() is about +// 3-10x slower than the built-in Math.random() because it is not native +// code, but this is typically fast enough anyway. Seeding is more expensive, +// especially if you use auto-seeding. Some details (timings on Chrome 4): +// +// Our Math.random() - avg less than 0.002 milliseconds per call +// seedrandom('explicit') - avg less than 0.5 milliseconds per call +// seedrandom('explicit', true) - avg less than 2 milliseconds per call +// seedrandom() - avg about 38 milliseconds per call +// +// LICENSE (BSD): +// +// Copyright 2010 David Bau, all rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// 2. 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. +// +// 3. Neither the name of this module 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. +// +/** + * All code is in an anonymous closure to keep the global namespace clean. + * + * @param {number=} overflow + * @param {number=} startdenom + */ + +// Patched by Seb so that seedrandom.js does not pollute the Math object. +// My tests suggest that doing Math.trouble = 1 makes Math lookups about 5% +// slower. +numeric.seedrandom = { pow:Math.pow, random:Math.random }; + +(function (pool, math, width, chunks, significance, overflow, startdenom) { + + +// +// seedrandom() +// This is the seedrandom function described above. +// +math['seedrandom'] = function seedrandom(seed, use_entropy) { + var key = []; + var arc4; + + // Flatten the seed string or build one from local entropy if needed. + seed = mixkey(flatten( + use_entropy ? [seed, pool] : + arguments.length ? seed : + [new Date().getTime(), pool, window], 3), key); + + // Use the seed to initialize an ARC4 generator. + arc4 = new ARC4(key); + + // Mix the randomness into accumulated entropy. + mixkey(arc4.S, pool); + + // Override Math.random + + // This function returns a random double in [0, 1) that contains + // randomness in every bit of the mantissa of the IEEE 754 value. + + math['random'] = function random() { // Closure to return a random double: + var n = arc4.g(chunks); // Start with a numerator n < 2 ^ 48 + var d = startdenom; // and denominator d = 2 ^ 48. + var x = 0; // and no 'extra last byte'. + while (n < significance) { // Fill up all significant digits by + n = (n + x) * width; // shifting numerator and + d *= width; // denominator and generating a + x = arc4.g(1); // new least-significant-byte. + } + while (n >= overflow) { // To avoid rounding up, before adding + n /= 2; // last byte, shift everything + d /= 2; // right using integer math until + x >>>= 1; // we have exactly the desired bits. + } + return (n + x) / d; // Form the number within [0, 1). + }; + + // Return the seed that was used + return seed; +}; + +// +// ARC4 +// +// An ARC4 implementation. The constructor takes a key in the form of +// an array of at most (width) integers that should be 0 <= x < (width). +// +// The g(count) method returns a pseudorandom integer that concatenates +// the next (count) outputs from ARC4. Its return value is a number x +// that is in the range 0 <= x < (width ^ count). +// +/** @constructor */ +function ARC4(key) { + var t, u, me = this, keylen = key.length; + var i = 0, j = me.i = me.j = me.m = 0; + me.S = []; + me.c = []; + + // The empty key [] is treated as [0]. + if (!keylen) { key = [keylen++]; } + + // Set up S using the standard key scheduling algorithm. + while (i < width) { me.S[i] = i++; } + for (i = 0; i < width; i++) { + t = me.S[i]; + j = lowbits(j + t + key[i % keylen]); + u = me.S[j]; + me.S[i] = u; + me.S[j] = t; + } + + // The "g" method returns the next (count) outputs as one number. + me.g = function getnext(count) { + var s = me.S; + var i = lowbits(me.i + 1); var t = s[i]; + var j = lowbits(me.j + t); var u = s[j]; + s[i] = u; + s[j] = t; + var r = s[lowbits(t + u)]; + while (--count) { + i = lowbits(i + 1); t = s[i]; + j = lowbits(j + t); u = s[j]; + s[i] = u; + s[j] = t; + r = r * width + s[lowbits(t + u)]; + } + me.i = i; + me.j = j; + return r; + }; + // For robust unpredictability discard an initial batch of values. + // See http://www.rsa.com/rsalabs/node.asp?id=2009 + me.g(width); +} + +// +// flatten() +// Converts an object tree to nested arrays of strings. +// +/** @param {Object=} result + * @param {string=} prop + * @param {string=} typ */ +function flatten(obj, depth, result, prop, typ) { + result = []; + typ = typeof(obj); + if (depth && typ == 'object') { + for (prop in obj) { + if (prop.indexOf('S') < 5) { // Avoid FF3 bug (local/sessionStorage) + try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {} + } + } + } + return (result.length ? result : obj + (typ != 'string' ? '\0' : '')); +} + +// +// mixkey() +// Mixes a string seed into a key that is an array of integers, and +// returns a shortened string seed that is equivalent to the result key. +// +/** @param {number=} smear + * @param {number=} j */ +function mixkey(seed, key, smear, j) { + seed += ''; // Ensure the seed is a string + smear = 0; + for (j = 0; j < seed.length; j++) { + key[lowbits(j)] = + lowbits((smear ^= key[lowbits(j)] * 19) + seed.charCodeAt(j)); + } + seed = ''; + for (j in key) { seed += String.fromCharCode(key[j]); } + return seed; +} + +// +// lowbits() +// A quick "n mod width" for width a power of 2. +// +function lowbits(n) { return n & (width - 1); } + +// +// The following constants are related to IEEE 754 limits. +// +startdenom = math.pow(width, chunks); +significance = math.pow(2, significance); +overflow = significance * 2; + +// +// When seedrandom.js is loaded, we immediately mix a few bits +// from the built-in RNG into the entropy pool. Because we do +// not want to intefere with determinstic PRNG state later, +// seedrandom will not call math.random on its own again after +// initialization. +// +mixkey(math.random(), pool); + +// End anonymous scope, and pass initial values. +}( + [], // pool: entropy pool starts empty + numeric.seedrandom, // math: package containing random, pow, and seedrandom + 256, // width: each RC4 output is 0 <= x < 256 + 6, // chunks: at least six RC4 outputs for each double + 52 // significance: there are 52 significant digits in a double + )); +/* This file is a slightly modified version of quadprog.js from Alberto Santini. + * It has been slightly modified by Sébastien Loisel to make sure that it handles + * 0-based Arrays instead of 1-based Arrays. + * License is in resources/LICENSE.quadprog */ +(function(exports) { + +function base0to1(A) { + if(typeof A !== "object") { return A; } + var ret = [], i,n=A.length; + for(i=0;i meq) { + work[l] = sum; + } else { + work[l] = -Math.abs(sum); + if (sum > 0) { + for (j = 1; j <= n; j = j + 1) { + amat[j][i] = -amat[j][i]; + } + bvec[i] = -bvec[i]; + } + } + } + + for (i = 1; i <= nact; i = i + 1) { + work[iwsv + iact[i]] = 0; + } + + nvl = 0; + temp = 0; + for (i = 1; i <= q; i = i + 1) { + if (work[iwsv + i] < temp * work[iwnbv + i]) { + nvl = i; + temp = work[iwsv + i] / work[iwnbv + i]; + } + } + if (nvl === 0) { + return 999; + } + + return 0; + } + + function fn_goto_55() { + for (i = 1; i <= n; i = i + 1) { + sum = 0; + for (j = 1; j <= n; j = j + 1) { + sum = sum + dmat[j][i] * amat[j][nvl]; + } + work[i] = sum; + } + + l1 = iwzv; + for (i = 1; i <= n; i = i + 1) { + work[l1 + i] = 0; + } + for (j = nact + 1; j <= n; j = j + 1) { + for (i = 1; i <= n; i = i + 1) { + work[l1 + i] = work[l1 + i] + dmat[i][j] * work[j]; + } + } + + t1inf = true; + for (i = nact; i >= 1; i = i - 1) { + sum = work[i]; + l = iwrm + (i * (i + 3)) / 2; + l1 = l - i; + for (j = i + 1; j <= nact; j = j + 1) { + sum = sum - work[l] * work[iwrv + j]; + l = l + j; + } + sum = sum / work[l1]; + work[iwrv + i] = sum; + if (iact[i] < meq) { + // continue; + break; + } + if (sum < 0) { + // continue; + break; + } + t1inf = false; + it1 = i; + } + + if (!t1inf) { + t1 = work[iwuv + it1] / work[iwrv + it1]; + for (i = 1; i <= nact; i = i + 1) { + if (iact[i] < meq) { + // continue; + break; + } + if (work[iwrv + i] < 0) { + // continue; + break; + } + temp = work[iwuv + i] / work[iwrv + i]; + if (temp < t1) { + t1 = temp; + it1 = i; + } + } + } + + sum = 0; + for (i = iwzv + 1; i <= iwzv + n; i = i + 1) { + sum = sum + work[i] * work[i]; + } + if (Math.abs(sum) <= vsmall) { + if (t1inf) { + ierr[1] = 1; + // GOTO 999 + return 999; + } else { + for (i = 1; i <= nact; i = i + 1) { + work[iwuv + i] = work[iwuv + i] - t1 * work[iwrv + i]; + } + work[iwuv + nact + 1] = work[iwuv + nact + 1] + t1; + // GOTO 700 + return 700; + } + } else { + sum = 0; + for (i = 1; i <= n; i = i + 1) { + sum = sum + work[iwzv + i] * amat[i][nvl]; + } + tt = -work[iwsv + nvl] / sum; + t2min = true; + if (!t1inf) { + if (t1 < tt) { + tt = t1; + t2min = false; + } + } + + for (i = 1; i <= n; i = i + 1) { + sol[i] = sol[i] + tt * work[iwzv + i]; + if (Math.abs(sol[i]) < vsmall) { + sol[i] = 0; + } + } + + crval[1] = crval[1] + tt * sum * (tt / 2 + work[iwuv + nact + 1]); + for (i = 1; i <= nact; i = i + 1) { + work[iwuv + i] = work[iwuv + i] - tt * work[iwrv + i]; + } + work[iwuv + nact + 1] = work[iwuv + nact + 1] + tt; + + if (t2min) { + nact = nact + 1; + iact[nact] = nvl; + + l = iwrm + ((nact - 1) * nact) / 2 + 1; + for (i = 1; i <= nact - 1; i = i + 1) { + work[l] = work[i]; + l = l + 1; + } + + if (nact === n) { + work[l] = work[n]; + } else { + for (i = n; i >= nact + 1; i = i - 1) { + if (work[i] === 0) { + // continue; + break; + } + gc = Math.max(Math.abs(work[i - 1]), Math.abs(work[i])); + gs = Math.min(Math.abs(work[i - 1]), Math.abs(work[i])); + if (work[i - 1] >= 0) { + temp = Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc))); + } else { + temp = -Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc))); + } + gc = work[i - 1] / temp; + gs = work[i] / temp; + + if (gc === 1) { + // continue; + break; + } + if (gc === 0) { + work[i - 1] = gs * temp; + for (j = 1; j <= n; j = j + 1) { + temp = dmat[j][i - 1]; + dmat[j][i - 1] = dmat[j][i]; + dmat[j][i] = temp; + } + } else { + work[i - 1] = temp; + nu = gs / (1 + gc); + for (j = 1; j <= n; j = j + 1) { + temp = gc * dmat[j][i - 1] + gs * dmat[j][i]; + dmat[j][i] = nu * (dmat[j][i - 1] + temp) - dmat[j][i]; + dmat[j][i - 1] = temp; + + } + } + } + work[l] = work[nact]; + } + } else { + sum = -bvec[nvl]; + for (j = 1; j <= n; j = j + 1) { + sum = sum + sol[j] * amat[j][nvl]; + } + if (nvl > meq) { + work[iwsv + nvl] = sum; + } else { + work[iwsv + nvl] = -Math.abs(sum); + if (sum > 0) { + for (j = 1; j <= n; j = j + 1) { + amat[j][nvl] = -amat[j][nvl]; + } + bvec[nvl] = -bvec[nvl]; + } + } + // GOTO 700 + return 700; + } + } + + return 0; + } + + function fn_goto_797() { + l = iwrm + (it1 * (it1 + 1)) / 2 + 1; + l1 = l + it1; + if (work[l1] === 0) { + // GOTO 798 + return 798; + } + gc = Math.max(Math.abs(work[l1 - 1]), Math.abs(work[l1])); + gs = Math.min(Math.abs(work[l1 - 1]), Math.abs(work[l1])); + if (work[l1 - 1] >= 0) { + temp = Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc))); + } else { + temp = -Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc))); + } + gc = work[l1 - 1] / temp; + gs = work[l1] / temp; + + if (gc === 1) { + // GOTO 798 + return 798; + } + if (gc === 0) { + for (i = it1 + 1; i <= nact; i = i + 1) { + temp = work[l1 - 1]; + work[l1 - 1] = work[l1]; + work[l1] = temp; + l1 = l1 + i; + } + for (i = 1; i <= n; i = i + 1) { + temp = dmat[i][it1]; + dmat[i][it1] = dmat[i][it1 + 1]; + dmat[i][it1 + 1] = temp; + } + } else { + nu = gs / (1 + gc); + for (i = it1 + 1; i <= nact; i = i + 1) { + temp = gc * work[l1 - 1] + gs * work[l1]; + work[l1] = nu * (work[l1 - 1] + temp) - work[l1]; + work[l1 - 1] = temp; + l1 = l1 + i; + } + for (i = 1; i <= n; i = i + 1) { + temp = gc * dmat[i][it1] + gs * dmat[i][it1 + 1]; + dmat[i][it1 + 1] = nu * (dmat[i][it1] + temp) - dmat[i][it1 + 1]; + dmat[i][it1] = temp; + } + } + + return 0; + } + + function fn_goto_798() { + l1 = l - it1; + for (i = 1; i <= it1; i = i + 1) { + work[l1] = work[l]; + l = l + 1; + l1 = l1 + 1; + } + + work[iwuv + it1] = work[iwuv + it1 + 1]; + iact[it1] = iact[it1 + 1]; + it1 = it1 + 1; + if (it1 < nact) { + // GOTO 797 + return 797; + } + + return 0; + } + + function fn_goto_799() { + work[iwuv + nact] = work[iwuv + nact + 1]; + work[iwuv + nact + 1] = 0; + iact[nact] = 0; + nact = nact - 1; + iter[2] = iter[2] + 1; + + return 0; + } + + go = 0; + while (true) { + go = fn_goto_50(); + if (go === 999) { + return; + } + while (true) { + go = fn_goto_55(); + if (go === 0) { + break; + } + if (go === 999) { + return; + } + if (go === 700) { + if (it1 === nact) { + fn_goto_799(); + } else { + while (true) { + fn_goto_797(); + go = fn_goto_798(); + if (go !== 797) { + break; + } + } + fn_goto_799(); + } + } + } + } + +} + +function solveQP(Dmat, dvec, Amat, bvec, meq, factorized) { + Dmat = base0to1(Dmat); + dvec = base0to1(dvec); + Amat = base0to1(Amat); + var i, n, q, + nact, r, + crval = [], iact = [], sol = [], work = [], iter = [], + message; + + meq = meq || 0; + factorized = factorized ? base0to1(factorized) : [undefined, 0]; + bvec = bvec ? base0to1(bvec) : []; + + // In Fortran the array index starts from 1 + n = Dmat.length - 1; + q = Amat[1].length - 1; + + if (!bvec) { + for (i = 1; i <= q; i = i + 1) { + bvec[i] = 0; + } + } + for (i = 1; i <= q; i = i + 1) { + iact[i] = 0; + } + nact = 0; + r = Math.min(n, q); + for (i = 1; i <= n; i = i + 1) { + sol[i] = 0; + } + crval[1] = 0; + for (i = 1; i <= (2 * n + (r * (r + 5)) / 2 + 2 * q + 1); i = i + 1) { + work[i] = 0; + } + for (i = 1; i <= 2; i = i + 1) { + iter[i] = 0; + } + + qpgen2(Dmat, dvec, n, n, sol, crval, Amat, + bvec, n, q, meq, iact, nact, iter, work, factorized); + + message = ""; + if (factorized[1] === 1) { + message = "constraints are inconsistent, no solution!"; + } + if (factorized[1] === 2) { + message = "matrix D in quadratic function is not positive definite!"; + } + + return { + solution: base1to0(sol), + value: base1to0(crval), + unconstrained_solution: base1to0(dvec), + iterations: base1to0(iter), + iact: base1to0(iact), + message: message + }; +} +exports.solveQP = solveQP; +}(numeric)); +/* +Shanti Rao sent me this routine by private email. I had to modify it +slightly to work on Arrays instead of using a Matrix object. +It is apparently translated from http://stitchpanorama.sourceforge.net/Python/svd.py +*/ + +numeric.svd= function svd(A) { + var temp; +//Compute the thin SVD from G. H. Golub and C. Reinsch, Numer. Math. 14, 403-420 (1970) + var prec= numeric.epsilon; //Math.pow(2,-52) // assumes double prec + var tolerance= 1.e-64/prec; + var itmax= 50; + var c=0; + var i=0; + var j=0; + var k=0; + var l=0; + + var u= numeric.clone(A); + var m= u.length; + + var n= u[0].length; + + if (m < n) throw "Need more rows than columns" + + var e = new Array(n); + var q = new Array(n); + for (i=0; i b) + return a*Math.sqrt(1.0+(b*b/a/a)) + else if (b == 0.0) + return a + return b*Math.sqrt(1.0+(a*a/b/b)) + } + + //Householder's reduction to bidiagonal form + + var f= 0.0; + var g= 0.0; + var h= 0.0; + var x= 0.0; + var y= 0.0; + var z= 0.0; + var s= 0.0; + + for (i=0; i < n; i++) + { + e[i]= g; + s= 0.0; + l= i+1; + for (j=i; j < m; j++) + s += (u[j][i]*u[j][i]); + if (s <= tolerance) + g= 0.0; + else + { + f= u[i][i]; + g= Math.sqrt(s); + if (f >= 0.0) g= -g; + h= f*g-s + u[i][i]=f-g; + for (j=l; j < n; j++) + { + s= 0.0 + for (k=i; k < m; k++) + s += u[k][i]*u[k][j] + f= s/h + for (k=i; k < m; k++) + u[k][j]+=f*u[k][i] + } + } + q[i]= g + s= 0.0 + for (j=l; j < n; j++) + s= s + u[i][j]*u[i][j] + if (s <= tolerance) + g= 0.0 + else + { + f= u[i][i+1] + g= Math.sqrt(s) + if (f >= 0.0) g= -g + h= f*g - s + u[i][i+1] = f-g; + for (j=l; j < n; j++) e[j]= u[i][j]/h + for (j=l; j < m; j++) + { + s=0.0 + for (k=l; k < n; k++) + s += (u[j][k]*u[i][k]) + for (k=l; k < n; k++) + u[j][k]+=s*e[k] + } + } + y= Math.abs(q[i])+Math.abs(e[i]) + if (y>x) + x=y + } + + // accumulation of right hand gtransformations + for (i=n-1; i != -1; i+= -1) + { + if (g != 0.0) + { + h= g*u[i][i+1] + for (j=l; j < n; j++) + v[j][i]=u[i][j]/h + for (j=l; j < n; j++) + { + s=0.0 + for (k=l; k < n; k++) + s += u[i][k]*v[k][j] + for (k=l; k < n; k++) + v[k][j]+=(s*v[k][i]) + } + } + for (j=l; j < n; j++) + { + v[i][j] = 0; + v[j][i] = 0; + } + v[i][i] = 1; + g= e[i] + l= i + } + + // accumulation of left hand transformations + for (i=n-1; i != -1; i+= -1) + { + l= i+1 + g= q[i] + for (j=l; j < n; j++) + u[i][j] = 0; + if (g != 0.0) + { + h= u[i][i]*g + for (j=l; j < n; j++) + { + s=0.0 + for (k=l; k < m; k++) s += u[k][i]*u[k][j]; + f= s/h + for (k=i; k < m; k++) u[k][j]+=f*u[k][i]; + } + for (j=i; j < m; j++) u[j][i] = u[j][i]/g; + } + else + for (j=i; j < m; j++) u[j][i] = 0; + u[i][i] += 1; + } + + // diagonalization of the bidiagonal form + prec= prec*x + for (k=n-1; k != -1; k+= -1) + { + for (var iteration=0; iteration < itmax; iteration++) + { // test f splitting + var test_convergence = false + for (l=k; l != -1; l+= -1) + { + if (Math.abs(e[l]) <= prec) + { test_convergence= true + break + } + if (Math.abs(q[l-1]) <= prec) + break + } + if (!test_convergence) + { // cancellation of e[l] if l>0 + c= 0.0 + s= 1.0 + var l1= l-1 + for (i =l; i= itmax-1) + throw 'Error: no convergence.' + // shift from bottom 2x2 minor + x= q[l] + y= q[k-1] + g= e[k-1] + h= e[k] + f= ((y-z)*(y+z)+(g-h)*(g+h))/(2.0*h*y) + g= pythag(f,1.0) + if (f < 0.0) + f= ((x-z)*(x+z)+h*(y/(f-g)-h))/x + else + f= ((x-z)*(x+z)+h*(y/(f+g)-h))/x + // next QR transformation + c= 1.0 + s= 1.0 + for (i=l+1; i< k+1; i++) + { + g= e[i] + y= q[i] + h= s*g + g= c*g + z= pythag(f,h) + e[i-1]= z + c= f/z + s= h/z + f= x*c+g*s + g= -x*s+g*c + h= y*s + y= y*c + for (j=0; j < n; j++) + { + x= v[j][i-1] + z= v[j][i] + v[j][i-1] = x*c+z*s + v[j][i] = -x*s+z*c + } + z= pythag(f,h) + q[i-1]= z + c= f/z + s= h/z + f= c*g+s*y + x= -s*g+c*y + for (j=0; j < m; j++) + { + y= u[j][i-1] + z= u[j][i] + u[j][i-1] = y*c+z*s + u[j][i] = -y*s+z*c + } + } + e[l]= 0.0 + e[k]= f + q[k]= x + } + } + + //vt= transpose(v) + //return (u,q,vt) + for (i=0;i= 0; j--) + { + if (q[j] < q[i]) + { + // writeln(i,'-',j) + c = q[j] + q[j] = q[i] + q[i] = c + for(k=0;k 1) { + x = p2.x; + y = p2.y; + + } else if (t > 0) { + x += dx * t; + y += dy * t; + } + } + + dx = p.x - x; + dy = p.y - y; + + return dx * dx + dy * dy; +} +// rest of the code doesn't care about point format + +// basic distance-based simplification +function simplifyRadialDist(points, sqTolerance) { + + var prevPoint = points[0], + newPoints = [prevPoint], + point; + + for (var i = 1, len = points.length; i < len; i++) { + point = points[i]; + + if (getSqDist(point, prevPoint) > sqTolerance) { + newPoints.push(point); + prevPoint = point; + } + } + + if (prevPoint !== point) newPoints.push(point); + + return newPoints; +} + +// simplification using optimized Douglas-Peucker algorithm with recursion elimination +function simplifyDouglasPeucker(points, sqTolerance) { + + var len = points.length, + MarkerArray = typeof Uint8Array !== 'undefined' ? Uint8Array : Array, + markers = new MarkerArray(len), + first = 0, + last = len - 1, + stack = [], + newPoints = [], + i, maxSqDist, sqDist, index; + + markers[first] = markers[last] = 1; + + while (last) { + + maxSqDist = 0; + + for (i = first + 1; i < last; i++) { + sqDist = getSqSegDist(points[i], points[first], points[last]); + + if (sqDist > maxSqDist) { + index = i; + maxSqDist = sqDist; + } + } + + if (maxSqDist > sqTolerance) { + markers[index] = 1; + stack.push(first, index, index, last); + } + + last = stack.pop(); + first = stack.pop(); + } + + for (i = 0; i < len; i++) { + if (markers[i]) newPoints.push(points[i]); + } + + return newPoints; +} + +// both algorithms combined for awesome performance +function simplify(points, tolerance, highestQuality) { + + var sqTolerance = tolerance !== undefined ? tolerance * tolerance : 1; + + points = highestQuality ? points : simplifyRadialDist(points, sqTolerance); + points = simplifyDouglasPeucker(points, sqTolerance); + + return points; +} + +// export as AMD module / Node module / browser or worker variable +if (typeof define === 'function' && define.amd) define(function() { return simplify; }); +else if (typeof module !== 'undefined') module.exports = simplify; +else if (typeof self !== 'undefined') self.simplify = simplify; +else window.simplify = simplify; + +})(); + +},{}],9:[function(require,module,exports){ +"use strict" + +module.exports = createKDTree +module.exports.deserialize = deserializeKDTree + +var ndarray = require("ndarray") +var ndselect = require("ndarray-select") +var pack = require("ndarray-pack") +var ops = require("ndarray-ops") +var ndscratch = require("ndarray-scratch") +var pool = require("typedarray-pool") +var inorderTree = require("inorder-tree-layout") +var bits = require("bit-twiddle") +var KDTHeap = require("./lib/heap.js") + +function KDTree(points, ids, n, d) { + this.points = points + this.ids = ids + this.dimension = d + this.length = n +} + +var proto = KDTree.prototype + +proto.serialize = function() { + if(this.length > 0) { + return { + p: Array.prototype.slice.call(this.points.data, 0, this.length*this.dimension), + i: Array.prototype.slice.call(this.ids, 0, this.length) + } + } else { + return { d: this.dimension } + } +} + +//Range query +proto.range = function kdtRangeQuery(lo, hi, visit) { + var n = this.length + if(n < 1) { + return + } + + //Check degenerate case + var d = this.dimension + for(var i=0; i 0) { + if(data[0] >= nearestD) { + break + } + + var idx = index[0] + var pidx = points.index(idx, 0) + var d2 = 0.0 + for(var i=0; i 0) { + if(data[0] >= nearestD) { + break + } + + var idx = index[0] + var pidx = points.index(idx, 0) + var d2 = 0.0 + for(var i=0; i= maxPoints) { + closestPoints.pop() + } + var pcount = closestPoints.count + cl_index[pcount] = idx + cl_data[pcount] = -d2 + closestPoints.push() + if(closestPoints.count >= maxPoints) { + nearestD = -cl_data[0] + } + } + + //Compute distance bounds for children + var k = bits.log2(idx+1)%d + var ds = 0 + for(var i=0; i=0; --i) { + result[i] = ids[cl_index[0]] + closestPoints.pop() + } + closestPoints.dispose() + + return result +} + +proto.dispose = function kdtDispose() { + pool.free(this.points.data) + pool.freeInt32(this.ids) + this.points = null + this.ids = null + this.length = 0 +} + +function createKDTree(points) { + var n, d, indexed + if(Array.isArray(points)) { + n = points.length + if(n === 0) { + return new KDTree(null, null, 0, 0) + } + d = points[0].length + indexed = ndarray(pool.mallocDouble(n*(d+1)), [n, d+1]) + pack(points, indexed.hi(n, d)) + } else { + n = points.shape[0] + d = points.shape[1] + + //Round up data type size + var type = points.dtype + if(type === "int8" || + type === "int16" || + type === "int32" ) { + type = "int32" + } else if(type === "uint8" || + type === "uint8_clamped" || + type === "buffer" || + type === "uint16" || + type === "uint32") { + type = "uint32" + } else if(type === "float32") { + type = "float32" + } else { + type = "float64" + } + indexed = ndarray(pool.malloc(n*(d+1)), [n, d+1]) + ops.assign(indexed.hi(n,d), points) + } + for(var i=0; i 1) { + var k = bits.log2(pointer+1)%d + var median + var n_2 = inorderTree.root(nn) + median = sel_cmp(array, n_2, function(a,b) { + return a.get(k) - b.get(k) + }) + + //Copy into new array + var pptr = pointArray.index(pointer, 0) + var mptr = median.offset + for(var i=0; i 2) { + toVisit.push(array.lo(n_2+1)) + } + } else { + //Copy into new array + var mptr = array.offset + var pptr = pointArray.index(pointer, 0) + for(var i=0; i> 1 + } + return (i >> 1) - 1 +} + +function KDTHeap(n, d) { + this.count = 0 + this.dataSize = d + this.index = pool.mallocInt32(n) + this.data = pool.mallocFloat64(n*d) +} + +var proto = KDTHeap.prototype + +proto.heapSwap = function(_i,_j) { + var data = this.data + var index = this.index + var d = this.dataSize + var tmp = index[_i] + index[_i] = index[_j] + index[_j] = tmp + var aptr = d*_i + var bptr = d*_j + for(var _k=0; _k0) { + var parent = heapParent(i) + if(parent >= 0) { + var pw = data[d*parent] + if(w < pw) { + this.heapSwap(i, parent) + i = parent + continue + } + } + break + } +} + +proto.heapDown = function(i) { + var d = this.dataSize + var index = this.index + var data = this.data + var count = this.count + var w = data[d*i] + while(true) { + var tw = w + var left = 2*i + 1 + var right = 2*(i + 1) + var next = i + if(left < count) { + var lw = data[d*left] + if(lw < tw) { + next = left + tw = lw + } + } + if(right < count) { + var rw = data[d*right] + if(rw < tw) { + next = right + } + } + if(next === i) { + break + } + this.heapSwap(i, next) + i = next + } +} + +//Clear item from top of heap +proto.pop = function() { + this.count -= 1 + this.heapSwap(0, this.count) + this.heapDown(0) +} + +//Assume object already written to data +proto.push = function() { + this.heapUp(this.count) + this.count += 1 +} + +proto.dispose = function() { + pool.freeInt32(this.index) + pool.freeFloat64(this.data) +} +},{"typedarray-pool":31}],11:[function(require,module,exports){ +/** + * Bit twiddling hacks for JavaScript. + * + * Author: Mikola Lysenko + * + * Ported from Stanford bit twiddling hack library: + * http://graphics.stanford.edu/~seander/bithacks.html + */ + +"use strict"; "use restrict"; + +//Number of bits in an integer +var INT_BITS = 32; + +//Constants +exports.INT_BITS = INT_BITS; +exports.INT_MAX = 0x7fffffff; +exports.INT_MIN = -1<<(INT_BITS-1); + +//Returns -1, 0, +1 depending on sign of x +exports.sign = function(v) { + return (v > 0) - (v < 0); +} + +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; +} + +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} + +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} + +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} + +//Computes log base 2 of v +exports.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} + +//Computes log base 10 of v +exports.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} + +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} + +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +exports.countTrailingZeros = countTrailingZeros; + +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} + +//Rounds down to previous power of 2 +exports.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} + +//Computes parity of word +exports.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} + +var REVERSE_TABLE = new Array(256); + +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; + } + tab[i] = (r << s) & 0xff; + } +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; +} + +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +//Extracts the nth interleaved component +exports.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} + + +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; + + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} + +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} + +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +} + + +},{}],12:[function(require,module,exports){ +"use strict" + +var bits = require("bit-twiddle") + +function rootInorder(n) { + var ptree = (bits.nextPow2(n+1)>>>1) - 1 + var f = n - ptree + if(bits.nextPow2(f)-1 >= ptree) { + return ptree + } + return (ptree>>>1)+f +} +exports.root = rootInorder + +function beginInorder(n) { + return 0 +} +exports.begin = beginInorder + +function endInorder(n) { + return n-1 +} +exports.end = endInorder + + +//This is really horrible because n is not necessarily a power of 2 +// If it was, we could just do: +// +// height = bits.countTrailingZeros(~x) +// +// Instead, we just binary search because doing the right thing here is way too complicated. +function heightInorder(n, x) { + if(n <= 0) { + return 0 + } + var r = rootInorder(n) + if(x > r) { + return heightInorder(n-r-1, x-r-1) + } else if(x === r) { + return bits.log2(n) + } + return heightInorder(r, x) +} +exports.height = heightInorder + +function prevInorder(n, x) { + return Math.max(x-1,0) +} +exports.prev = prevInorder + +function nextInorder(n, x) { + return Math.min(x+1,n-1) +} +exports.next = nextInorder + + +//The version for n = (1< r) { + var q = parentInorder(n-r-1, x-r-1) + if(q < 0) { + return r + } else { + return q + r + 1 + } + } else if(x === r) { + return -1 + } + var q = parentInorder(r, x) + if(q < 0) { + return r + } + return q +} +exports.parent = parentInorder + + +//Again, we get screwed because n is not a power of two -1. If it was, we could do: +// +// left = x - (1 << (h-1) ) +// +// Where h is the height of the node +// +function leftInorder(n, x) { + if(n <= 0) { + return 0 + } + var r = rootInorder(n) + if(x > r) { + return leftInorder(n-r-1, x-r-1) + r + 1 + } else if(x === r) { + return rootInorder(x) + } + return leftInorder(r, x) + +} +exports.left = leftInorder + +//for power of two minus one: +// +// right = x + (1<<(h-1)) +// +function rightInorder(n, x) { + if(n <= 0) { + return 0 + } + var r = rootInorder(n) + if(x > r) { + return rightInorder(n-r-1, x-r-1) + r + 1 + } else if(x === r) { + return rootInorder(n-r-1) + r + 1 + } + return rightInorder(r, x) +} +exports.right = rightInorder + + +function leafInorder(n, x) { + return heightInorder(n, x) === 0 +} +exports.leaf = leafInorder + + +function loInorder(n, x) { + n |= 0 + x |= 0 + var l = 0 + while(n > 1) { + var r = rootInorder(n) + if(x > r) { + l += r + 1 + n -= r + 1 + x -= r + 1 + } else if(x === r) { + break + } else { + n = r + } + } + return l +} +exports.lo = loInorder + +function hiInorder(n, x) { + n |= 0 + x |= 0 + var l = 0 + while(n > 1) { + var r = rootInorder(n) + if(x > r) { + l += r + 1 + n -= r + 1 + x -= r + 1 + } else if(x === r) { + l += n-1 + break + } else { + n = r + } + } + return l +} +exports.hi = hiInorder + +},{"bit-twiddle":13}],13:[function(require,module,exports){ +arguments[4][11][0].apply(exports,arguments) +},{"dup":11}],14:[function(require,module,exports){ +"use strict" + +var compile = require("cwise-compiler") + +var EmptyProc = { + body: "", + args: [], + thisVars: [], + localVars: [] +} + +function fixup(x) { + if(!x) { + return EmptyProc + } + for(var i=0; i>", + rrshift: ">>>" +} +;(function(){ + for(var id in assign_ops) { + var op = assign_ops[id] + exports[id] = makeOp({ + args: ["array","array","array"], + body: {args:["a","b","c"], + body: "a=b"+op+"c"}, + funcName: id + }) + exports[id+"eq"] = makeOp({ + args: ["array","array"], + body: {args:["a","b"], + body:"a"+op+"=b"}, + rvalue: true, + funcName: id+"eq" + }) + exports[id+"s"] = makeOp({ + args: ["array", "array", "scalar"], + body: {args:["a","b","s"], + body:"a=b"+op+"s"}, + funcName: id+"s" + }) + exports[id+"seq"] = makeOp({ + args: ["array","scalar"], + body: {args:["a","s"], + body:"a"+op+"=s"}, + rvalue: true, + funcName: id+"seq" + }) + } +})(); + +var unary_ops = { + not: "!", + bnot: "~", + neg: "-", + recip: "1.0/" +} +;(function(){ + for(var id in unary_ops) { + var op = unary_ops[id] + exports[id] = makeOp({ + args: ["array", "array"], + body: {args:["a","b"], + body:"a="+op+"b"}, + funcName: id + }) + exports[id+"eq"] = makeOp({ + args: ["array"], + body: {args:["a"], + body:"a="+op+"a"}, + rvalue: true, + count: 2, + funcName: id+"eq" + }) + } +})(); + +var binary_ops = { + and: "&&", + or: "||", + eq: "===", + neq: "!==", + lt: "<", + gt: ">", + leq: "<=", + geq: ">=" +} +;(function() { + for(var id in binary_ops) { + var op = binary_ops[id] + exports[id] = makeOp({ + args: ["array","array","array"], + body: {args:["a", "b", "c"], + body:"a=b"+op+"c"}, + funcName: id + }) + exports[id+"s"] = makeOp({ + args: ["array","array","scalar"], + body: {args:["a", "b", "s"], + body:"a=b"+op+"s"}, + funcName: id+"s" + }) + exports[id+"eq"] = makeOp({ + args: ["array", "array"], + body: {args:["a", "b"], + body:"a=a"+op+"b"}, + rvalue:true, + count:2, + funcName: id+"eq" + }) + exports[id+"seq"] = makeOp({ + args: ["array", "scalar"], + body: {args:["a","s"], + body:"a=a"+op+"s"}, + rvalue:true, + count:2, + funcName: id+"seq" + }) + } +})(); + +var math_unary = [ + "abs", + "acos", + "asin", + "atan", + "ceil", + "cos", + "exp", + "floor", + "log", + "round", + "sin", + "sqrt", + "tan" +] +;(function() { + for(var i=0; ithis_s){this_s=-a}else if(a>this_s){this_s=a}", localVars: [], thisVars: ["this_s"]}, + post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, + funcName: "norminf" +}) + +exports.norm1 = compile({ + args:["array"], + pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"}, + body: {args:[{name:"a", lvalue:false, rvalue:true, count:3}], body: "this_s+=a<0?-a:a", localVars: [], thisVars: ["this_s"]}, + post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, + funcName: "norm1" +}) + +exports.sup = compile({ + args: [ "array" ], + pre: + { body: "this_h=-Infinity", + args: [], + thisVars: [ "this_h" ], + localVars: [] }, + body: + { body: "if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_", + args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ], + thisVars: [ "this_h" ], + localVars: [] }, + post: + { body: "return this_h", + args: [], + thisVars: [ "this_h" ], + localVars: [] } + }) + +exports.inf = compile({ + args: [ "array" ], + pre: + { body: "this_h=Infinity", + args: [], + thisVars: [ "this_h" ], + localVars: [] }, + body: + { body: "if(_inline_1_arg0_this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}", + args:[ + {name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2}, + {name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}], + thisVars:["this_i","this_v"], + localVars:["_inline_1_k"]}, + post:{ + body:"{return this_i}", + args:[], + thisVars:["this_i"], + localVars:[]} +}) + +exports.random = makeOp({ + args: ["array"], + pre: {args:[], body:"this_f=Math.random", thisVars:["this_f"]}, + body: {args: ["a"], body:"a=this_f()", thisVars:["this_f"]}, + funcName: "random" +}) + +exports.assign = makeOp({ + args:["array", "array"], + body: {args:["a", "b"], body:"a=b"}, + funcName: "assign" }) + +exports.assigns = makeOp({ + args:["array", "scalar"], + body: {args:["a", "b"], body:"a=b"}, + funcName: "assigns" }) + + +exports.equals = compile({ + args:["array", "array"], + pre: EmptyProc, + body: {args:[{name:"x", lvalue:false, rvalue:true, count:1}, + {name:"y", lvalue:false, rvalue:true, count:1}], + body: "if(x!==y){return false}", + localVars: [], + thisVars: []}, + post: {args:[], localVars:[], thisVars:[], body:"return true"}, + funcName: "equals" +}) + + + +},{"cwise-compiler":15}],15:[function(require,module,exports){ +"use strict" + +var createThunk = require("./lib/thunk.js") + +function Procedure() { + this.argTypes = [] + this.shimArgs = [] + this.arrayArgs = [] + this.arrayBlockIndices = [] + this.scalarArgs = [] + this.offsetArgs = [] + this.offsetArgIndex = [] + this.indexArgs = [] + this.shapeArgs = [] + this.funcName = "" + this.pre = null + this.body = null + this.post = null + this.debug = false +} + +function compileCwise(user_args) { + //Create procedure + var proc = new Procedure() + + //Parse blocks + proc.pre = user_args.pre + proc.body = user_args.body + proc.post = user_args.post + + //Parse arguments + var proc_args = user_args.args.slice(0) + proc.argTypes = proc_args + for(var i=0; i0) { + throw new Error("cwise: pre() block may not reference array args") + } + if(i < proc.post.args.length && proc.post.args[i].count>0) { + throw new Error("cwise: post() block may not reference array args") + } + } else if(arg_type === "scalar") { + proc.scalarArgs.push(i) + proc.shimArgs.push("scalar" + i) + } else if(arg_type === "index") { + proc.indexArgs.push(i) + if(i < proc.pre.args.length && proc.pre.args[i].count > 0) { + throw new Error("cwise: pre() block may not reference array index") + } + if(i < proc.body.args.length && proc.body.args[i].lvalue) { + throw new Error("cwise: body() block may not write to array index") + } + if(i < proc.post.args.length && proc.post.args[i].count > 0) { + throw new Error("cwise: post() block may not reference array index") + } + } else if(arg_type === "shape") { + proc.shapeArgs.push(i) + if(i < proc.pre.args.length && proc.pre.args[i].lvalue) { + throw new Error("cwise: pre() block may not write to array shape") + } + if(i < proc.body.args.length && proc.body.args[i].lvalue) { + throw new Error("cwise: body() block may not write to array shape") + } + if(i < proc.post.args.length && proc.post.args[i].lvalue) { + throw new Error("cwise: post() block may not write to array shape") + } + } else if(typeof arg_type === "object" && arg_type.offset) { + proc.argTypes[i] = "offset" + proc.offsetArgs.push({ array: arg_type.array, offset:arg_type.offset }) + proc.offsetArgIndex.push(i) + } else { + throw new Error("cwise: Unknown argument type " + proc_args[i]) + } + } + + //Make sure at least one array argument was specified + if(proc.arrayArgs.length <= 0) { + throw new Error("cwise: No array arguments specified") + } + + //Make sure arguments are correct + if(proc.pre.args.length > proc_args.length) { + throw new Error("cwise: Too many arguments in pre() block") + } + if(proc.body.args.length > proc_args.length) { + throw new Error("cwise: Too many arguments in body() block") + } + if(proc.post.args.length > proc_args.length) { + throw new Error("cwise: Too many arguments in post() block") + } + + //Check debug flag + proc.debug = !!user_args.printCode || !!user_args.debug + + //Retrieve name + proc.funcName = user_args.funcName || "cwise" + + //Read in block size + proc.blockSize = user_args.blockSize || 64 + + return createThunk(proc) +} + +module.exports = compileCwise + +},{"./lib/thunk.js":17}],16:[function(require,module,exports){ +"use strict" + +var uniq = require("uniq") + +// This function generates very simple loops analogous to how you typically traverse arrays (the outermost loop corresponds to the slowest changing index, the innermost loop to the fastest changing index) +// TODO: If two arrays have the same strides (and offsets) there is potential for decreasing the number of "pointers" and related variables. The drawback is that the type signature would become more specific and that there would thus be less potential for caching, but it might still be worth it, especially when dealing with large numbers of arguments. +function innerFill(order, proc, body) { + var dimension = order.length + , nargs = proc.arrayArgs.length + , has_index = proc.indexArgs.length>0 + , code = [] + , vars = [] + , idx=0, pidx=0, i, j + for(i=0; i=0; --i) { // Start at largest stride and work your way inwards + idx = order[i] + code.push(["for(i",i,"=0;i",i," 0) { + code.push(["index[",pidx,"]-=s",pidx].join("")) + } + code.push(["++index[",idx,"]"].join("")) + } + code.push("}") + } + return code.join("\n") +} + +// Generate "outer" loops that loop over blocks of data, applying "inner" loops to the blocks by manipulating the local variables in such a way that the inner loop only "sees" the current block. +// TODO: If this is used, then the previous declaration (done by generateCwiseOp) of s* is essentially unnecessary. +// I believe the s* are not used elsewhere (in particular, I don't think they're used in the pre/post parts and "shape" is defined independently), so it would be possible to make defining the s* dependent on what loop method is being used. +function outerFill(matched, order, proc, body) { + var dimension = order.length + , nargs = proc.arrayArgs.length + , blockSize = proc.blockSize + , has_index = proc.indexArgs.length > 0 + , code = [] + for(var i=0; i0;){"].join("")) // Iterate back to front + code.push(["if(j",i,"<",blockSize,"){"].join("")) // Either decrease j by blockSize (s = blockSize), or set it to zero (after setting s = j). + code.push(["s",order[i],"=j",i].join("")) + code.push(["j",i,"=0"].join("")) + code.push(["}else{s",order[i],"=",blockSize].join("")) + code.push(["j",i,"-=",blockSize,"}"].join("")) + if(has_index) { + code.push(["index[",order[i],"]=j",i].join("")) + } + } + for(var i=0; i 0) { + allEqual = allEqual && summary[i] === summary[i-1] + } + } + if(allEqual) { + return summary[0] + } + return summary.join("") +} + +//Generates a cwise operator +function generateCWiseOp(proc, typesig) { + + //Compute dimension + // Arrays get put first in typesig, and there are two entries per array (dtype and order), so this gets the number of dimensions in the first array arg. + var dimension = (typesig[1].length - Math.abs(proc.arrayBlockIndices[0]))|0 + var orders = new Array(proc.arrayArgs.length) + var dtypes = new Array(proc.arrayArgs.length) + for(var i=0; i 0) { + vars.push("shape=SS.slice(0)") // Makes the shape over which we iterate available to the user defined functions (so you can use width/height for example) + } + if(proc.indexArgs.length > 0) { + // Prepare an array to keep track of the (logical) indices, initialized to dimension zeroes. + var zeros = new Array(dimension) + for(var i=0; i 3) { + code.push(processBlock(proc.pre, proc, dtypes)) + } + + //Process body + var body = processBlock(proc.body, proc, dtypes) + var matched = countMatches(loopOrders) + if(matched < dimension) { + code.push(outerFill(matched, loopOrders[0], proc, body)) // TODO: Rather than passing loopOrders[0], it might be interesting to look at passing an order that represents the majority of the arguments for example. + } else { + code.push(innerFill(loopOrders[0], proc, body)) + } + + //Inline epilog + if(proc.post.body.length > 3) { + code.push(processBlock(proc.post, proc, dtypes)) + } + + if(proc.debug) { + console.log("-----Generated cwise routine for ", typesig, ":\n" + code.join("\n") + "\n----------") + } + + var loopName = [(proc.funcName||"unnamed"), "_cwise_loop_", orders[0].join("s"),"m",matched,typeSummary(dtypes)].join("") + var f = new Function(["function ",loopName,"(", arglist.join(","),"){", code.join("\n"),"} return ", loopName].join("")) + return f() +} +module.exports = generateCWiseOp + +},{"uniq":18}],17:[function(require,module,exports){ +"use strict" + +// The function below is called when constructing a cwise function object, and does the following: +// A function object is constructed which accepts as argument a compilation function and returns another function. +// It is this other function that is eventually returned by createThunk, and this function is the one that actually +// checks whether a certain pattern of arguments has already been used before and compiles new loops as needed. +// The compilation passed to the first function object is used for compiling new functions. +// Once this function object is created, it is called with compile as argument, where the first argument of compile +// is bound to "proc" (essentially containing a preprocessed version of the user arguments to cwise). +// So createThunk roughly works like this: +// function createThunk(proc) { +// var thunk = function(compileBound) { +// var CACHED = {} +// return function(arrays and scalars) { +// if (dtype and order of arrays in CACHED) { +// var func = CACHED[dtype and order of arrays] +// } else { +// var func = CACHED[dtype and order of arrays] = compileBound(dtype and order of arrays) +// } +// return func(arrays and scalars) +// } +// } +// return thunk(compile.bind1(proc)) +// } + +var compile = require("./compile.js") + +function createThunk(proc) { + var code = ["'use strict'", "var CACHED={}"] + var vars = [] + var thunkName = proc.funcName + "_cwise_thunk" + + //Build thunk + code.push(["return function ", thunkName, "(", proc.shimArgs.join(","), "){"].join("")) + var typesig = [] + var string_typesig = [] + var proc_args = [["array",proc.arrayArgs[0],".shape.slice(", // Slice shape so that we only retain the shape over which we iterate (which gets passed to the cwise operator as SS). + Math.max(0,proc.arrayBlockIndices[0]),proc.arrayBlockIndices[0]<0?(","+proc.arrayBlockIndices[0]+")"):")"].join("")] + var shapeLengthConditions = [], shapeConditions = [] + // Process array arguments + for(var i=0; i0) { // Gather conditions to check for shape equality (ignoring block indices) + shapeLengthConditions.push("array" + proc.arrayArgs[0] + ".shape.length===array" + j + ".shape.length+" + (Math.abs(proc.arrayBlockIndices[0])-Math.abs(proc.arrayBlockIndices[i]))) + shapeConditions.push("array" + proc.arrayArgs[0] + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[0]) + "]===array" + j + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[i]) + "]") + } + } + // Check for shape equality + if (proc.arrayArgs.length > 1) { + code.push("if (!(" + shapeLengthConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same dimensionality!')") + code.push("for(var shapeIndex=array" + proc.arrayArgs[0] + ".shape.length-" + Math.abs(proc.arrayBlockIndices[0]) + "; shapeIndex-->0;) {") + code.push("if (!(" + shapeConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same shape!')") + code.push("}") + } + // Process scalar arguments + for(var i=0; i=0; --i) { + stride[i] = sz + sz *= shape[i] + } + return ndarray(pool.malloc(sz, dtype), shape, stride, 0) +} +exports.malloc = malloc + +function free(array) { + if(array.dtype === "generic" || array.dtype === "array") { + return + } + pool.free(array.data) +} +exports.free = free + +function zeros(shape, dtype) { + if(!dtype) { + dtype = "double" + } + + var sz = 1 + var stride = new Array(shape.length) + for(var i=shape.length-1; i>=0; --i) { + stride[i] = sz + sz *= shape[i] + } + var buf = pool.malloc(sz, dtype) + for(var i=0; i=0; --i) { + stride[i] = sz + sz *= shape[i] + } + var buf = pool.malloc(sz, dtype) + for(var i=0; i=0; --i) { + stride[i] = sz + sz *= shape[i] + } + var buf = pool.malloc(sz, dtype) + for(i=0; i=0; i--) { + offsum += stride[i] + mindim = Math.min(mindim,shape[i]) + } + for(i=0,offset=0; i 1) { + vars.push(STEP_CMP(i) + "=(" + STRIDE(i) + "-" + SHAPE(i-1) + "*" + STRIDE(i-1) + ")|0", + STEP(order[i]) + "=(" + STRIDE(order[i]) + "-" + SHAPE(order[i-1]) + "*" + STRIDE(order[i-1]) + ")|0") + } else { + vars.push(STEP_CMP(i) + "=" + STRIDE(i), + STEP(order[i]) + "=" + STRIDE(order[i])) + } + } + if(useCompare) { + for(var i=0; i<2; ++i) { + vars.push(PICK(i) + "=" + ARRAY + ".pick(0)") + } + } + vars.push( + PIVOT + "=0", + LO + "=0", + HI + "=" + SHAPE(order[0]) + "-1") + + function compare(out, i0, i1) { + if(useCompare) { + code.push( + PICK(0), ".offset=", OFFSET, "+", STRIDE(order[0]), "*(", i0, ");", + PICK(1), ".offset=", OFFSET, "+", STRIDE(order[0]), "*(", i1, ");", + out, "=", CMP, "(", PICK(0), ",", PICK(1), ");") + } else { + code.push( + PTR(0), "=", OFFSET, "+", STRIDE(0), "*(", i0, ");", + PTR(1), "=", OFFSET, "+", STRIDE(0), "*(", i1, ");") + if(dimension > 1) { + code.push("_cmp:") + } + for(var i=dimension-1; i>0; --i) { + code.push("for(", INDEX(i), "=0;", + INDEX(i), "<", SHAPE(i), ";", + INDEX(i), "++){") + } + if(useGetter) { + code.push(out, "=", DATA, ".get(", PTR(0), ")-", + DATA, ".get(", PTR(1), ");") + } else { + code.push(out, "=", DATA, "[", PTR(0), "]-", + DATA, "[", PTR(1), "];") + } + if(dimension > 1) { + code.push("if(", out, ")break _cmp;") + } + for(var i=1; i0; --i) { + code.push("for(", INDEX(order[i]), "=0;", + INDEX(order[i]), "<", SHAPE(order[i]), ";", + INDEX(order[i]), "++){") + } + if(useGetter) { + code.push(TMP, "=", DATA, ".get(", PTR(0), ");", + DATA, ".set(", PTR(0), ",", DATA, ".get(", PTR(1), "));", + DATA, ".set(", PTR(1), ",", TMP, ");") + } else { + code.push(TMP, "=", DATA, "[", PTR(0), "];", + DATA, "[", PTR(0), "]=", DATA, "[", PTR(1), "];", + DATA, "[", PTR(1), "]=", TMP, ";") + } + for(var i=1; i= the pivot are behind the pivot) + + //Check pivot bounds + code.push( + "if(", PIVOT, "===", RANK, "){", + LO, "=", PIVOT, ";", + "break;", + "}else if(", RANK, "<", PIVOT, "){", + HI, "=", PIVOT, "-1;", + "}else{", + LO, "=", PIVOT, "+1;", + "}", + "}") + + if(useCompare) { + code.push(PICK(0), ".offset=", OFFSET, "+", LO, "*", STRIDE(0), ";", + "return ", PICK(0), ";") + } else { + code.push("return ", ARRAY, ".pick(", LO, ");") + } + + //Compile and link js together + var procCode = [ + "'use strict';function ", funcName, "(", args, "){", + "var ", vars.join(), ";", + code.join(""), + "};return ", funcName + ].join("") + + var proc = new Function(procCode) + return proc() +} + +var CACHE = {} + +function lookupCache(order, useCompare, dtype) { + var typesig = order.join() + useCompare + dtype + var proc = CACHE[typesig] + if(proc) { + return proc + } + return CACHE[typesig] = compileQuickSelect(order, useCompare, dtype) +} + +function ndSelect(array, k, compare) { + k |= 0 + if((array.dimension === 0) || + (array.shape[0] <= k) || + (k < 0)) { + return null + } + var useCompare = !!compare + var proc = lookupCache(array.order, useCompare, array.dtype) + if(useCompare) { + return proc(array, k, compare) + } else { + return proc(array, k) + } +} +},{}],27:[function(require,module,exports){ +var iota = require("iota-array") +var isBuffer = require("is-buffer") + +var hasTypedArrays = ((typeof Float64Array) !== "undefined") + +function compare1st(a, b) { + return a[0] - b[0] +} + +function order() { + var stride = this.stride + var terms = new Array(stride.length) + var i + for(i=0; iMath.abs(this.stride[1]))?[1,0]:[0,1]}})") + } else if(dimension === 3) { + code.push( +"var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\ +if(s0>s1){\ +if(s1>s2){\ +return [2,1,0];\ +}else if(s0>s2){\ +return [1,2,0];\ +}else{\ +return [1,0,2];\ +}\ +}else if(s0>s2){\ +return [2,0,1];\ +}else if(s2>s1){\ +return [0,1,2];\ +}else{\ +return [0,2,1];\ +}}})") + } + } else { + code.push("ORDER})") + } + } + + //view.set(i0, ..., v): + code.push( +"proto.set=function "+className+"_set("+args.join(",")+",v){") + if(useGetters) { + code.push("return this.data.set("+index_str+",v)}") + } else { + code.push("return this.data["+index_str+"]=v}") + } + + //view.get(i0, ...): + code.push("proto.get=function "+className+"_get("+args.join(",")+"){") + if(useGetters) { + code.push("return this.data.get("+index_str+")}") + } else { + code.push("return this.data["+index_str+"]}") + } + + //view.index: + code.push( + "proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}") + + //view.hi(): + code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+ + indices.map(function(i) { + return ["(typeof i",i,"!=='number'||i",i,"<0)?this.shape[", i, "]:i", i,"|0"].join("") + }).join(",")+","+ + indices.map(function(i) { + return "this.stride["+i + "]" + }).join(",")+",this.offset)}") + + //view.lo(): + var a_vars = indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" }) + var c_vars = indices.map(function(i) { return "c"+i+"=this.stride["+i+"]" }) + code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(",")) + for(var i=0; i=0){\ +d=i"+i+"|0;\ +b+=c"+i+"*d;\ +a"+i+"-=d}") + } + code.push("return new "+className+"(this.data,"+ + indices.map(function(i) { + return "a"+i + }).join(",")+","+ + indices.map(function(i) { + return "c"+i + }).join(",")+",b)}") + + //view.step(): + code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+ + indices.map(function(i) { + return "a"+i+"=this.shape["+i+"]" + }).join(",")+","+ + indices.map(function(i) { + return "b"+i+"=this.stride["+i+"]" + }).join(",")+",c=this.offset,d=0,ceil=Math.ceil") + for(var i=0; i=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}") + } + code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}") + + //Add return statement + code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+ + indices.map(function(i) { + return "shape["+i+"]" + }).join(",")+","+ + indices.map(function(i) { + return "stride["+i+"]" + }).join(",")+",offset)}") + + //Compile procedure + var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n")) + return procedure(CACHED_CONSTRUCTORS[dtype], order) +} + +function arrayDType(data) { + if(isBuffer(data)) { + return "buffer" + } + if(hasTypedArrays) { + switch(Object.prototype.toString.call(data)) { + case "[object Float64Array]": + return "float64" + case "[object Float32Array]": + return "float32" + case "[object Int8Array]": + return "int8" + case "[object Int16Array]": + return "int16" + case "[object Int32Array]": + return "int32" + case "[object Uint8Array]": + return "uint8" + case "[object Uint16Array]": + return "uint16" + case "[object Uint32Array]": + return "uint32" + case "[object Uint8ClampedArray]": + return "uint8_clamped" + } + } + if(Array.isArray(data)) { + return "array" + } + return "generic" +} + +var CACHED_CONSTRUCTORS = { + "float32":[], + "float64":[], + "int8":[], + "int16":[], + "int32":[], + "uint8":[], + "uint16":[], + "uint32":[], + "array":[], + "uint8_clamped":[], + "buffer":[], + "generic":[] +} + +;(function() { + for(var id in CACHED_CONSTRUCTORS) { + CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1)) + } +}); + +function wrappedNDArrayCtor(data, shape, stride, offset) { + if(data === undefined) { + var ctor = CACHED_CONSTRUCTORS.array[0] + return ctor([]) + } else if(typeof data === "number") { + data = [data] + } + if(shape === undefined) { + shape = [ data.length ] + } + var d = shape.length + if(stride === undefined) { + stride = new Array(d) + for(var i=d-1, sz=1; i>=0; --i) { + stride[i] = sz + sz *= shape[i] + } + } + if(offset === undefined) { + offset = 0 + for(var i=0; i + * License: MIT + * + * `npm install is-buffer` + */ + +module.exports = function (obj) { + return !!(obj != null && + (obj._isBuffer || // For Safari 5-7 (missing Object.prototype.constructor) + (obj.constructor && + typeof obj.constructor.isBuffer === 'function' && + obj.constructor.isBuffer(obj)) + )) +} + +},{}],30:[function(require,module,exports){ +"use strict" + +function dupe_array(count, value, i) { + var c = count[i]|0 + if(c <= 0) { + return [] + } + var result = new Array(c), j + if(i === count.length-1) { + for(j=0; j 0) { + return dupe_number(count|0, value) + } + break + case "object": + if(typeof (count.length) === "number") { + return dupe_array(count, value, 0) + } + break + } + return [] +} + +module.exports = dupe +},{}],31:[function(require,module,exports){ +(function (global,Buffer){ +'use strict' + +var bits = require('bit-twiddle') +var dup = require('dup') + +//Legacy pool support +if(!global.__TYPEDARRAY_POOL) { + global.__TYPEDARRAY_POOL = { + UINT8 : dup([32, 0]) + , UINT16 : dup([32, 0]) + , UINT32 : dup([32, 0]) + , INT8 : dup([32, 0]) + , INT16 : dup([32, 0]) + , INT32 : dup([32, 0]) + , FLOAT : dup([32, 0]) + , DOUBLE : dup([32, 0]) + , DATA : dup([32, 0]) + , UINT8C : dup([32, 0]) + , BUFFER : dup([32, 0]) + } +} + +var hasUint8C = (typeof Uint8ClampedArray) !== 'undefined' +var POOL = global.__TYPEDARRAY_POOL + +//Upgrade pool +if(!POOL.UINT8C) { + POOL.UINT8C = dup([32, 0]) +} +if(!POOL.BUFFER) { + POOL.BUFFER = dup([32, 0]) +} + +//New technique: Only allocate from ArrayBufferView and Buffer +var DATA = POOL.DATA + , BUFFER = POOL.BUFFER + +exports.free = function free(array) { + if(Buffer.isBuffer(array)) { + BUFFER[bits.log2(array.length)].push(array) + } else { + if(Object.prototype.toString.call(array) !== '[object ArrayBuffer]') { + array = array.buffer + } + if(!array) { + return + } + var n = array.length || array.byteLength + var log_n = bits.log2(n)|0 + DATA[log_n].push(array) + } +} + +function freeArrayBuffer(buffer) { + if(!buffer) { + return + } + var n = buffer.length || buffer.byteLength + var log_n = bits.log2(n) + DATA[log_n].push(buffer) +} + +function freeTypedArray(array) { + freeArrayBuffer(array.buffer) +} + +exports.freeUint8 = +exports.freeUint16 = +exports.freeUint32 = +exports.freeInt8 = +exports.freeInt16 = +exports.freeInt32 = +exports.freeFloat32 = +exports.freeFloat = +exports.freeFloat64 = +exports.freeDouble = +exports.freeUint8Clamped = +exports.freeDataView = freeTypedArray + +exports.freeArrayBuffer = freeArrayBuffer + +exports.freeBuffer = function freeBuffer(array) { + BUFFER[bits.log2(array.length)].push(array) +} + +exports.malloc = function malloc(n, dtype) { + if(dtype === undefined || dtype === 'arraybuffer') { + return mallocArrayBuffer(n) + } else { + switch(dtype) { + case 'uint8': + return mallocUint8(n) + case 'uint16': + return mallocUint16(n) + case 'uint32': + return mallocUint32(n) + case 'int8': + return mallocInt8(n) + case 'int16': + return mallocInt16(n) + case 'int32': + return mallocInt32(n) + case 'float': + case 'float32': + return mallocFloat(n) + case 'double': + case 'float64': + return mallocDouble(n) + case 'uint8_clamped': + return mallocUint8Clamped(n) + case 'buffer': + return mallocBuffer(n) + case 'data': + case 'dataview': + return mallocDataView(n) + + default: + return null + } + } + return null +} + +function mallocArrayBuffer(n) { + var n = bits.nextPow2(n) + var log_n = bits.log2(n) + var d = DATA[log_n] + if(d.length > 0) { + return d.pop() + } + return new ArrayBuffer(n) +} +exports.mallocArrayBuffer = mallocArrayBuffer + +function mallocUint8(n) { + return new Uint8Array(mallocArrayBuffer(n), 0, n) +} +exports.mallocUint8 = mallocUint8 + +function mallocUint16(n) { + return new Uint16Array(mallocArrayBuffer(2*n), 0, n) +} +exports.mallocUint16 = mallocUint16 + +function mallocUint32(n) { + return new Uint32Array(mallocArrayBuffer(4*n), 0, n) +} +exports.mallocUint32 = mallocUint32 + +function mallocInt8(n) { + return new Int8Array(mallocArrayBuffer(n), 0, n) +} +exports.mallocInt8 = mallocInt8 + +function mallocInt16(n) { + return new Int16Array(mallocArrayBuffer(2*n), 0, n) +} +exports.mallocInt16 = mallocInt16 + +function mallocInt32(n) { + return new Int32Array(mallocArrayBuffer(4*n), 0, n) +} +exports.mallocInt32 = mallocInt32 + +function mallocFloat(n) { + return new Float32Array(mallocArrayBuffer(4*n), 0, n) +} +exports.mallocFloat32 = exports.mallocFloat = mallocFloat + +function mallocDouble(n) { + return new Float64Array(mallocArrayBuffer(8*n), 0, n) +} +exports.mallocFloat64 = exports.mallocDouble = mallocDouble + +function mallocUint8Clamped(n) { + if(hasUint8C) { + return new Uint8ClampedArray(mallocArrayBuffer(n), 0, n) + } else { + return mallocUint8(n) + } +} +exports.mallocUint8Clamped = mallocUint8Clamped + +function mallocDataView(n) { + return new DataView(mallocArrayBuffer(n), 0, n) +} +exports.mallocDataView = mallocDataView + +function mallocBuffer(n) { + n = bits.nextPow2(n) + var log_n = bits.log2(n) + var cache = BUFFER[log_n] + if(cache.length > 0) { + return cache.pop() + } + return new Buffer(n) +} +exports.mallocBuffer = mallocBuffer + +exports.clearCache = function clearCache() { + for(var i=0; i<32; ++i) { + POOL.UINT8[i].length = 0 + POOL.UINT16[i].length = 0 + POOL.UINT32[i].length = 0 + POOL.INT8[i].length = 0 + POOL.INT16[i].length = 0 + POOL.INT32[i].length = 0 + POOL.FLOAT[i].length = 0 + POOL.DOUBLE[i].length = 0 + POOL.UINT8C[i].length = 0 + DATA[i].length = 0 + BUFFER[i].length = 0 + } +} +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) +},{"bit-twiddle":11,"buffer":2,"dup":30}],32:[function(require,module,exports){ +var colorSort; + +colorSort = require("../color/sort.coffee"); + +module.exports = function(a, b, keys, sort, colors, vars, depth) { + var i, k, retVal; + if (!sort) { + sort = "asc"; + } + if (!(colors instanceof Array)) { + colors = [colors]; + } + if (!(keys instanceof Array)) { + keys = [keys]; + } + if (vars && depth !== void 0 && typeof depth !== "number") { + depth = vars.id.nesting.indexOf(depth); + } + retVal = 0; + i = 0; + while (i < keys.length) { + k = keys[i]; + a = vars && a.d3plus && a.d3plus.sortKeys ? a.d3plus.sortKeys[k] : a[k]; + b = vars && b.d3plus && b.d3plus.sortKeys ? b.d3plus.sortKeys[k] : b[k]; + if (vars && colors.indexOf(k) >= 0) { + retVal = colorSort(a, b); + } else { + retVal = a < b ? -1 : 1; + } + if (retVal !== 0 || i === keys.length - 1) { + break; + } + i++; + } + if (sort === "asc") { + return retVal; + } else { + return -retVal; + } +}; + + +},{"../color/sort.coffee":49}],33:[function(require,module,exports){ +module.exports = function(arr, value) { + var constructor; + if (arr instanceof Array) { + constructor = value === void 0 || value === null ? value : value.constructor; + return arr.indexOf(value) >= 0 || arr.indexOf(constructor) >= 0; + } else { + return false; + } +}; + + +},{}],34:[function(require,module,exports){ +var comparator, fetchSort; + +comparator = require("./comparator.coffee"); + +fetchSort = require("../core/fetch/sort.coffee"); + +module.exports = function(arr, keys, sort, colors, vars, depth) { + var d, data, i, len; + if (!arr || arr.length <= 1) { + return arr || []; + } else { + if (vars) { + if (!keys) { + keys = vars.order.value || vars.size.value || vars.id.value; + } + if (!sort) { + sort = vars.order.sort.value; + } + if (!colors) { + colors = vars.color.value || []; + } + for (i = 0, len = arr.length; i < len; i++) { + d = arr[i]; + if (!d.d3plus) { + d.d3plus = {}; + } + data = "d3plus" in d && "d3plus" in d.d3plus ? d.d3plus : d; + d.d3plus.sortKeys = fetchSort(vars, data, keys, colors, depth); + } + } + return arr.sort(function(a, b) { + return comparator(a, b, keys, sort, colors, vars, depth); + }); + } +}; + + +},{"../core/fetch/sort.coffee":65,"./comparator.coffee":32}],35:[function(require,module,exports){ +module.exports = function(arr, x) { + if (x === void 0) { + return arr; + } + if (x === false) { + return []; + } + if (x instanceof Array) { + return x; + } + if (!(arr instanceof Array)) { + arr = []; + } + if (arr.indexOf(x) >= 0) { + arr.splice(arr.indexOf(x), 1); + } else { + arr.push(x); + } + return arr; +}; + + +},{}],36:[function(require,module,exports){ +var sheet; + +sheet = function(name) { + var css, i, returnBoolean, tested; + tested = sheet.tested; + if (name in tested) { + return tested[name]; + } + i = 0; + returnBoolean = false; + while (i < document.styleSheets.length) { + css = document.styleSheets[i]; + if (css.href && css.href.indexOf(name) >= 0) { + returnBoolean = true; + break; + } + i++; + } + return returnBoolean; +}; + +sheet.tested = {}; + +module.exports = sheet; + + +},{}],37:[function(require,module,exports){ +// Determines if the current browser is Internet Explorer. +module.exports = /(MSIE|Trident\/|Edge\/)/i.test(navigator.userAgent); + +},{}],38:[function(require,module,exports){ +var ie, touch; + +ie = require("./ie.js"); + +touch = require("./touch.coffee"); + +if (touch) { + module.exports = { + click: "click", + down: "touchstart", + up: "touchend", + over: ie ? "mouseenter" : "mouseover", + out: ie ? "mouseleave" : "mouseout", + move: "mousemove" + }; +} else { + module.exports = { + click: "click", + down: "mousedown", + up: "mouseup", + over: ie ? "mouseenter" : "mouseover", + out: ie ? "mouseleave" : "mouseout", + move: "mousemove" + }; +} + + +},{"./ie.js":37,"./touch.coffee":43}],39:[function(require,module,exports){ +var prefix; + +prefix = function() { + var val; + if ("-webkit-transform" in document.body.style) { + val = "-webkit-"; + } else if ("-moz-transform" in document.body.style) { + val = "-moz-"; + } else if ("-ms-transform" in document.body.style) { + val = "-ms-"; + } else if ("-o-transform" in document.body.style) { + val = "-o-"; + } else { + val = ""; + } + prefix = function() { + return val; + }; + return val; +}; + +module.exports = prefix; + + +},{}],40:[function(require,module,exports){ +module.exports = d3.select("html").attr("dir") === "rtl"; + + +},{}],41:[function(require,module,exports){ +module.exports = { + "y": function() { + return (window.pageYOffset !== undefined) ? window.pageYOffset : + (document.documentElement || document.body.parentNode || document.body).scrollTop + }, + "x": function() { + return (window.pageXOffset !== undefined) ? window.pageXOffset : + (document.documentElement || document.body.parentNode || document.body).scrollLeft + } +} + +},{}],42:[function(require,module,exports){ +var scrollbar; + +scrollbar = function() { + var inner, outer, val, w1, w2; + inner = document.createElement("p"); + inner.style.width = "100%"; + inner.style.height = "200px"; + outer = document.createElement("div"); + outer.style.position = "absolute"; + outer.style.top = "0px"; + outer.style.left = "0px"; + outer.style.visibility = "hidden"; + outer.style.width = "200px"; + outer.style.height = "150px"; + outer.style.overflow = "hidden"; + outer.appendChild(inner); + document.body.appendChild(outer); + w1 = inner.offsetWidth; + outer.style.overflow = "scroll"; + w2 = inner.offsetWidth; + if (w1 === w2) { + w2 = outer.clientWidth; + } + document.body.removeChild(outer); + val = w1 - w2; + scrollbar = function() { + return val; + }; + return val; +}; + +module.exports = scrollbar; + + +},{}],43:[function(require,module,exports){ +module.exports = ("ontouchstart" in window) || window.DocumentTouch && document instanceof DocumentTouch ? true : false; + + +},{}],44:[function(require,module,exports){ +module.exports = function(color) { + var hsl; + hsl = d3.hsl(color); + if (hsl.l > .45) { + if (hsl.s > .8) { + hsl.s = 0.8; + } + hsl.l = 0.45; + } + return hsl.toString(); +}; + + +},{}],45:[function(require,module,exports){ +module.exports = function(color, increment) { + var c; + if (increment === void 0) { + increment = 0.5; + } + c = d3.hsl(color); + increment = (1 - c.l) * increment; + c.l += increment; + c.s -= increment; + return c.toString(); +}; + + +},{}],46:[function(require,module,exports){ +module.exports = function(c1, c2, o1, o2) { + var b, g, r; + if (!o1) { + o1 = 1; + } + if (!o2) { + o2 = 1; + } + c1 = d3.rgb(c1); + c2 = d3.rgb(c2); + r = (o1 * c1.r + o2 * c2.r - o1 * o2 * c2.r) / (o1 + o2 - o1 * o2); + g = (o1 * c1.g + o2 * c2.g - o1 * o2 * c2.g) / (o1 + o2 - o1 * o2); + b = (o1 * c1.b + o2 * c2.b - o1 * o2 * c2.b) / (o1 + o2 - o1 * o2); + return d3.rgb(r, g, b).toString(); +}; + + +},{}],47:[function(require,module,exports){ +var defaultScale; + +defaultScale = require("./scale.coffee"); + +module.exports = function(x, scale) { + var rand_int; + rand_int = x || Math.floor(Math.random() * 20); + scale = scale || defaultScale; + return scale(rand_int); +}; + + +},{"./scale.coffee":48}],48:[function(require,module,exports){ +module.exports = d3.scale.ordinal().range(["#b22200", "#282F6B", "#EACE3F", "#B35C1E", "#224F20", "#5F487C", "#759143", "#419391", "#993F88", "#e89c89", "#ffee8d", "#afd5e8", "#f7ba77", "#a5c697", "#c5b5e5", "#d1d392", "#bbefd0", "#e099cf"]); + + +},{}],49:[function(require,module,exports){ +module.exports = function(a, b) { + var aHSL, bHSL; + aHSL = d3.hsl(a); + bHSL = d3.hsl(b); + a = aHSL.s === 0 ? 361 : aHSL.h; + b = bHSL.s === 0 ? 361 : bHSL.h; + if (a === b) { + return aHSL.l - bHSL.l; + } else { + return a - b; + } +}; + + +},{}],50:[function(require,module,exports){ +module.exports = function(color) { + var b, g, r, rgbColor, yiq; + rgbColor = d3.rgb(color); + r = rgbColor.r; + g = rgbColor.g; + b = rgbColor.b; + yiq = (r * 299 + g * 587 + b * 114) / 1000; + if (yiq >= 128) { + return "#444444"; + } else { + return "#f7f7f7"; + } +}; + + +},{}],51:[function(require,module,exports){ +module.exports = function(color) { + var blackColors, testColor, userBlack; + color = color + ""; + color = color.replace(RegExp(" ", "g"), ""); + if (color.indexOf("rgb") === 0) { + color = color.split("(")[1].split(")")[0].split(",").slice(0, 3).join(","); + } + if (color.indexOf("hsl") === 0) { + color = color.split(",")[2].split(")")[0]; + } + testColor = d3.rgb(color).toString(); + blackColors = ["black", "#000", "#000000", "0%", "0,0,0"]; + userBlack = blackColors.indexOf(color) >= 0; + return testColor !== "#000000" || userBlack; +}; + + +},{}],52:[function(require,module,exports){ +var ie, print, wiki; + +ie = require("../../client/ie.js"); + +wiki = require("./wiki.coffee"); + +print = function(type, message, style) { + style = style || ""; + if (ie || typeof InstallTrigger !== 'undefined') { + console.log("[ D3plus ] " + message); + } else if (type.indexOf("group") === 0) { + console[type]("%c[ D3plus ]%c " + message, "font-weight: 800;" + "color: #b35c1e;" + "margin-left: 0px;", "font-weight:200;" + style); + } else { + console[type]("%c" + message, style + "font-weight:200;"); + } +}; + +print.comment = function(message) { + this("log", message, "color:#aaa;"); +}; + +print.error = function(message, url) { + this("groupCollapsed", "ERROR: " + message, "font-weight:800;color:#D74B03;"); + this.stack(); + this.wiki(url); + this.groupEnd(); +}; + +print.group = function(message) { + this("group", message, "color:#888;"); +}; + +print.groupCollapsed = function(message) { + this("groupCollapsed", message, "color:#888;"); +}; + +print.groupEnd = function() { + if (!ie) { + console.groupEnd(); + } +}; + +print.log = function(message) { + this("log", message, "color:#444444;"); +}; + +print.stack = function() { + var err, line, message, page, splitter, stack, url; + if (!ie) { + err = new Error(); + if (err.stack) { + stack = err.stack.split("\n"); + stack = stack.filter(function(e) { + return e.indexOf("Error") !== 0 && e.indexOf("d3plus.js:") < 0 && e.indexOf("d3plus.min.js:") < 0; + }); + if (stack.length && stack[0].length) { + splitter = window.chrome ? "at " : "@"; + url = stack[0]; + if (url.indexOf(splitter) >= 0) { + url = url.split(splitter)[1]; + } + stack = url.split(":"); + if (stack.length === 3) { + stack.pop(); + } + line = stack.pop(); + page = stack.join(":").split("/"); + page = page[page.length - 1]; + message = "line " + line + " of " + page + ": " + url; + this("log", message, "color:#D74B03;"); + } + } + } +}; + +print.time = function(message) { + if (!ie) { + console.time(message); + } +}; + +print.timeEnd = function(message) { + if (!ie) { + console.timeEnd(message); + } +}; + +print.warning = function(message, url) { + this("groupCollapsed", message, "color:#888;"); + this.stack(); + this.wiki(url); + this.groupEnd(); +}; + +print.wiki = function(url) { + if (url) { + if (url in wiki) { + url = d3plus.repo + "wiki/" + wiki[url]; + } + this("log", "documentation: " + url, "color:#aaa;"); + } +}; + +module.exports = print; + + +},{"../../client/ie.js":37,"./wiki.coffee":53}],53:[function(require,module,exports){ +module.exports = { + active: "Visualizations#active", + aggs: "Visualizations#aggs", + alt: "Forms#alt", + attrs: "Visualizations#attrs", + axes: "Visualizations#axes", + background: "Visualizations#background", + color: "Visualizations#color", + cols: "Visualizations#cols", + config: "Visualizations#config", + container: "Visualizations#container", + coords: "Visualizations#coords", + csv: "Visualizations#csv", + data: "Visualizations#data", + depth: "Visualizations#depth", + descs: "Visualizations#descs", + dev: "Visualizations#dev", + draw: "Visualizations#draw", + edges: "Visualizations#edges", + error: "Visualizations#error", + focus: "Visualizations#focus", + font: "Visualizations#font", + footer: "Visualizations#footer", + format: "Visualizations#format", + height: "Visualizations#height", + history: "Visualizations#history", + hover: "Forms#hover", + icon: "Visualizations#icon", + id: "Visualizations#id", + keywords: "Forms#keywords", + labels: "Visualizations#labels", + legend: "Visualizations#legend", + links: "Visualizations#links", + margin: "Visualizations#margin", + messages: "Visualizations#messages", + method: "Methods", + mouse: "Visualizations#mouse", + nodes: "Visualizations#nodes", + open: "Forms#open", + order: "Visualizations#order", + remove: "Forms#remove", + search: "Forms#search", + select: "Forms#select", + selectAll: "Forms#selectAll", + shape: "Visualizations#shape", + size: "Visualizations#size", + temp: "Visualizations#temp", + text: "Visualizations#text", + time: "Visualizations#time", + timeline: "Visualizations#timeline", + timing: "Visualizations#timing", + title: "Visualizations#title", + tooltip: "Visualizations#tooltip", + total: "Visualizations#total", + type: "Visualizations#type", + ui: "Visualizations#ui", + width: "Visualizations#width", + x: "Visualizations#x", + y: "Visualizations#y", + zoom: "Visualizations#zoom" +}; + + +},{}],54:[function(require,module,exports){ +var buckets = require("../../util/buckets.coffee"), + fetchValue = require("../fetch/value.coffee"), + print = require("../console/print.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Sets color range of data, if applicable +//------------------------------------------------------------------- +module.exports = function(vars) { + + if ( vars.dev.value ) print.time("getting color data range") + + if (vars.color.domain.value) { + var data_range = vars.color.domain.value; + } + else { + var data_range = [] + vars.data.pool.forEach(function(d){ + var val = parseFloat(fetchValue(vars,d,vars.color.value)) + if (typeof val == "number" && !isNaN(val) && data_range.indexOf(val) < 0) data_range.push(val) + }) + } + + if ( vars.dev.value ) print.timeEnd("getting color data range") + + if (data_range.length > 1) { + + var data_domain = null + + if ( vars.dev.value ) print.time("calculating color scale") + + data_range = d3.extent(data_range); + + if (data_range[0] < 0 && data_range[1] > 0) { + var color_range = vars.color.range + if (color_range.length == 3) { + data_range.push(data_range[1]) + data_range[1] = 0 + } + } + else if (data_range[1] > 0 && data_range[0] >= 0) { + var color_range = vars.color.heatmap + data_range = buckets(data_range,color_range.length) + } + else { + var color_range = vars.color.range.slice(0) + if (data_range[0] < 0) { + color_range.pop() + } + else { + color_range.shift() + } + } + + vars.color.valueScale = d3.scale.sqrt() + .domain(data_range) + .range(color_range) + .interpolate(d3.interpolateRgb) + + if ( vars.dev.value ) print.timeEnd("calculating color scale") + + } + else { + vars.color.valueScale = null + } + +} + +},{"../../util/buckets.coffee":204,"../console/print.coffee":52,"../fetch/value.coffee":67}],55:[function(require,module,exports){ +var fetchValue = require("../fetch/value.coffee"), + print = require("../console/print.coffee"), + validObject = require("../../object/validate.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Restricts data based on Solo/Mute filters +//------------------------------------------------------------------------------ +module.exports = function( vars , data ) { + + if ( vars.dev.value ) print.time("filtering data") + + var availableKeys = d3.keys(vars.data.keys || {}) + + if ( "attrs" in vars ) { + availableKeys = availableKeys.concat(d3.keys(vars.attrs.keys || {})) + } + + data = data.filter(function(d){ + var val = fetchValue(vars, d, vars.id.value); + return val !== null; + }); + + var typeReqs = vars.types[vars.type.value].requirements || []; + + vars.data.filters.forEach( function( key ) { + + if (availableKeys.indexOf(vars[key].value) >= 0 && + typeReqs.indexOf(key) >= 0) { + + data = data.filter( function( d ) { + + var val = fetchValue(vars,d,vars[key].value); + + if (key === "y" && vars.y2.value && val === null) { + val = fetchValue(vars,d,vars.y2.value); + } + else if (key === "x" && vars.x2.value && val === null) { + val = fetchValue(vars,d,vars.x2.value); + } + + if ( key === "size" ) { + return typeof val === "number" + } + else { + return val !== null + } + + }) + + } + + }); + + // if "solo", only check against "solo" (disregard "mute") + var key = vars.data.solo.length ? "solo" : "mute"; + + if (vars.data[key].length) { + + vars.data[key].forEach(function(v) { + + function test_value(val) { + + var arr = vars[v][key].value; + + var match = false; + arr.forEach(function(f){ + if (typeof f === "function") { + match = f(val); + } + else if (f === val) { + match = true; + } + + }) + + return key === "solo" ? match : !match; + + } + + function filter_data(d, flat) { + if (!flat && vars[v].nesting) { + var nesting = vars[v].nesting; + if (validObject(nesting)) { + nesting = d3.values(nesting); + } + for (var n = 0; n < nesting.length; n++) { + var new_data = d.filter(function(dd){ + return test_value(fetchValue(vars, dd, nesting[n])); + }); + if (new_data.length) d = new_data; + } + } + else { + d = d.filter(function(dd){ + return test_value(fetchValue(vars, dd, vars[v].value)); + }); + } + return d; + } + + data = filter_data(data); + + if ( v === "id" ) { + + if ("nodes" in vars && vars.nodes.value) { + if ( vars.dev.value ) print.time("filtering nodes") + vars.nodes.restricted = filter_data(vars.nodes.value); + if ( vars.dev.value ) print.timeEnd("filtering nodes") + } + + if ("edges" in vars && vars.edges.value) { + if ( vars.dev.value ) print.time("filtering edges") + vars.edges.restricted = vars.edges.value.filter(function(d){ + var points = filter_data([d[vars.edges.source], d[vars.edges.target]]); + return points.length === 2; + }) + if ( vars.dev.value ) print.timeEnd("filtering edges") + } + + } + + }) + + } + else if ("nodes" in vars) { + vars.nodes.restricted = undefined; + vars.edges.restricted = undefined; + } + + if ( vars.dev.value ) print.timeEnd("filtering data") + + return data + +} + +},{"../../object/validate.coffee":172,"../console/print.coffee":52,"../fetch/value.coffee":67}],56:[function(require,module,exports){ +var dataNest = require("./nest.js"), + fetchValue = require("../fetch/value.coffee"), + print = require("../console/print.coffee"), + uniques = require("../../util/uniques.coffee"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Formats raw data by time and nesting +//------------------------------------------------------------------------------ +module.exports = function( vars ) { + + var timerString; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Gets all unique time values + //---------------------------------------------------------------------------- + vars.data.time = {"values": []}; + if (vars.time && vars.time.value) { + + if ( vars.dev.value ) { + timerString = "analyzing time periods"; + print.time( timerString ); + } + + vars.data.time.values = uniques(vars.data.value, vars.time.value, fetchValue, vars); + + vars.data.time.values.sort(function(a,b){ return a-b; }); + + var step = []; + vars.data.time.values.forEach(function(y,i){ + if (i !== 0) { + var prev = vars.data.time.values[i-1]; + step.push(y-prev); + if (i === vars.data.time.values.length - 1) { + vars.data.time.total = y - vars.data.time.values[0]; + } + } + }); + + step = d3.min(step); + vars.data.time.step = step; + + var periods = ["Milliseconds","Seconds","Minutes","Hours","Date","Month","FullYear"], + conversions = [1000,60,60,24,30,12,1]; + + vars.data.time.periods = periods; + + var getDiff = function(start,end,i) { + + if (!vars.data.time.stepDivider) { + arr = conversions.slice(0,i); + if (arr.length) { + vars.data.time.stepDivider = arr.reduce(function(a,b){ return a*b; }); + } + else { + vars.data.time.stepDivider = 1; + } + } + + return Math.round(Math.floor(end-start)/vars.data.time.stepDivider); + + }; + + var total = vars.data.time.total; + periods.forEach(function(p,i){ + var c = p === "Date" ? 28 : conversions[i]; + if (!vars.data.time.stepType && (i === periods.length-1 || Math.round(step) < c)) { + vars.data.time.stepType = p; + var start = vars.data.time.values[0], + end = vars.data.time.values[vars.data.time.values.length-1]; + vars.data.time.stepIntervals = getDiff(start,end,i); + } + + if (!vars.data.time.totalType && (i === periods.length-1 || Math.round(total) < c)) { + vars.data.time.totalType = p; + } + + step = step/c; + total = total/c; + }); + + vars.data.time.values.forEach(function(y,i){ + if (i !== 0) { + var prev = vars.data.time.values[0]; + vars.data.time.dataSteps.push(getDiff(prev,y,periods.indexOf(vars.data.time.stepType))); + } + else { + vars.data.time.dataSteps = [0]; + } + }); + + var userFormat = vars.time.format.value, + locale = vars.format.locale.value, + functions = [ + function(d) { return d.getMilliseconds(); }, + function(d) { return d.getSeconds(); }, + function(d) { return d.getMinutes(); }, + function(d) { return d.getHours(); }, + function(d) { return d.getDate() != 1; }, + function(d) { return d.getMonth(); }, + function(d) { return true; } + ]; + + vars.data.time.functions = functions; + + var getFormat = function(s,t,small) { + + if (s === t) { + return small && locale.timeFormat[s+"Small"] ? locale.timeFormat[s+"Small"] : locale.timeFormat[s]; + } + else { + if (periods.indexOf(s) >= 4 || periods.indexOf(t) <= 3) { + return locale.timeFormat[t+"-"+s]; + } + else { + + var format; + + if (t === "Date") { + format = locale.timeFormat[t]; + } + else { + format = locale.timeFormat[t+"-Date"]; + } + + if (s === "Hours") { + return format +" "+ locale.timeFormat[s]; + } + else { + return format +" "+ locale.timeFormat["Hours-"+s]; + } + + } + } + + }; + + vars.data.time.getFormat = getFormat; + + if (userFormat) { + + if (typeof userFormat === "string") { + vars.data.time.format = d3.locale(locale.format).timeFormat(userFormat); + } + else if (typeof userFormat === "function") { + vars.data.time.format = userFormat; + } + else if (userFormat instanceof Array) { + vars.data.time.format = d3.locale(locale.format).timeFormat.multi(userFormat); + } + vars.data.time.multiFormat = vars.data.time.format; + + } + else { + + var stepType = vars.data.time.stepType, + totalType = vars.data.time.totalType; + + var multi = []; + + for (var p = periods.indexOf(stepType); p <= periods.indexOf(totalType); p++) { + var prev = p-1 < periods.indexOf(stepType) ? periods[p] : periods[p-1]; + var small = periods[p] === prev && stepType !== totalType; + var format = getFormat(prev,periods[p],small); + multi.push([format,functions[p]]); + } + + vars.data.time.format = d3.locale(locale.format).timeFormat(getFormat(stepType,totalType)); + if (multi.length > 1) { + multi[multi.length-1][1] = function (d) { return true; } + vars.data.time.multiFormat = d3.locale(locale.format).timeFormat.multi(multi); + } + else { + vars.data.time.multiFormat = vars.data.time.format; + } + + } + + vars.data.time.ticks = []; + var min = d3.min(vars.data.time.values); + var max = d3.max(vars.data.time.values); + for (var s = 0; s <= vars.data.time.stepIntervals; s++) { + var m = new Date(min); + m["set"+vars.data.time.stepType](m["get"+vars.data.time.stepType]() + s); + if (m <= max) vars.data.time.ticks.push(m); + } + + if ( vars.dev.value ) print.timeEnd( timerString ); + + } + + if ( vars.dev.value ) { + timerString = "nesting data by time and depths"; + print.time( timerString ); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Gets all unique time values + //---------------------------------------------------------------------------- + vars.data.nested = {}; + if (vars.data.time.values.length === 0) { + + vars.data.nested.all = {}; + vars.id.nesting.forEach( function( depth , i ) { + + var nestingDepth = vars.id.nesting.slice( 0 , i + 1 ); + vars.data.nested.all[ depth ] = dataNest(vars, vars.data.value, nestingDepth); + + }); + + } + else { + + var timeData = vars.data.value.reduce(function(o, d){ + var ms = fetchValue(vars, d, vars.time.value).getTime(); + if (!(ms in o)) o[ms] = []; + o[ms].push(d); + return o; + }, {}); + + vars.data.time.values.forEach( function( t ) { + + var ms = t.getTime(); + + vars.data.nested[ms] = {}; + + vars.id.nesting.forEach( function( depth , i ) { + var nestingDepth = vars.id.nesting.slice(0, i + 1); + vars.data.nested[ ms ][ depth ] = dataNest(vars, timeData[ms], nestingDepth); + }); + + }); + + } + + if ( vars.dev.value ) print.timeEnd( timerString ); + +}; + +},{"../../util/uniques.coffee":210,"../console/print.coffee":52,"../fetch/value.coffee":67,"./nest.js":60}],57:[function(require,module,exports){ +var fetchValue; + +fetchValue = require("../fetch/value.coffee"); + +module.exports = function(vars, data, nesting) { + var d, groupedData, i, j, k, len, len1, n, strippedData, val; + groupedData = d3.nest(); + if (vars.id.grouping.value) { + if (nesting === void 0) { + nesting = vars.id.nesting; + } + for (i = j = 0, len = nesting.length; j < len; i = ++j) { + n = nesting[i]; + if (i < vars.depth.value) { + (function(n) { + return groupedData.key(function(d) { + return fetchValue(vars, d.d3plus, n); + }); + })(n); + } + } + } + strippedData = []; + for (k = 0, len1 = data.length; k < len1; k++) { + d = data[k]; + val = vars.size.value ? fetchValue(vars, d, vars.size.value) : 1; + if (val && typeof val === "number" && val > 0) { + delete d.d3plus.r; + delete d.d3plus.x; + delete d.d3plus.y; + strippedData.push({ + d3plus: d, + id: d[vars.id.value], + value: val + }); + } + } + return groupedData.entries(strippedData); +}; + + +},{"../fetch/value.coffee":67}],58:[function(require,module,exports){ +var print, validObject, + indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; + +print = require("../console/print.coffee"); + +validObject = require("../../object/validate.coffee"); + +module.exports = function(vars, type) { + var get_keys, k, kk, lengthMatch, ref, ref1, timerString, v, vv; + timerString = type + " key analysis"; + if (vars.dev.value) { + print.time(timerString); + } + vars[type].keys = {}; + get_keys = function(arr) { + var a, i, k, len, results, results1, v; + if (arr instanceof Array) { + results = []; + for (i = 0, len = arr.length; i < len; i++) { + a = arr[i]; + results.push(get_keys(a)); + } + return results; + } else if (validObject(arr)) { + results1 = []; + for (k in arr) { + v = arr[k]; + if (k.indexOf("d3plus") !== 0 && !(indexOf.call(vars[type].keys, k) >= 0) && v !== null) { + results1.push(vars[type].keys[k] = typeof v); + } else { + results1.push(void 0); + } + } + return results1; + } + }; + if (validObject(vars[type].value)) { + lengthMatch = d3.keys(vars[type].value).length === vars.id.nesting.length; + ref = vars[type].value; + for (k in ref) { + v = ref[k]; + if (lengthMatch && vars.id.nesting.indexOf(k) >= 0 && validObject(v)) { + for (kk in v) { + vv = v[kk]; + get_keys(vv); + } + } else { + get_keys(v); + } + } + } else { + ref1 = vars[type].value; + for (k in ref1) { + v = ref1[k]; + get_keys(v); + } + } + if (vars.dev.value) { + return print.time(timerString); + } +}; + + +},{"../../object/validate.coffee":172,"../console/print.coffee":52}],59:[function(require,module,exports){ +var print, validObject; + +print = require("../console/print.coffee"); + +validObject = require("../../object/validate.coffee"); + +module.exports = function(vars, key, next) { + var consoleMessage, fileType, parser, url; + consoleMessage = vars.dev.value; + if (consoleMessage) { + print.time("loading " + key); + } + url = vars[key].url; + if (!vars[key].filetype.value) { + fileType = url.slice(url.length - 5).split("."); + if (fileType.length > 1) { + fileType = fileType[1]; + } else { + fileType = false; + } + if (fileType) { + if (fileType === "txt") { + fileType = "text"; + } + if (vars[key].filetype.accepted.indexOf(fileType) < 0) { + fileType = "json"; + } + } else { + fileType = "json"; + } + } else { + fileType = vars[key].filetype.value; + } + if (fileType === "dsv") { + parser = d3.dsv(vars[key].delimiter.value, "text/plain"); + } else { + parser = d3[fileType]; + } + return parser(url, function(error, data) { + var k, ret; + if (!error && data) { + if (typeof vars[key].callback === "function") { + ret = vars[key].callback(data); + if (ret) { + if (validObject(ret) && key in ret) { + for (k in ret) { + if (k in vars) { + vars[k].value = ret[k]; + } + } + } else { + vars[key].value = ret; + } + } + } else { + vars[key].value = data; + } + if (["json"].indexOf(fileType) < 0) { + vars[key].value.forEach(function(d) { + var results; + results = []; + for (k in d) { + if (!isNaN(d[k])) { + results.push(d[k] = parseFloat(d[k])); + } else if (d[k].toLowerCase() === "false") { + results.push(d[k] = false); + } else if (d[k].toLowerCase() === "true") { + results.push(d[k] = true); + } else if (d[k].toLowerCase() === "null") { + results.push(d[k] = null); + } else { + if (d[k].toLowerCase() === "undefined") { + results.push(d[k] = void 0); + } else { + results.push(void 0); + } + } + } + return results; + }); + } + vars[key].changed = true; + vars[key].loaded = true; + } else { + vars.error.internal = "Could not load data from: \"" + url + "\""; + } + if (consoleMessage) { + print.timeEnd("loading " + key); + } + return next(); + }); +}; + + +},{"../../object/validate.coffee":172,"../console/print.coffee":52}],60:[function(require,module,exports){ +var fetchValue = require("../fetch/value.coffee"), + validObject = require("../../object/validate.coffee"), + uniqueValues = require("../../util/uniques.coffee"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Nests and groups the data. +//------------------------------------------------------------------------------ +var dataNest = function(vars, flatData, nestingLevels, discrete) { + + if (discrete === undefined) discrete = true; + + var nestedData = d3.nest(), + groupedData = [], + segments = "temp" in vars ? [ "active" , "temp" , "total" ] : []; + + if (!nestingLevels.length) { + nestedData.key(function(d){ return true; }); + } + else { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Loop through each nesting level. + //---------------------------------------------------------------------------- + nestingLevels.forEach(function(level, i){ + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create a nest key for the current level. + //-------------------------------------------------------------------------- + nestedData.key(function(d){ return fetchValue(vars, d, level); }); + + }); + + } + + if (discrete && vars.axes && vars.axes.discrete && (!vars.time || vars[vars.axes.discrete].value !== vars.time.value)) { + nestedData.key(function(d){ + return fetchValue(vars, d, vars[vars.axes.discrete].value); + }); + } + + var deepest_is_id = nestingLevels.length && vars.id.nesting.indexOf(nestingLevels[nestingLevels.length - 1]) >= 0; + var i = nestingLevels.length && deepest_is_id ? nestingLevels.length - 1 : 0; + var depthKey = deepest_is_id ? vars.id.nesting[i] : vars.depth.value; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If we're at the deepest level, create the rollup function. + //---------------------------------------------------------------------------- + nestedData.rollup(function(leaves) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If there's only 1 leaf, and it's been processed, return it as-is. + //-------------------------------------------------------------------------- + if (leaves.length === 1 && ("d3plus" in leaves[0])) { + groupedData.push(leaves[0]); + return leaves[0]; + } + + leaves = leaves.reduce(function(arr, ll){ + if (ll.values instanceof Array) { + return arr.concat(ll.values); + } + arr.push(ll); + return arr; + }, []); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create the "d3plus" object for the return variable, starting with + // just the current depth. + //-------------------------------------------------------------------------- + var returnObj = { + "d3plus": { + "data": {}, + "depth": i + } + }; + + var merged = d3.sum(leaves, function(ll){ return "d3plus" in ll && ll.d3plus.merged ? 1 : 0; }); + + if (merged === leaves.length) { + for (var ll = 0; ll < leaves.length; ll++) { + var l = leaves[ll]; + if (!returnObj.d3plus.merged) returnObj.d3plus.merged = []; + returnObj.d3plus.merged = returnObj.d3plus.merged.concat(l.d3plus.merged); + if (l.d3plus.text) returnObj.d3plus.text = l.d3plus.text; + } + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create a reference sum for the 3 different "segment" variables. + //-------------------------------------------------------------------------- + for (var s = 0; s < segments.length; s++) { + + var c = segments[s]; + var segmentAgg = vars.aggs && vars.aggs.value[key] ? vars.aggs.value[key] : "sum"; + + if ("d3plus" in leaves[0] && c in leaves[0].d3plus) { + returnObj.d3plus[c] = d3.sum(leaves, function(d){ + return d.d3plus[c]; + }); + } + else if (typeof segmentAgg === "function") { + returnObj.d3plus[c] = segmentAgg(leaves); + } + else { + + returnObj.d3plus[c] = d3[segmentAgg](leaves, function(d) { + + var a = c === "total" ? 1 : 0; + if (vars[c].value) { + a = fetchValue(vars, d, vars[c].value); + if (typeof a !== "number") a = a ? 1 : 0; + } + return a; + + }); + + } + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Aggregate all values detected in the data. + //-------------------------------------------------------------------------- + for (var key in vars.data.keys) { + + if (key in returnObj.d3plus.data) { + returnObj[key] = returnObj.d3plus[key]; + } + else { + + var agg = vars.aggs && vars.aggs.value[key] ? vars.aggs.value[key] : "sum", + aggType = typeof agg, + keyType = vars.data.keys[key], + idKey = vars.id.nesting.indexOf(key) >= 0, + timeKey = "time" in vars && key === vars.time.value; + + if (key in returnObj.d3plus.data) { + returnObj[key] = returnObj.d3plus[key]; + } + else if (aggType === "function") { + returnObj[key] = vars.aggs.value[key](leaves); + } + else if (timeKey) { + returnObj[key] = parseDates(uniqueValues(leaves, key)); + } + else if (vars.axes && vars.axes.discrete && vars[vars.axes.discrete].value === key) { + returnObj[key] = uniqueValues(leaves, key); + } + else if (keyType === "number" && aggType === "string" && !idKey) { + var vals = leaves.map(function(d){ return d[key]; }); + vals = vals.filter(function(d){ return typeof d === keyType; }); + if (vals.length) returnObj[key] = d3[agg](vals); + } + else { + + var testVals = checkVal(leaves, key); + var keyValues = testVals.length === 1 ? testVals[0][key] + : uniqueValues(testVals, key); + + if (testVals.length === 1) { + returnObj[key] = keyValues; + } + else if (keyValues && keyValues.length) { + + if (!(keyValues instanceof Array)) { + keyValues = [keyValues]; + } + + if (idKey && vars.id.nesting.indexOf(key) > i) { + // if (idKey && vars.id.nesting.indexOf(key) > i && keyValues.length > 1) { + // if (nestingLevels.length == 1 && testVals.length > leaves.length) { + // var newNesting = nestingLevels.concat(key); + // testVals = dataNest(vars,testVals,newNesting); + // } + returnObj[key] = testVals; + } + else { + + returnObj[key] = keyValues; + + } + + } + else if (idKey) { + var endPoint = vars.id.nesting.indexOf(key) - 1; + if (endPoint >= i && (!("endPoint" in returnObj.d3plus) || returnObj.d3plus.endPoint > i)) { + returnObj.d3plus.endPoint = i; + } + } + + } + + } + + if (key in returnObj && returnObj[key] instanceof Array && returnObj[key].length === 1) { + returnObj[key] = returnObj[key][0]; + } + + } + + for (var lll = 0; lll < nestingLevels.length; lll++) { + var level = nestingLevels[lll]; + if (!(level in returnObj)) { + returnObj[level] = fetchValue(vars, leaves[0], level); + } + } + + groupedData.push(returnObj); + + return returnObj; + + }); + + var find_keys = function(obj,depth,keys) { + if (obj.children) { + if (vars.data.keys[nestingLevels[depth]] == "number") { + obj.key = parseFloat(obj.key); + } + keys[nestingLevels[depth]] = obj.key; + delete obj.key; + for ( var k in keys ) { + obj[k] = keys[k]; + } + depth++; + obj.children.forEach(function(c){ + find_keys(c,depth,keys); + }); + } + }; + + nestedData = nestedData + .entries(flatData) + .map(rename_key_value) + .map(function(obj){ + find_keys(obj,0,{}); + return obj; + }); + + return groupedData; + +}; + +var checkVal = function(leaves, key) { + + var returnVals = []; + + function run(obj) { + if (obj instanceof Array) { + obj.forEach(run); + } + else if (validObject(obj) && key in obj) { + if (obj[key] instanceof Array) { + obj[key].forEach(run); + } + else { + returnVals.push(obj); + } + } + } + + run(leaves); + + return returnVals; + +}; + +var parseDates = function(dateArray) { + + var dates = []; + + function checkDate(arr) { + + for (var i = 0; i < arr.length; i++) { + var d = arr[i]; + if (d) { + if (d.constructor === Array) { + checkDate(d); + } + else { + dates.push(d); + } + // if (d.constructor === Date) dates.push(d); + // else if (d.constructor === Array) { + // checkDate(d); + // } + // else { + // d = new Date(d.toString()); + // if (d !== "Invalid Date") { + // d.setTime( d.getTime() + d.getTimezoneOffset() * 60 * 1000 ); + // dates.push(d); + // } + // } + } + } + + } + + checkDate(dateArray); + + return uniqueValues(dates); + +}; + +var rename_key_value = function(obj) { + if (obj.values && obj.values.length) { + obj.children = obj.values.map(function(obj) { + return rename_key_value(obj); + }); + delete obj.values; + return obj; + } + else if(obj.values) { + return obj.values; + } + else { + return obj; + } +}; + +module.exports = dataNest; + +},{"../../object/validate.coffee":172,"../../util/uniques.coffee":210,"../fetch/value.coffee":67}],61:[function(require,module,exports){ +var arraySort = require("../../array/sort.coffee"), + dataNest = require("./nest.js"), + fetchValue = require("../fetch/value.coffee"), + fetchColor = require("../fetch/color.coffee"), + fetchText = require("../fetch/text.js"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Merges data underneath the size threshold +//------------------------------------------------------------------- +module.exports = function( vars , rawData , split ) { + + var threshold; + if ( vars.size.threshold.value === false ) { + threshold = 0; + } + else if (typeof vars.size.threshold.value === "number") { + threshold = vars.size.threshold.value; + } + else if (typeof vars.size.threshold.value === "function") { + threshold = vars.size.threshold.value(vars); + } + else if (typeof vars.types[vars.type.value].threshold === "number") { + threshold = vars.types[vars.type.value].threshold; + } + else if (typeof vars.types[vars.type.value].threshold === "function") { + threshold = vars.types[vars.type.value].threshold(vars); + } + else { + threshold = 0.02; + } + + if (typeof threshold == "number" && threshold > 0) { + + var largeEnough = [], + cutoff = vars.depth.value === 0 ? 0 : {}, + removed = [], + parents = [], + labelException = [], + largest = {}; + + var nest = d3.nest(); + + if (split) { + nest + .key(function(d){ + return fetchValue(vars, d, split); + }); + } + + nest + .rollup(function(leaves){ + var total = leaves.length; + if (vars.aggs.value[vars.size.value]) { + if (typeof vars.aggs.value[vars.size.value] == "function") { + total = vars.aggs.value[vars.size.value](leaves); + } + else if (typeof vars.aggs.value[vars.size.value] == "string") { + total = d3[vars.aggs.value[vars.size.value]](leaves,function(l){ + return fetchValue(vars,l,vars.size.value); + }); + } + } + else { + total = d3.sum(leaves,function(l){ + return fetchValue(vars,l,vars.size.value); + }); + } + var x = split ? fetchValue(vars,leaves[0],split) : "all"; + largest[x] = total; + return total; + }) + .entries(rawData); + + rawData.forEach(function(d){ + var id = fetchValue(vars, d, vars.id.value), + val = fetchValue(vars, d, vars.size.value), + x = split ? fetchValue(vars, d, split) : "all", + allowed = val/largest[x] >= threshold; + + if (allowed && largeEnough.indexOf(id) < 0) { + largeEnough.push(id); + if (vars.depth.value) { + var p = fetchValue(vars, d, vars.id.nesting[vars.depth.value-1]); + if (parents.indexOf(p) < 0) { + parents.push(p); + } + } + } + + }); + + var filteredData = rawData.filter(function(d){ + + var id = fetchValue(vars, d, vars.id.value), + allowed = largeEnough.indexOf(id) >= 0; + + var p = vars.depth.value ? + fetchValue(vars, d, vars.id.nesting[vars.depth.value-1]) : + null; + + if (p !== null && parents.indexOf(p) < 0 && labelException.indexOf(p) < 0) { + labelException.push(p); + } + + if (!allowed) { + var val = fetchValue(vars, d, vars.size.value); + if (val > 0) { + if (vars.depth.value === 0) { + if (val > cutoff) cutoff = val; + } + else { + if (!(p in cutoff)) cutoff[p] = 0; + if (val > cutoff[p]) cutoff[p] = val; + } + removed.push(d); + } + } + return allowed; + + }); + + if ( removed.length > 1 ) { + + removed = arraySort( removed , vars.size.value , "desc" , [] , vars ); + + var levels = vars.id.nesting.slice(0,vars.depth.value); + if (vars.types[vars.type.value].requirements.indexOf(vars.axes.discrete) >= 0) { + levels.push(vars[vars.axes.discrete].value); + } + var merged = dataNest(vars, removed, levels); + + merged.forEach(function(m){ + + var parent = vars.id.nesting[vars.depth.value-1]; + var p_id = fetchValue(vars, m, parent); + children = parent ? removed.filter(function(r){ + return fetchValue(vars, r, parent) === p_id; + }) : removed; + + if (children.length > 1) { + + vars.id.nesting.forEach(function(d,i){ + + if (vars.depth.value == i) { + var prev = m[d]; + if ( typeof prev === "string" ) { + m[d] = "d3plus_other_"+prev; + } + else { + m[d] = "d3plus_other"; + } + } + else if (i > vars.depth.value) { + delete m[d]; + } + }); + + if (vars.color.value && vars.color.type === "string") { + if (vars.depth.value === 0) { + m[vars.color.value] = vars.color.missing; + } + else { + m[vars.color.value] = fetchValue(vars,p_id,vars.color.value,parent); + } + } + + if (vars.icon.value) { + m[vars.icon.value] = fetchValue(vars,p_id,vars.icon.value,parent); + } + + if (p_id) { + m.d3plus.depth = vars.depth.value; + } + + var textLabel; + if (vars.depth.value === 0) { + textLabel = vars.format.value(vars.format.locale.value.ui.values, {"key": "threshold", "vars": vars}); + textLabel += " < "+vars.format.value(cutoff, {"key": vars.size.value, "vars": vars}); + } + else { + textLabel = fetchText(vars,m,vars.depth.value-1); + textLabel = textLabel.length ? textLabel[0].split(" < ")[0] : vars.format.value(vars.format.locale.value.ui.values, {"key": "threshold", "vars": vars}); + if (p_id, labelException.indexOf(p_id) < 0) { + textLabel += " < "+vars.format.value(cutoff[p_id], {"key": vars.size.value, "vars": vars}); + } + } + if (p_id, labelException.indexOf(p_id) < 0) { + textLabel += " ("+vars.format.value(threshold*100, {"key": "share", "vars": vars})+")"; + } + + m.d3plus.threshold = cutoff; + m.d3plus.merged = children; + + if (vars.text.value) { + m[vars.text.value] = textLabel; + } + m.d3plus.text = textLabel; + + } + + }); + + } + else { + merged = removed; + } + + return filteredData.concat(merged); + + } + + return rawData; + +}; + +},{"../../array/sort.coffee":34,"../fetch/color.coffee":63,"../fetch/text.js":66,"../fetch/value.coffee":67,"./nest.js":60}],62:[function(require,module,exports){ +var sizes; + +sizes = require("../../font/sizes.coffee"); + +module.exports = function(vars, opts) { + var f, format, func, getFormat, limit, locale, p, periods, pp, prev, render, small, step, style, time, total, vals, values; + values = opts.values || vars.data.time.ticks; + style = opts.style || {}; + limit = opts.limit || vars.width.value; + time = {}; + periods = vars.data.time.periods; + step = vars.data.time.stepType; + total = vars.data.time.totalType; + func = vars.data.time.functions; + getFormat = vars.data.time.getFormat; + locale = vars.format.locale.value.format; + if (vars.time.format.value) { + time.format = vars.data.time.format; + time.values = values; + time.sizes = sizes(values.map(function(v) { + return time.format(v); + }), style); + } else { + p = periods.indexOf(step); + while (p <= periods.indexOf(total)) { + vals = values.filter(function(t) { + var match, pp; + if (p === periods.indexOf(step)) { + return true; + } + match = true; + pp = p - 1; + if (p < 0) { + return true; + } + while (pp >= periods.indexOf(step)) { + if (!match) { + break; + } + match = !func[pp](t); + pp--; + } + return match; + }); + if (periods[p] === total) { + format = d3.locale(locale).timeFormat(getFormat(periods[p], total)); + } else { + pp = p; + format = []; + while (pp <= periods.indexOf(total)) { + prev = pp - 1 < periods.indexOf(step) ? pp : pp - 1; + prev = periods[prev]; + small = periods[pp] === prev && step !== total; + f = getFormat(prev, periods[pp], small); + format.push([f, func[pp]]); + pp++; + } + format[format.length - 1][1] = function() { + return true; + }; + format = d3.locale(locale).timeFormat.multi(format); + } + render = sizes(vals.map(function(v) { + return format(v); + }), style); + if (d3.sum(render, function(r) { + return r.width; + }) < limit || p === periods.indexOf(total)) { + time.format = format; + time.values = vals; + time.sizes = render; + break; + } + p++; + } + } + return time; +}; + + +},{"../../font/sizes.coffee":102}],63:[function(require,module,exports){ +var fetchValue, getColor, getRandom, randomColor, uniques, validColor, validObject; + +fetchValue = require("./value.coffee"); + +randomColor = require("../../color/random.coffee"); + +validColor = require("../../color/validate.coffee"); + +validObject = require("../../object/validate.coffee"); + +uniques = require("../../util/uniques.coffee"); + +module.exports = function(vars, id, level) { + var color, colorLevel, colors, i, obj, value; + obj = validObject(id); + if (obj && "d3plus" in id && "color" in id.d3plus) { + return id.d3plus.color; + } + if (level === void 0) { + level = vars.id.value; + } + if (typeof level === "number") { + level = vars.id.nesting[level]; + } + if (!vars.color.value) { + return getRandom(vars, id, level); + } else { + colors = []; + i = vars.id.nesting.indexOf(level); + while (i >= 0) { + colorLevel = vars.id.nesting[i]; + value = uniques(id, vars.color.value, fetchValue, vars, colorLevel); + if (value.length === 1) { + value = value[0]; + } + if (!(value instanceof Array) && value !== void 0 && value !== null) { + color = getColor(vars, id, value, level); + if (colors.indexOf(color) < 0) { + colors.push(color); + } + break; + } + i--; + } + if (colors.length === 1) { + return colors[0]; + } else { + return vars.color.missing; + } + } +}; + +getColor = function(vars, id, color, level) { + if (!color) { + if (vars.color.value && typeof vars.color.valueScale === "function") { + return vars.color.valueScale(0); + } + return getRandom(vars, id, level); + } else if (!vars.color.valueScale) { + if (validColor(color)) { + return color; + } else { + return getRandom(vars, color, level); + } + } else { + return vars.color.valueScale(color); + } +}; + +getRandom = function(vars, c, level) { + if (validObject(c)) { + c = fetchValue(vars, c, level); + } + if (c instanceof Array) { + c = c[0]; + } + return randomColor(c, vars.color.scale.value); +}; + + +},{"../../color/random.coffee":47,"../../color/validate.coffee":51,"../../object/validate.coffee":172,"../../util/uniques.coffee":210,"./value.coffee":67}],64:[function(require,module,exports){ +var dataFilter = require("../data/filter.js"), + dataNest = require("../data/nest.js"), + print = require("../console/print.coffee"), + stringFormat = require("../../string/format.js"), + stringList = require("../../string/list.coffee"); + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Fetches specific years of data +//------------------------------------------------------------------- +module.exports = function(vars, years, depth) { + + if (!vars.data.value) return []; + + if (depth === undefined) depth = vars.depth.value; + var nestLevel = vars.id.nesting[depth]; + + if (years && !(years instanceof Array)) years = [years]; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If "years" have not been requested, determine the years using .time() + // solo and mute + //---------------------------------------------------------------------------- + if (!years && "time" in vars) { + + years = []; + + var key = vars.time.solo.value.length ? "solo" : "mute", + filterList = vars.time[key].value; + + if (filterList.length) { + + years = []; + for (var yi = 0; yi < filterList.length; yi++) { + var y = filterList[yi]; + + if (typeof y === "function") { + for (var ti = 0; ti < vars.data.time.values.length; ti++) { + var ms = vars.data.time.values[ti].getTime(); + if (y(ms)) years.push(ms); + } + } + else if (y.constructor === Date) { + years.push(new Date(y).getTime()); + } + else { + y += ""; + if (y.length === 4 && parseInt(y)+"" === y) y = y + "/01/01"; + var d = new Date(y); + if (d !== "Invalid Date") { + // d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000); + years.push(d.getTime()); + } + } + + } + + if ( key === "mute" ) { + years = vars.data.time.values.filter(function( t ){ + return years.indexOf(t.getTime()) < 0; + }); + } + + } + else years.push("all"); + + } + else { + years = ["all"]; + } + + if (years.indexOf("all") >= 0 && vars.data.time.values.length) { + years = vars.data.time.values.slice(0); + for (var i = 0; i < years.length; i++) { + years[i] = years[i].getTime(); + } + } + + var cacheID = [ vars.type.value , nestLevel , depth ] + .concat( vars.data.filters ) + .concat( years ), + filter = vars.data.solo.length ? "solo" : "mute", + cacheKeys = d3.keys(vars.data.cache), + vizFilter = vars.types[vars.type.value].filter || undefined; + + if ( vars.data[filter].length ) { + for (var di = 0; di < vars.data[filter].length; di++) { + var f = vars.data[filter][di]; + var vals = vars[f][filter].value.slice(0); + vals.unshift(f); + vals.unshift(filter); + cacheID = cacheID.concat(vals); + } + } + + if (vars.axes && vars.axes.discrete) cacheID.push(vars.axes.discrete); + + cacheID = cacheID.join("_"); + vars.data.cacheID = cacheID; + + var match = false; + + for (var c = 0 ; c < cacheKeys.length ; c++) { + + var matchKey = cacheKeys[c].split("_").slice(1).join("_"); + + if ( matchKey === cacheID ) { + cacheID = new Date().getTime() + "_" + cacheID; + vars.data.cache[cacheID] = vars.data.cache[cacheKeys[c]]; + delete vars.data.cache[cacheKeys[c]]; + break; + } + + } + + var returnData; + + if ( vars.data.cache[cacheID] ) { + + if ( vars.dev.value ) print.comment("data already cached"); + + returnData = vars.data.cache[cacheID].data; + if ("nodes" in vars) { + vars.nodes.restricted = vars.data.cache[cacheID].nodes; + vars.edges.restricted = vars.data.cache[cacheID].edges; + } + + if ( typeof vizFilter === "function" ) { + returnData = vizFilter( vars , returnData ); + } + + return returnData; + + } + else { + + var missing = []; + returnData = []; + + if (vars.data.value && vars.data.value.length) { + + for (var yz = 0; yz < years.length; yz++) { + var year = years[yz]; + if (vars.data.nested[year]) { + returnData = returnData.concat(vars.data.nested[year][nestLevel]); + } + else { + missing.push(year); + } + } + + } + + if (returnData.length === 0 && missing.length && !vars.error.internal) { + + if (missing.length > 1) { + missing = d3.extent(missing); + } + + missing = missing.map(function(m){ + return vars.data.time.format(new Date(m)); + }); + missing = missing.join(" - "); + + var str = vars.format.locale.value.error.dataYear, + and = vars.format.locale.value.ui.and; + missing = stringList(missing,and); + vars.error.internal = stringFormat(str,missing); + vars.time.missing = true; + + } + else { + + if (vars.time) vars.time.missing = false; + + if ( years.length > 1 ) { + + var separated = false; + ["x", "y", "x2", "y2"].forEach(function(a){ + if (vars[a].value === vars.time.value && + vars[a].scale.value === "discrete" ) { + separated = true; + } + }); + + if (!separated) { + var nested = vars.id.nesting.slice(0,depth+1); + returnData = dataNest(vars, returnData, nested); + } + + } + + if (!returnData) { + returnData = []; + } + else { + returnData = dataFilter(vars, returnData); + } + + if ( cacheKeys.length === 20 ) { + cacheKeys.sort(); + delete vars.data.cache[cacheKeys[0]]; + } + + cacheID = new Date().getTime() + "_" + cacheID; + vars.data.cache[cacheID] = {"data": returnData}; + if ("nodes" in vars) { + vars.data.cache[cacheID].nodes = vars.nodes.restricted; + vars.data.cache[cacheID].edges = vars.edges.restricted; + } + + if ( typeof vizFilter === "function" ) { + returnData = vizFilter( vars , returnData ); + } + + if ( vars.dev.value ) print.comment("storing data in cache"); + + } + + return returnData; + + } + +}; + +},{"../../string/format.js":173,"../../string/list.coffee":174,"../console/print.coffee":52,"../data/filter.js":55,"../data/nest.js":60}],65:[function(require,module,exports){ +var fetchColor, fetchText, fetchValue; + +fetchValue = require("./value.coffee"); + +fetchColor = require("./color.coffee"); + +fetchText = require("./text.js"); + +module.exports = function(vars, d, keys, colors, depth) { + var agg, i, key, len, obj, value; + if (!(keys instanceof Array)) { + keys = [keys]; + } + if (!(colors instanceof Array)) { + colors = [colors]; + } + if (vars) { + if (depth === void 0) { + depth = vars.id.value; + } else if (typeof depth !== "number") { + depth = vars.id.nesting.indexOf(depth); + } + } + obj = {}; + for (i = 0, len = keys.length; i < len; i++) { + key = keys[i]; + if (vars) { + if (colors.indexOf(key) >= 0) { + value = fetchColor(vars, d, depth); + } else if (key === vars.text.value) { + value = fetchText(vars, d, depth); + } else if (d3.keys(d).length === 3 && d["d3plus"] && d["key"] && d["values"]) { + value = fetchValue(vars, d.values.map(function(dd) { + return dd.d3plus; + }), key, depth); + } else { + value = fetchValue(vars, d, key, depth); + } + } else { + value = d[key]; + } + if ([vars.data.keys[key], vars.attrs.keys[key]].indexOf("number") >= 0) { + agg = vars.order.agg.value || vars.aggs.value[key] || "sum"; + if (agg.constructor === String) { + agg = d3[agg]; + } + if (!(value instanceof Array)) { + value = [value]; + } + value = agg(value); + } else { + if (value instanceof Array) { + value = value[0]; + } + value = typeof value === "string" ? value.toLowerCase() : value; + } + obj[key] = value; + } + return obj; +}; + + +},{"./color.coffee":63,"./text.js":66,"./value.coffee":67}],66:[function(require,module,exports){ +var fetchValue = require("./value.coffee"), + validObject = require("../../object/validate.coffee"), + uniques = require("../../util/uniques.coffee"); + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Get array of available text values +//------------------------------------------------------------------------------ +module.exports = function(vars, obj, depth) { + + if (typeof depth !== "number") depth = vars.depth.value; + + var key = vars.id.nesting[depth], textKeys; + + if ( vars.text.nesting && validObject(vars.text.nesting) ) { + if ( vars.text.nesting[key] ) { + textKeys = vars.text.nesting[key]; + } + else { + textKeys = vars.text.value; + } + } + else { + textKeys = []; + if (vars.text.value && depth === vars.depth.value) textKeys.push(vars.text.value); + textKeys.push(key); + } + + if ( !(textKeys instanceof Array) ) { + textKeys = [ textKeys ]; + } + + var names = []; + + if (validObject(obj) && "d3plus" in obj && obj.d3plus.text) { + names.push(obj.d3plus.text.toString()); + names.push(vars.format.value(obj.d3plus.text.toString(), {"vars": vars, "data": obj})); + } + else { + + var formatObj = validObject(obj) ? obj : undefined; + + if (formatObj && obj[vars.id.value] instanceof Array) { + obj = obj[vars.id.value]; + } + else if (!(obj instanceof Array)) { + obj = [obj]; + } + + textKeys.forEach(function( t ){ + + var name = uniques(obj, t, fetchValue, vars, key); + + if ( name.length ) { + if (name.length > 1) { + name = name.filter(function(n){ + return (n instanceof Array) || (typeof n === "string" && n.indexOf(" < ") < 0); + }); + } + name = name.map(function(n){ + if (n instanceof Array) { + n = n.filter(function(nn){ return nn; }); + return n.map(function(nn){ + return vars.format.value(nn.toString(), {"vars": vars, "data": formatObj, "key": t}); + }); + } + else if (n) { + return vars.format.value(n.toString(), {"vars": vars, "data": formatObj, "key": t}); + } + }); + if (name.length === 1) name = name[0]; + names.push(name); + } + + }); + + } + + return names; + +}; + +},{"../../object/validate.coffee":172,"../../util/uniques.coffee":210,"./value.coffee":67}],67:[function(require,module,exports){ +var cacheInit, checkAttrs, checkData, fetch, fetchArray, filterArray, find, uniqueValues, validObject, valueParse; + +validObject = require("../../object/validate.coffee"); + +uniqueValues = require("../../util/uniques.coffee"); + +find = function(vars, node, variable, depth) { + var cache, nodeObject, returned, val; + nodeObject = validObject(node); + if (typeof variable === "function" && nodeObject) { + return variable(node, vars); + } + if (nodeObject) { + if (variable in node) { + return node[variable]; + } + cache = vars.data.cacheID + "_" + depth; + cacheInit(node, cache, vars); + if (variable in node.d3plus.data[cache]) { + return node.d3plus.data[cache][variable]; + } + if (depth in node) { + node = node[depth]; + } else if (vars.id.value in node) { + node = node[vars.id.value]; + if (depth !== variable) { + returned = checkData(vars, node, depth, vars.id.value); + } + if (returned === null || returned === void 0) { + returned = checkAttrs(vars, node, depth, vars.id.value); + } + if (returned === null || returned === void 0) { + return null; + } else if (depth === variable) { + return returned; + } + node = returned; + } else { + return null; + } + } + if (node instanceof Array && !validObject(node[0])) { + node = uniqueValues(node); + } + if (node instanceof Array && validObject(node[0])) { + val = uniqueValues(node, variable); + if (val.length) { + return val; + } + } + val = checkData(vars, node, variable, depth); + if (val) { + return val; + } + val = checkAttrs(vars, node, variable, depth); + return val; +}; + +checkData = function(vars, node, variable, depth) { + var val; + if (vars.data.viz instanceof Array && variable in vars.data.keys) { + val = uniqueValues(filterArray(vars.data.viz, node, depth), variable); + } + if (val && val.length) { + return val; + } else { + return null; + } +}; + +checkAttrs = function(vars, node, variable, depth) { + var attrList, n, val, vals; + if ("attrs" in vars && vars.attrs.value && variable in vars.attrs.keys) { + if (validObject(vars.attrs.value) && depth in vars.attrs.value) { + attrList = vars.attrs.value[depth]; + } else { + attrList = vars.attrs.value; + } + if (attrList instanceof Array) { + val = uniqueValues(filterArray(attrList, node, depth), variable); + if (val.length) { + return val; + } + } else if (node instanceof Array) { + attrList = [ + (function() { + var j, len, results; + if (n in attrList) { + results = []; + for (j = 0, len = node.length; j < len; j++) { + n = node[j]; + results.push(attrList[n]); + } + return results; + } + })() + ]; + if (attrList.length) { + vals = uniqueValues(attrList, variable); + if (vals.length) { + return vals; + } + } + } else if (node in attrList) { + return attrList[node][variable]; + } + } + return null; +}; + +filterArray = function(arr, node, depth) { + if (node instanceof Array) { + return arr.filter(function(d) { + return node.indexOf(d[depth]) >= 0; + }); + } else { + return arr.filter(function(d) { + return d[depth] === node; + }); + } +}; + +cacheInit = function(node, cache, vars) { + if (!("d3plus" in node)) { + node.d3plus = {}; + } + if (!("data" in node.d3plus)) { + node.d3plus.data = {}; + } + if (vars.data.changed || (vars.attrs && vars.attrs.changed) || !(cache in node.d3plus.data)) { + node.d3plus.data[cache] = {}; + } + return node; +}; + +valueParse = function(vars, node, depth, variable, val) { + var cache, d, i, j, len, timeVar, v; + if (val === null) { + return val; + } + timeVar = "time" in vars && vars.time.value === variable; + if (!(val instanceof Array)) { + val = [val]; + } + for (i = j = 0, len = val.length; j < len; i = ++j) { + v = val[i]; + if (timeVar && v !== null && v.constructor !== Date) { + v = v + ""; + if (v.length === 4 && parseInt(v) + "" === v) { + v += "/01/01"; + } + d = new Date(v); + if (d !== "Invalid Date") { + val[i] = d; + } + } + } + if (val.length === 1) { + val = val[0]; + } + if (val !== null && validObject(node) && typeof variable === "string" && !(variable in node)) { + cache = vars.data.cacheID + "_" + depth; + node.d3plus.data[cache][variable] = val; + } + return val; +}; + +fetchArray = function(vars, arr, variable, depth) { + var item, j, len, v, val; + val = []; + for (j = 0, len = arr.length; j < len; j++) { + item = arr[j]; + if (validObject(item)) { + v = find(vars, item, variable, depth); + val.push(valueParse(vars, item, depth, variable, v)); + } else { + val.push(item); + } + } + if (typeof val[0] !== "number") { + val = uniqueValues(val); + } + if (val.length === 1) { + return val[0]; + } else { + return val; + } +}; + +fetch = function(vars, node, variable, depth) { + var nodeObject, val; + if (!variable) { + return null; + } + if (typeof variable === "number") { + return variable; + } + nodeObject = validObject(node); + if (!depth) { + depth = vars.id.value; + } + if (nodeObject && node.values instanceof Array) { + val = fetchArray(vars, node.values, variable, depth); + } else if (nodeObject && node[variable] instanceof Array) { + val = fetchArray(vars, node[variable], variable, depth); + } else if (node instanceof Array) { + val = fetchArray(vars, node, variable, depth); + } else { + val = find(vars, node, variable, depth); + val = valueParse(vars, node, depth, variable, val); + } + return val; +}; + +module.exports = fetch; + + +},{"../../object/validate.coffee":172,"../../util/uniques.coffee":210}],68:[function(require,module,exports){ +module.exports = function(type) { + var attrs, styles, tester; + if (["div", "svg"].indexOf(type) < 0) { + type = "div"; + } + styles = { + position: "absolute", + left: "-9999px", + top: "-9999px", + visibility: "hidden", + display: "block" + }; + attrs = type === "div" ? {} : { + position: "absolute" + }; + tester = d3.select("body").selectAll(type + ".d3plus_tester").data([0]); + tester.enter().append(type).attr("class", "d3plus_tester").style(styles).attr(attrs); + return tester; +}; + + +},{}],69:[function(require,module,exports){ +module.exports = { + "format": { + "decimal": ",", + "thousands": ".", + "grouping": [3], + "currency": ["", " €"], + "dateTime": "%A, der %e. %B %Y, %X", + "date": "%d.%m.%Y", + "time": "%H:%M:%S", + "periods": ["AM", "PM"], // unused + "days": ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"], + "shortDays": ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"], + "months": ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"], + "shortMonths": ["Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"] + }, + "error": { + "accepted": "{0} ist kein gültiger {1} für {2}-Darstellungen. Benutzen Sie bitte: {3}.", + "connections": "Keine Verbindungen verfügbar für {0}.", + "data": "Keine Daten verfügbar", + "dataYear": "Für {0} sind keine Daten verfügbar.", + "lib": "{0}-Darstellungen erfordern das Laden der Bibliothek {1}.", + "libs": "{0}-Darstellungen erfordern das Laden folgender Bibliotheken: {1}.", + "method": "{0}-Darstellungen erfordern die Methode {1}.", + "methods": "Weitere Einstellungen für folgende Methoden {1} sind bei {0}-Darstellungen erforderlich." + }, + "lowercase": [ + "ein", + "ein", + "und", + "wie", + "bei", + "aber", + "durch", + "für", + "von", + "wenn", + "in", + "in", + "in der Nähe", + "noch", + "von", + "auf", + "auf", + "oder", + "pro", + "das", + "die", + "zu", + "mit", + "über", + "gegen", + "gegen." + ], + "method": { + "active": "aktive Segmente", + "color": "Farbe", + "depth": "Tiefe", + "dev": "ausführlich", + "focus": "Fokus", + "icon": "Symbol", + "id": "Kennung", + "height": "Höhe", + "labels": "Beschriftungen", + "legend": "Legende", + "margin": "Rand", + "messages": "Statusmeldungen", + "order": "Reihenfolge", + "search": "Suche", + "shape": "Form", + "size": "Größe", + "style": "Stil", + "temp": "temporäre Segmente", + "text": "Text", + "time": "Zeit", + "timeline": "Zeitleiste", + "total": "Segmente gesamt", + "type": "Typ", + "width": "Breite", + "x": "x-Achse", + "y": "y-Achse", + "zoom": "Zoom", + "mode": "Modus", + "mute": "ausblenden", + "solo": "isolieren" + }, + "time": [ + "Datum", + "Tag", + "Monat", + "Zeit", + "Jahr" + ], + "visualization": { + "bubbles": "Blasen", + "chart": "Diagramm", + "geo_map": "Karte", + "line": "Liniendiagramm", + "network": "Netzwerk", + "rings": "Ringe", + "scatter": "Punktdiagramm", + "stacked": "Gestapelte Fläche", + "tree_map": "Baumdiagramm", + "bar": "Balkendiagramm", + "box": "Boxplot", + "paths": "Pfade", + "pie": "Kreisdiagramm", + "table": "Tabelle" + }, + "ui": { + "and": "und", + "back": "zurück", + "collapse": "Zum Ausblenden klicken", + "error": "Fehler", + "expand": "Zum Einblenden klicken", + "loading": "Lade...", + "more": "{0} weitere", + "moreInfo": "Für zusätzliche Informationen klicken", + "noResults": "Keine Ergebnisse für {0} gefunden.", + "primary": "Primäre Verbindungen", + "share": "teilen", + "total": "gesamt", + "values": "Werte", + "including": "einschließlich", + "or": "oder", + "iqr": "Interquartilsabstände {0}", + "max": "Maximalwert", + "min": "Minimalwert", + "percentile": "Perzentil P{0}", + "tukey_bottom": "Unterer Ausreißer", + "tukey_top": "Oberer Ausreißer", + "quartile_first": "Unteres Quartil Q1", + "quartile_third": "Oberes Quartil Q3", + "median": "Medianwert" + }, + "message": { + "data": "analysiere Daten", + "draw": "Darstellung wird gerendert", + "initializing": "initialisiere {0}", + "loading": "Daten werden geladen", + "tooltipReset": "Tooltips zurücksetzen", + "ui": "aktualisiere Oberfläche" + }, + "uppercase": [ + "CEO", + "CEOs", + "CFO", + "CFOs", + "CNC", + "COO", + "COOs", + "CPU", + "CPUs", + "BIP", + "HVAC", + "ID", + "IT", + "FuE", + "TV", + "UI" + ] +} + +},{}],70:[function(require,module,exports){ +module.exports = { + dev: { + accepted: "{0} is not an accepted value for {1}, please use one of the following: {2}.", + deprecated: "the {0} method has been removed, please update your code to use {1}.", + noChange: "{0} was not updated because it did not change.", + noContainer: "cannot find a container on the page matching {0}.", + of: "of", + oldStyle: "style properties for {0} have now been embedded directly into .{1}().", + sameEdge: "edges cannot link to themselves. automatically removing self-referencing edge {0}.", + set: "{0} has been set.", + setLong: "{0} has been set to {1}.", + setContainer: "please define a container div using .container()" + }, + error: { + accepted: "{0} is not an accepted {1} for {2} visualizations, please use one of the following: {3}.", + connections: "no connections available for {0}.", + data: "no data available", + dataYear: "no data available for {0}.", + lib: "{0} visualizations require loading the {1} library.", + libs: "{0} visualizations require loading the following libraries: {1}.", + method: "{0} visualizations require setting the {1} method.", + methods: "{0} visualizations require setting the following methods: {1}." + }, + format: { + decimal: ".", + thousands: ",", + grouping: [3], + currency: ["$", ""], + dateTime: "%A, %B %-d, %Y %X", + date: "%-m/%-d/%Y", + time: "%I:%M:%S %p", + 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"] + }, + lowercase: ["a", "an", "and", "as", "at", "but", "by", "for", "from", "if", "in", "into", "near", "nor", "of", "on", "onto", "or", "per", "that", "the", "to", "with", "via", "vs", "vs."], + message: { + data: "analyzing data", + draw: "drawing visualization", + initializing: "initializing {0}", + loading: "loading data", + tooltipReset: "resetting tooltips", + ui: "updating ui" + }, + method: { + active: "active segments", + color: "color", + depth: "depth", + dev: "verbose", + focus: "focus", + icon: "icon", + id: "id", + height: "height", + labels: "labels", + legend: "legend", + margin: "margin", + messages: "status messages", + mode: "mode", + mute: "hide", + order: "order", + search: "search", + shape: "shape", + size: "size", + solo: "isolate", + style: "style", + temp: "temporary segments", + text: "text", + time: "time", + timeline: "timeline", + total: "total segments", + type: "type", + width: "width", + x: "x axis", + y: "y axis", + zoom: "zoom" + }, + time: ["date", "day", "month", "time", "year"], + timeFormat: { + FullYear: "%Y", + Month: "%B", + MonthSmall: "%b", + Date: "%A %-d", + DateSmall: "%-d", + Hours: "%I %p", + Minutes: "%I:%M", + Seconds: "%Ss", + Milliseconds: "%Lms", + "FullYear-Month": "%b %Y", + "FullYear-Date": "%-m/%-d/%Y", + "Month-Date": "%b %-d", + "Hours-Minutes": "%I:%M %p", + "Hours-Seconds": "%I:%M:%S %p", + "Hours-Milliseconds": "%H:%M:%S.%L", + "Minutes-Seconds": "%I:%M:%S %p", + "Minutes-Milliseconds": "%H:%M:%S.%L", + "Seconds-Milliseconds": "%H:%M:%S.%L" + }, + ui: { + and: "and", + back: "back", + collapse: "click to collapse", + error: "error", + expand: "click to expand", + including: "including", + iqr: "interquartile range for {0}", + loading: "loading...", + max: "maximum", + median: "median", + min: "minimum", + more: "{0} more", + moreInfo: "click for more info", + or: "or", + noResults: "no results matching {0}.", + percentile: "{0} percentile", + primary: "primary connections", + quartile_first: "first quartile", + quartile_third: "third quartile", + share: "share", + total: "total", + tukey_bottom: "bottom tukey", + tukey_top: "top tukey", + values: "values" + }, + uppercase: ["CEO", "CEOs", "CFO", "CFOs", "CNC", "COO", "COOs", "CPU", "CPUs", "GDP", "HVAC", "ID", "IT", "R&D", "TV", "UI"], + visualization: { + bar: "Bar Chart", + box: "Box Plot", + bubbles: "Bubbles", + chart: "Chart", + geo_map: "Geo Map", + line: "Line Plot", + network: "Network", + paths: "Paths", + pie: "Pie Chart", + rings: "Rings", + scatter: "Scatter Plot", + stacked: "Stacked Area", + table: "Table", + tree_map: "Tree Map" + } +}; + + +},{}],71:[function(require,module,exports){ +module.exports = { + "format": { + "decimal": ",", + "thousands": ".", + "grouping": [3], + "currency": ["", " €"], + "dateTime": "%A, %e de %B de %Y, %X", + "date": "%d/%m/%Y", + "time": "%H:%M:%S", + "periods": ["AM", "PM"], + "days": ["domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"], + "shortDays": ["dom", "lun", "mar", "mié", "jue", "vie", "sáb"], + "months": ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"], + "shortMonths": ["ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"] + }, + "dev": { + "accepted": "{0} no es un valor aceptado para {1}, por favor utilice uno de los siguientes: {2}.", + "deprecated": "el método {0} ha sido eliminado, por favor, actualiza tu código para utilizar {1}.", + "noChange": "{0} no se actualiza porque no cambió.", + "noContainer": "no se puede encontrar un contenedor en la página correspondiente a {0}.", + "of": "de", + "oldStyle": "propiedades de estilo para {0} ahora se han incorporado directamente en. {1} ().", + "sameEdge": "los vínculos no se pueden enlazar con si mismos. eliminando automáticamente el vínculo {0} que se autorreferencia.", + "set": "{0} se ha establecido.", + "setLong": "{0} ha sido establecido a {1}.", + "setContainer": "defina un div contenedor utilizando .container ()" + }, + "error": { + "accepted": "{0} no es un {1} aceptado para visualizaciones de {2}, por favor utilice uno de los siguientes: {3}.", + "connections": "no hay conexiones disponibles para {0}.", + "data": "No hay datos disponibles", + "dataYear": "no hay datos disponibles para {0}.", + "lib": "{0} visualizaciones requieren cargar las siguientes librerías: {1}.", + "libs": "{0} visualizaciones requieren cargar las siguientes librerías: {1}.", + "method": "{0} visualizaciones requieren establecer el ​​método {1}.", + "methods": "{0} visualizaciones requieren establecer los siguientes métodos: {1}." + }, + "lowercase": [ + "una", + "y", + "en", + "pero", + "en", + "de", + "o", + "el", + "la", + "los", + "las", + "para", + "a", + "con" + ], + "method": { + "active": "segmentos activos", + "color": "color", + "depth": "profundidad", + "dev": "detallado", + "focus": "foco", + "icon": "ícono", + "id": "id", + "height": "alto", + "labels": "rótulo", + "legend": "leyenda", + "margin": "margen", + "messages": "mensajes de estado", + "order": "orden", + "search": "búsqueda", + "shape": "forma", + "size": "tamaño", + "style": "estilo", + "temp": "segmentos temporales", + "text": "texto", + "time": "tiempo", + "timeline": "línea de tiempo", + "total": "segmentos totales", + "type": "tipo", + "width": "anchura", + "x": "eje x", + "y": "eje Y", + "zoom": "zoom", + "mode": "modo", + "mute": "ocultar", + "solo": "aislar" + }, + "time": [ + "fecha", + "día", + "mes", + "hora", + "año" + ], + "visualization": { + "bubbles": "Burbujas", + "chart": "Gráfico", + "geo_map": "Mapa", + "line": "Gráfico de linea", + "network": "Red", + "rings": "Anillos", + "scatter": "Gráfico De Dispersión", + "stacked": "Área Apilada", + "tree_map": "Tree Map", + "bar": "Gráfico De Barras", + "box": "Diagrama de Cajas", + "paths": "Caminos", + "pie": "Gráfico de Pastel", + "table": "Tabla" + }, + "ui": { + "and": "y", + "back": "atrás", + "collapse": "click para cerrar", + "error": "error", + "expand": "haga clic para ampliar", + "loading": "Cargando ...", + "more": "{0} más", + "moreInfo": "clic para más información", + "noResults": "no se encontraron resultados para {0}.", + "primary": "relaciones principales", + "share": "porcentaje", + "total": "total", + "values": "valores", + "including": "Incluyendo", + "or": "o", + "iqr": "rango intercuartil para {0}", + "max": "máximo", + "min": "mínimo", + "percentile": "{0} percentil", + "tukey_bottom": "Tukey inferior", + "tukey_top": "la parte superior de Tukey", + "quartile_first": "primer cuartil", + "quartile_third": "tercer cuartil", + "median": "mediana" + }, + "message": { + "data": "analizando los datos", + "draw": "visualizando", + "initializing": "inicializando {0}", + "loading": "cargando datos", + "tooltipReset": "restableciendo las descripciones emergentes", + "ui": "actualizando la interfaz de usuario" + }, + "uppercase": [ + "CEO", + "CEOs", + "CFO", + "CFOs", + "CNC", + "COO", + "COOs", + "CPU", + "CPUs", + "PIB", + "HVAC", + "ID", + "TI", + "I&D", + "TV", + "UI" + ] +} + +},{}],72:[function(require,module,exports){ +module.exports = { + "format": { + "decimal": ",", + "thousands": ".", + "grouping": [3], + "currency": ["", " €"], + "dateTime": "%A, le %e %B %Y, %X", + "date": "%d/%m/%Y", + "time": "%H:%M:%S", + "periods": ["AM", "PM"], // unused + "days": ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"], + "shortDays": ["dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam."], + "months": ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"], + "shortMonths": ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."] + }, + "dev": { + "accepted": "{0} n'est pas une option valide pour {1}, les valeurs possibles sont: {2}.", + "deprecated": "{0} a été éliminé de la version courante, mettez à jour votre code source avec {1}.", + "noChange": "{0} n'a pas été mis à jour car inchangé.", + "noContainer": "impossible de trouver un contenant correspondant à {0}.", + "of": "de", + "oldStyle": "les propriétés de {0} ont été imbriquées dans .{1}().", + "sameEdge": "un arc ne peut pas boucler sur lui même. L'auto-référence est automatiquement éliminée {0}.", + "set": "{0} a été mis à jour.", + "setLong": "{0} a été mis à jour à {1}.", + "setContainer": "merci de choisir un div qui utilise .container()" + }, + "error": { + "accepted": "{0} n'est pas correct {1} pour {2} visualisations, merci d'utilisez une des options suivantes: {3}.", + "connections": "Pas de connections disponibles pour {0}.", + "data": "Pas de données disponibles", + "dataYear": "Pas de données disponibles pour {0}.", + "lib": "La visualisation de {0} nécessite le chargement de la librairie {1}.", + "libs": "La visualisation de {0} nécessite le chargement des librairies {1}.", + "method": "La visualisation du {0} exige la définition de {1}.", + "methods": "La visualisation du {0} exige les définitions de {1}." + }, + "lowercase": [ + "un", + "une", + "de", + "des", + "et", + "mais", + "les", + "ou", + "pour", + "avec", + "comme", + "par", + "vers", + "si", + "dans", + "près", + "ni", + "dessus", + "que", + "le", + "la", + "via", + "sinon", + "alors" + ], + "method": { + "active": "segments actifs", + "color": "couleur", + "depth": "profondeur", + "dev": "verbeux", + "focus": "focus", + "icon": "ícone", + "id": "id", + "height": "hauteur", + "labels": "labels", + "legend": "légende", + "margin": "marge", + "messages": "messages", + "order": "ordre", + "search": "recherche", + "shape": "format", + "size": "taille", + "style": "style", + "temp": "segments temporaires", + "text": "texte", + "time": "temps", + "timeline": "ligne temporelle", + "total": "segments totaux", + "type": "type", + "width": "largeur", + "x": "axe x", + "y": "axe y", + "zoom": "zoom", + "mode": "mode", + "mute": "cacher", + "solo": "isoler" + }, + "time": [ + "année", + "date", + "jour", + "heure", + "mois" + ], + "visualization": { + "bubbles": "Bulles", + "chart": "Graphique", + "geo_map": "Carte", + "line": "Courbes", + "network": "Réseau", + "rings": "Anneaux", + "scatter": "Nuage de points", + "stacked": "Aires empilées", + "tree_map": "Arbre", + "bar": "Diagramme en barres", + "box": "Boîtes à Moustaches", + "paths": "Chemins", + "pie": "Camembert", + "table": "Table" + }, + "ui": { + "and": "et", + "back": "retour", + "collapse": "clic pour réduire", + "error": "erreur", + "expand": "clic pour agrandir", + "loading": "chargement ...", + "more": "plus {0}", + "moreInfo": "clic pour plus d'information", + "noResults": "pas de résultat correspondant à {0}.", + "primary": "connections primaires", + "share": "part", + "total": "total", + "values": "valeurs", + "including": "incluant", + "or": "ou", + "iqr": "gamme interquartile pour {0}", + "max": "maximum", + "min": "le minimum", + "percentile": "{0} percentile", + "tukey_bottom": "tukey bas", + "tukey_top": "top tukey", + "quartile_first": "premier quartile", + "quartile_third": "le troisième quartile", + "median": "médian" + }, + "message": { + "data": "analyse des données", + "draw": "tracé en cours", + "initializing": "Initialisation {0}", + "loading": "chargement", + "tooltipReset": "réinitialisation des bulles", + "ui": "rafraichissement de l'interface" + }, + "uppercase": [ + "CEO", + "CEOs", + "CFO", + "CFOs", + "CNC", + "COO", + "COOs", + "CPU", + "CPUs", + "PIB", + "HVAC", + "ID", + "IT", + "TV", + "UI" + ] +} + +},{}],73:[function(require,module,exports){ +module.exports = { + "format": { + "decimal": ".", + "thousands": ",", + "grouping": [3], + "currency": ["₩", ""], + "dateTime": "%Y/%m/%d %a %X", + "date": "%Y/%m/%d", + "time": "%H:%M:%S", + "periods": ["오전", "오후"], + "days": ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"], + "shortDays": ["일", "월", "화", "수", "목", "금", "토"], + "months": ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"], + "shortMonths": ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"] + }, + "error": { + "accepted": "{0}하지 허용 {1} {2} 시각화는 다음 중 하나를 사용하십시오에 대해 : {3}.", + "connections": "{0}에 대한 연결이 없음.", + "data": "자료 없음", + "dataYear": "{0}에 대한 자료가 없음.", + "lib": "{0} 시각화는 {1} 라이브러리를로드 할 필요합니다.", + "libs": "{0} 시각화는 다음과 같은 라이브러리를로드 할 필요 : {1}.", + "method": "{0} 시각화를 위해 {1} 메서드를 설정해야 한다.", + "methods": "{0} 시각화를 위해 다음과 같은 메서드를 설정해야한다: {1}." + }, + "lowercase": [ + "" + ], + "method": { + "active": "활성 세그먼트", + "color": "색", + "depth": "깊이", + "dev": "풀어서", + "focus": "집중하다", + "icon": "상", + "id": "신분증", + "height": "높이", + "labels": "라벨", + "legend": "범례", + "margin": "여유", + "messages": "상태 메시지", + "order": "주문", + "search": "수색", + "shape": "모양", + "size": "크기", + "style": "스타일", + "temp": "임시 세그먼트", + "text": "본문", + "time": "시각", + "timeline": "타임 라인", + "total": "총 세그먼트", + "type": "유형", + "width": "폭", + "x": "X 축", + "y": "Y 축", + "zoom": "줌", + "mode": "모드", + "mute": "숨김", + "solo": "독주" + }, + "time": [ + "날짜", + "요일", + "월", + "시간", + "년" + ], + "visualization": { + "bubbles": "버블 차트", + "chart": "차트", + "geo_map": "지도형", + "line": "선형 그래프", + "network": "네트워크 그래프", + "rings": "반지", + "scatter": "산포도", + "stacked": "누적 된 지역", + "tree_map": "트리 맵", + "bar": "막대 차트", + "box": "박스 플롯", + "paths": "경로", + "pie": "파이 차트", + "table": "탁자" + }, + "ui": { + "and": "과", + "back": "뒤로", + "collapse": "축소하려면 클릭", + "error": "오류", + "expand": "확장하려면 클릭", + "loading": "로드 중 ...", + "more": "{0} 이상", + "moreInfo": "추가 정보를 위해 클릭하십시오", + "noResults": "일치하는 결과값이 없음 {0}.", + "primary": "기본 연결", + "share": "비중", + "total": "합계", + "values": "값", + "including": "...을 포함하여", + "or": "또는", + "iqr": "대한 사 분위 범위 {0}", + "max": "최고", + "min": "최저한의", + "percentile": "{0} 백분위 수", + "tukey_bottom": "바닥 Tukey에", + "tukey_top": "상단 Tukey에", + "quartile_first": "1 분위", + "quartile_third": "3 분위", + "median": "중앙값" + }, + "message": { + "data": "데이터 분석 중", + "draw": "데이터 시각화 중", + "initializing": "초기화 {0}", + "loading": "데이터 로딩 중", + "tooltipReset": "툴팁을 재설정", + "ui": "UI 업데이트 중" + }, + "uppercase": [ + "CEO", + "최고 경영자", + "최고 재무 책임자 (CFO)", + "CFO는", + "CNC", + "COO", + "구구", + "CPU", + "CPU에", + "GDP", + "HVAC", + "ID", + "IT", + "R & D", + "TV", + "UI" + ] +} + +},{}],74:[function(require,module,exports){ +module.exports = { + "format": { + "decimal": ",", + "thousands": ".", + "grouping": [3], + "currency": ["", " ден."], + "dateTime": "%A, %e %B %Y г. %X", + "date": "%d.%m.%Y", + "time": "%H:%M:%S", + "periods": ["AM", "PM"], + "days": ["недела", "понеделник", "вторник", "среда", "четврток", "петок", "сабота"], + "shortDays": ["нед", "пон", "вто", "сре", "чет", "пет", "саб"], + "months": ["јануари", "февруари", "март", "април", "мај", "јуни", "јули", "август", "септември", "октомври", "ноември", "декември"], + "shortMonths": ["јан", "фев", "мар", "апр", "мај", "јун", "јул", "авг", "сеп", "окт", "ное", "дек"] + }, + "error": { + "accepted": "{0} не е прифатлива за {1} {2} визуелизација, ве молиме користете една од следниве: {3}.", + "connections": "не е достапна за врски {0}.", + "data": "нема податоци", + "dataYear": "Не е достапен за податоци {0}.", + "lib": "{0} визуализации бараат вчитување на библиотеката {1} .", + "libs": "{0} визуализации бараат вчитување на следниве библиотеки: {1}.", + "method": "{0} визуализации бара поставување на {1} методот.", + "methods": "{0} визуализации бараат поставување на следниве методи: {1}." + }, + "lowercase": [ + "a", + "и", + "во", + "но", + "на", + "или", + "да", + "се", + "со" + ], + "method": { + "active": "активни сегменти", + "color": "боја", + "depth": "длабочина", + "dev": "опширно", + "focus": "фокус", + "icon": "икона", + "id": "проект", + "height": "височина", + "labels": "етикети", + "legend": "легенда", + "margin": "маргина", + "messages": "пораки за статусот", + "order": "со цел", + "search": "барај", + "shape": "форма", + "size": "големина", + "style": "стил", + "temp": "привремени сегменти", + "text": "текст", + "time": "време", + "timeline": "времеплов", + "total": "Вкупно сегменти", + "type": "тип", + "width": "ширина", + "x": "x оската", + "y": "Y оската", + "zoom": "зум", + "mode": "режим", + "mute": "се скрие", + "solo": "изолирање" + }, + "time": [ + "датум", + "ден", + "месец", + "време", + "година" + ], + "visualization": { + "bubbles": "меурчиња", + "chart": "Графикон", + "geo_map": "Гео мапа", + "line": "Линиски график", + "network": "мрежа", + "rings": "прстени", + "scatter": "Распрскан график", + "stacked": "Наредена површина", + "tree_map": "Мапа во вид на дрво", + "bar": "бар шема", + "box": "правоаголен дијаграм", + "paths": "патеки", + "pie": "пита графикон", + "table": "Табела" + }, + "ui": { + "and": "и", + "back": "назад", + "collapse": "кликни за да се собере", + "error": "грешка", + "expand": "Кликни за проширување", + "loading": "Се вчитува ...", + "more": "{0} повеќе", + "moreInfo": "кликнете за повеќе информации", + "noResults": "Не се пронајдени резултати за појавување на {0}.", + "primary": "основните врски", + "share": "удел", + "total": "Вкупниот", + "values": "вредности", + "including": "Вклучувајќи", + "or": "или", + "iqr": "interquartile опсег за {0}", + "max": "максималната", + "min": "минимум", + "percentile": "{0} перцентил", + "tukey_bottom": "дното Tukey", + "tukey_top": "Топ Tukey", + "quartile_first": "првиот квартал", + "quartile_third": "третиот квартал", + "median": "средната" + }, + "message": { + "data": "анализа на податоци", + "draw": "цртање на визуелизација", + "initializing": "иницијализација {0}", + "loading": "податоци за товарење", + "tooltipReset": "ресетирање на објаснувањата", + "ui": "ажурирање на кориничкиот интерфејс" + }, + "uppercase": [ + "CEO", + "CEOs", + "CFO", + "CFOs", + "CNC", + "COO", + "COOs", + "CPU", + "CPUs", + "GDP", + "HVAC", + "ID", + "IT", + "R&D", + "TV", + "UI" + ] +} + +},{}],75:[function(require,module,exports){ +module.exports = { + "format": { + "decimal": ",", + "thousands": ".", + "grouping": [3], + "currency": ["R$", ""], + "dateTime": "%A, %e de %B de %Y. %X", + "date": "%d/%m/%Y", + "time": "%H:%M:%S", + "periods": ["AM", "PM"], + "days": ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"], + "shortDays": ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"], + "months": ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"], + "shortMonths": ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"] + }, + "dev": { + "accepted": "{0} não é um valor válido para {1}, por favor use um dos seguintes procedimentos: {2}.", + "deprecated": "{0} método foi removido, por favor atualize seu código para utilizar {1}.", + "noChange": "{0} não foi atualizado porque ele não mudou.", + "noContainer": "Não foi possível encontrar um local na página correspondente a {0}.", + "of": "do", + "oldStyle": "propriedades de estilo para {0} já foram incorporados diretamente no. {1} ().", + "sameEdge": "bordas não podem vincular a si mesmos. removendo automaticamente borda de auto-referência {0}.", + "set": "{0} foi definido.", + "setLong": "{0} foi definido para {1}.", + "setContainer": "por favor, defina um div utilizando .container()" + }, + "error": { + "accepted": "{0} não é um {1} reconhecido para visualizações {2}, favor usar um dos seguintes procedimentos: {3}.", + "connections": "Não há conexões disponíveis para {0}.", + "data": "Não há dados disponíveis", + "dataYear": "Não há dados disponíveis para {0}.", + "lib": "A visualização {0} necessita que seja carregado a biblioteca {1}.", + "libs": "A visualização {0} necessita que seja carregado as bibliotecas {1}.", + "method": "A visualização {0} exige a definição do método {1}.", + "methods": "A visualização {0} exige a definição dos métodos {1}." + }, + "lowercase": [ + "um", + "uma", + "e", + "como", + "em", + "no", + "na", + "mas", + "por", + "para", + "pelo", + "pela", + "de", + "do", + "da", + "se", + "perto", + "nem", + "ou", + "que", + "o", + "a", + "com", + "v" + ], + "method": { + "active": "segmentos activos", + "color": "cor", + "depth": "profundidade", + "dev": "verboso", + "focus": "foco", + "icon": "ícone", + "id": "identificador", + "height": "altura", + "labels": "etiquetas", + "legend": "legenda", + "margin": "margem", + "messages": "mensagens de status", + "order": "ordenar", + "search": "pesquisar", + "shape": "forma", + "size": "tamanho", + "style": "estilo", + "temp": "segmentos temporários", + "text": "texto", + "time": "Tempo", + "timeline": "cronograma", + "total": "segmentos totais", + "type": "digitar", + "width": "largura", + "x": "eixo x", + "y": "eixo y", + "zoom": "zoom", + "mode": "modo", + "mute": "ocultar", + "solo": "isolar" + }, + "time": [ + "data", + "dia", + "mês", + "hora", + "ano" + ], + "visualization": { + "bubbles": "Bolhas", + "chart": "Gráfico", + "geo_map": "Mapa", + "line": "Gráfico de Linha", + "network": "Rede", + "rings": "Anéis", + "scatter": "dispersão", + "stacked": "Evolução", + "tree_map": "Tree Map", + "bar": "Gráfico de Barras", + "box": "box Plot", + "paths": "caminhos", + "pie": "Carta de torta", + "table": "Mesa" + }, + "ui": { + "and": "e", + "back": "voltar", + "collapse": "clique para entrar em colapso", + "error": "erro", + "expand": "clique para expandir", + "loading": "carregando ...", + "more": "mais {0}", + "moreInfo": "Clique para mais informações", + "noResults": "nenhum resultado para {0}.", + "primary": "conexões primárias", + "share": "participação", + "total": "total", + "values": "valores", + "including": "Incluindo", + "or": "ou", + "iqr": "intervalo interquartil para {0}", + "max": "máximo", + "min": "mínimo", + "percentile": "{0} percentil", + "tukey_bottom": "tukey bottom", + "tukey_top": "tukey topo", + "quartile_first": "primeiro quartil", + "quartile_third": "terceiro quartil", + "median": "mediana" + }, + "message": { + "data": "analisando dados", + "draw": "desenhando visualização", + "initializing": "inicializando {0}", + "loading": "carregando dados", + "tooltipReset": "redefinindo as dicas", + "ui": "atualizando interface" + }, + "uppercase": [ + "CEO", + "CEOs", + "CFO", + "CFOs", + "CNC", + "COO", + "COOs", + "CPU", + "CPUs", + "PIB", + "HVAC", + "ID", + "TI", + "P&D", + "TV", + "IU" + ] +} + +},{}],76:[function(require,module,exports){ +module.exports = { + "format": { + "decimal": ",", + "thousands": ".", + "grouping": [3], + "currency": ["€", ""], + "dateTime": "%A, %e de %B de %Y. %X", + "date": "%d/%m/%Y", + "time": "%H:%M:%S", + "periods": ["AM", "PM"], + "days": ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"], + "shortDays": ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"], + "months": ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"], + "shortMonths": ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"] + }, + "error": { + "accepted": "{0} não é uma {1} válida para a visualização {2}, por favor escolha uma das seguintes: {3}.", + "connections": "não existem ligações disponíveis para {0}.", + "data": "não existem dados disponíveis", + "dataYear": "não existem dados disponíveis para {0}.", + "lib": "a visualização {0} necessita que a biblioteca {1} seja carregada.", + "libs": "a visualização {0} necessita que as seguintes bibliotecas sejam carregadas: {1}.", + "method": "A visualização {0} exige a definição do método {1}.", + "methods": "A visualização {0} exige a definição dos seguintes métodos {1}." + }, + "lowercase": [ + "um", + "uma", + "e", + "como", + "em", + "no", + "na", + "mas", + "por", + "para", + "pelo", + "pela", + "de", + "do", + "da", + "se", + "perto", + "nem", + "ou", + "que", + "o", + "a", + "com", + "v" + ], + "method": { + "active": "segmentos activos", + "color": "cor", + "depth": "profundidade", + "dev": "verboso", + "focus": "foco", + "icon": "ícone", + "id": "identificador", + "height": "altura", + "labels": "etiquetas", + "legend": "legenda", + "margin": "margem", + "messages": "estado", + "order": "ordenar", + "search": "pesquisar", + "shape": "forma", + "size": "tamanho", + "style": "estilo", + "temp": "segmentos temporários", + "text": "texto", + "time": "tempo", + "timeline": "linha temporal", + "total": "segmentos totais", + "type": "digitar", + "width": "largura", + "x": "eixo dos xx", + "y": "eixo dos yy", + "zoom": "zoom", + "mode": "modo", + "mute": "ocultar", + "solo": "isolar" + }, + "time": [ + "data", + "dia", + "mês", + "hora", + "ano" + ], + "visualization": { + "bubbles": "Bolhas", + "chart": "Diagrama", + "geo_map": "Mapa", + "line": "Gráfico de Linha", + "network": "Grafo", + "rings": "Anéis", + "scatter": "Gráfico de Dispersão", + "stacked": "Gráfico de Área", + "tree_map": "Tree Map", + "bar": "Gráfico de Barras", + "box": "Diagrama de Caixa e Bigodes", + "paths": "caminhos", + "pie": "Gráfico de Setores", + "table": "Mesa" + }, + "ui": { + "and": "e", + "back": "voltar", + "collapse": "Clique para colapsar", + "error": "erro", + "expand": "clique para expandir", + "loading": "a carregar ...", + "more": "mais {0}", + "moreInfo": "Clique para mais informações", + "noResults": "nenhum resultado para {0}.", + "primary": "ligações principais", + "share": "proporção", + "total": "total", + "values": "valores", + "including": "Incluindo", + "or": "ou", + "iqr": "intervalo interquartil para {0}", + "max": "máximo", + "min": "mínimo", + "percentile": "{0} percentil", + "tukey_bottom": "tukey bottom", + "tukey_top": "tukey topo", + "quartile_first": "primeiro quartil", + "quartile_third": "terceiro quartil", + "median": "mediana" + }, + "message": { + "data": "a analisar os dados", + "draw": "a desenhar a visualização", + "initializing": "a inicializar {0}", + "loading": "a carregar os dados", + "tooltipReset": "a actualizar as caixas de informação", + "ui": "a actualizar o interface" + }, + "uppercase": [ + "CEO", + "CEOs", + "CFO", + "CFOs", + "CNC", + "COO", + "COOs", + "CPU", + "CPUs", + "PIB", + "HVAC", + "ID", + "TI", + "I&D", + "TV", + "IU" + ] +} + +},{}],77:[function(require,module,exports){ +module.exports = { + "format": { + "decimal": ",", + "thousands": "\xa0", + "grouping": [3], + "currency": ["", " руб."], + "dateTime": "%A, %e %B %Y г. %X", + "date": "%d.%m.%Y", + "time": "%H:%M:%S", + "periods": ["AM", "PM"], + "days": ["воскресенье", "понедельник", "вторник", "среда", "четверг", "пятница", "суббота"], + "shortDays": ["вс", "пн", "вт", "ср", "чт", "пт", "сб"], + "months": ["января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"], + "shortMonths": ["янв", "фев", "мар", "апр", "май", "июн", "июл", "авг", "сен", "окт", "ноя", "дек"] + }, + "error": { + "accepted": "{0} не является обслуживаемым {1} для {2} визуализаций, пожалуйста, используйте одно из следующих действий: {3}.", + "connections": "нет соединений, доступных для {0}.", + "data": "данные недоступны", + "dataYear": "нет данных для {0}.", + "lib": "{0} визуализаций требуют загрузки {1} библиотеки.", + "libs": "{0} визуализаций требует загрузки следующие библиотеки: {1}.", + "method": "{0} визуализаций требуют установки {1} метод.", + "methods": "{0} визуализаций требуют установки следующих методов: {1}." + }, + "lowercase": [ + "и", + "как", + "в", + "но", + "для", + "из", + "если в", + "в", + "недалеко", + "ни", + "на", + "на", + "или", + "в", + "что", + "к", + "с", + "с помощью", + "против", + "против" + ], + "method": { + "active": "активные сегменты", + "color": "цвет", + "depth": "глубина", + "dev": "подробный", + "focus": "фокус", + "icon": "значок", + "id": "Я бы", + "height": "высота", + "labels": "надписи", + "legend": "легенда", + "margin": "поле", + "messages": "сообщения о состоянии", + "order": "заказ", + "search": "поиск", + "shape": "форма", + "size": "размер", + "style": "стиль", + "temp": "временные сегменты", + "text": "текст", + "time": "время", + "timeline": "график", + "total": "всего сегментов", + "type": "тип", + "width": "ширина", + "x": "ось х", + "y": "ось Y", + "zoom": "масштаб", + "mode": "Режим", + "mute": "скрывать", + "solo": "изолировать" + }, + "time": [ + "дата", + "день недели", + "месяц", + "время", + "год" + ], + "visualization": { + "bubbles": "Пузыри", + "chart": "Диаграмма", + "geo_map": "Карта Geo", + "line": "линия Участок", + "network": "сеть", + "rings": "Кольца", + "scatter": "Scatter Plot", + "stacked": "Stacked Площадь", + "tree_map": "Дерево Карта", + "bar": "гистограмма", + "box": "Box Участок", + "paths": "пути", + "pie": "Круговая диаграмма", + "table": "Таблица" + }, + "ui": { + "and": "а также", + "back": "назад", + "collapse": "нажмите, чтобы свернуть", + "error": "ошибка", + "expand": "нажмите, чтобы развернуть", + "loading": "загрузка ...", + "more": "{0} более", + "moreInfo": "нажмите для получения дополнительной информации", + "noResults": "нет результатов, соответствующих {0}.", + "primary": "первичные соединения", + "share": "доля", + "total": "Всего", + "values": "значения", + "including": "в том числе", + "or": "или", + "iqr": "межквартильный диапазон для {0}", + "max": "максимальная", + "min": "минимальный", + "percentile": "{0} процентиль", + "tukey_bottom": "нижний Тьюки", + "tukey_top": "сверху Тьюки", + "quartile_first": "первый квартиль", + "quartile_third": "третий квартиль", + "median": "медиана" + }, + "message": { + "data": "данные анализа", + "draw": "рисование визуализация", + "initializing": "инициализацией {0}", + "loading": "Загрузка данных", + "tooltipReset": "сброс всплывающих подсказок", + "ui": "обновление пользовательского интерфейса" + }, + "uppercase": [ + "ID" + ] +} + +},{}],78:[function(require,module,exports){ +module.exports = { + "format": { + "decimal": ".", + "thousands": ",", + "grouping": [3], + "currency": ["¥", ""], + "dateTime": "%A %B %e %Y %X", + "date": "%Y/%-m/%-d", + "time": "%H:%M:%S", + "periods": ["上午", "下午"], + "days": ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"], + "shortDays": ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"], + "months": ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], + "shortMonths": ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"] + }, + "error": { + "accepted": "{0}对于{2}的可视化效果并不是一个可接受的{1}, 请使用如下的一个:{3}.", + "connections": "没有对{0}可用的连接。", + "data": "无可用数据", + "dataYear": "没有数据对{0}可用。", + "lib": "{0}的可视化要求装载{1}库。", + "libs": "{0}的可视化需要加载以下库:{1}。", + "method": "{0}的可视化要求设置{1}方法。", + "methods": "{0}的可视化要求设置以下方法:{1}。" + }, + "lowercase": [ + "一个", + "和", + "在", + "但是", + "在...里", + "的", + "或者", + "这", + "向", + "与...一起" + ], + "method": { + "active": "活跃段", + "color": "颜色", + "depth": "深度", + "dev": "详细", + "focus": "焦点", + "icon": "图标", + "id": "身份认证", + "height": "高度", + "labels": "标签", + "legend": "图例注释", + "margin": "外边距", + "messages": "状态消息", + "order": "规则", + "search": "搜索", + "shape": "形状", + "size": "大小", + "style": "样式", + "temp": "暂时性区段", + "text": "文本", + "time": "时间", + "timeline": "时间轴", + "total": "总段", + "type": "类型", + "width": "宽度", + "x": "X轴", + "y": "Y轴", + "zoom": "缩放", + "mode": "模式", + "mute": "隐藏", + "solo": "隔离" + }, + "time": [ + "日", + "星期", + "月", + "时间", + "年" + ], + "visualization": { + "bubbles": "气泡", + "chart": "图表", + "geo_map": "地理地图", + "line": "线图", + "network": "网络", + "rings": "特性", + "scatter": "散点图", + "stacked": "堆积面积图", + "tree_map": "树图", + "bar": "条图", + "box": "箱形图", + "paths": "路径", + "pie": "饼形图", + "table": "表" + }, + "ui": { + "and": "和", + "back": "后面", + "collapse": "点击合并", + "error": "错误", + "expand": "单击以展开", + "loading": "载入中...", + "more": "{0}更多", + "moreInfo": "点击了解更多信息", + "noResults": "没有结果匹配{0}。", + "primary": "主要连接", + "share": "共享", + "total": "总", + "values": "值", + "including": "包括", + "or": "要么", + "iqr": "间距范围为{0}", + "max": "最大值", + "min": "最低限度", + "percentile": "{0}百分", + "tukey_bottom": "底部杜克", + "tukey_top": "顶部杜克", + "quartile_first": "第一个四分位数", + "quartile_third": "第三个四分位数", + "median": "中位数" + }, + "message": { + "data": "分析数据", + "draw": "绘制可视化", + "initializing": "初始化{0}", + "loading": "加载数据", + "tooltipReset": "重置工具提示", + "ui": "更新UI" + }, + "uppercase": [ + "CEO", + "CEOs", + "CFO", + "CFOs", + "CNC", + "COO", + "COOs", + "CPU", + "CPUs", + "GDP", + "HVAC", + "ID", + "电视", + "用户界面", + "研发" + ] +} + +},{}],79:[function(require,module,exports){ +module.exports = { + de_DE: require("./languages/de_DE.js"), + en_US: require("./languages/en_US.coffee"), + es_ES: require("./languages/es_ES.js"), + fr_FR: require("./languages/fr_FR.js"), + ko_KR: require("./languages/ko_KR.js"), + mk_MK: require("./languages/mk_MK.js"), + pt_BR: require("./languages/pt_BR.js"), + pt_PT: require("./languages/pt_PT.js"), + ru_RU: require("./languages/ru_RU.js"), + zh_CN: require("./languages/zh_CN.js") +}; + + +},{"./languages/de_DE.js":69,"./languages/en_US.coffee":70,"./languages/es_ES.js":71,"./languages/fr_FR.js":72,"./languages/ko_KR.js":73,"./languages/mk_MK.js":74,"./languages/pt_BR.js":75,"./languages/pt_PT.js":76,"./languages/ru_RU.js":77,"./languages/zh_CN.js":78}],80:[function(require,module,exports){ +var checkObject, copy, createFunction, initialize, print, process, setMethod, stringFormat, validObject; + +copy = require("../../util/copy.coffee"); + +print = require("../console/print.coffee"); + +process = require("./process/detect.coffee"); + +setMethod = require("./set.coffee"); + +stringFormat = require("../../string/format.js"); + +validObject = require("../../object/validate.coffee"); + +module.exports = function(vars, methods) { + var method, obj, results; + results = []; + for (method in methods) { + obj = methods[method]; + vars[method] = copy(obj); + vars[method].initialized = initialize(vars, vars[method], method); + results.push(vars.self[method] = createFunction(vars, method)); + } + return results; +}; + +initialize = function(vars, obj, method, p) { + var d, deps, i, len, o; + obj.previous = false; + obj.changed = false; + obj.initialized = false; + obj.callback = false; + if ("init" in obj && (!("value" in obj))) { + obj.value = obj.init(vars); + delete obj.init; + } + if ("process" in obj) { + obj.value = process(vars, obj, obj.value); + } + for (o in obj) { + if (o === "deprecates") { + deps = obj[o] instanceof Array ? obj[o] : [obj[o]]; + for (i = 0, len = deps.length; i < len; i++) { + d = deps[i]; + vars.self[d] = (function(dep, n) { + return function(x) { + var doc, rec, str; + str = vars.format.locale.value.dev.deprecated; + dep = "." + dep + "()"; + rec = p ? "\"" + n + "\" in ." + p + "()" : "." + n + "()"; + doc = p || n; + print.error(stringFormat(str, dep, rec), doc); + return vars.self; + }; + })(d, method); + } + } else if (o === "global") { + if (!(method in vars)) { + vars[method] = []; + } + } else if (o !== "value") { + if (validObject(obj[o])) { + initialize(vars, obj[o], o, method); + } + } + } + return true; +}; + +createFunction = function(vars, key) { + return function(user, callback) { + var accepted, checkFont, checkValue, fontAttr, fontAttrValue, s, starting, str; + accepted = "accepted" in vars[key] ? vars[key].accepted : null; + if (typeof accepted === "function") { + accepted = accepted(vars); + } + if (!(accepted instanceof Array)) { + accepted = [accepted]; + } + if (user === Object) { + return vars[key]; + } else if (!arguments.length && accepted.indexOf(void 0) < 0) { + if ("value" in vars[key]) { + return vars[key].value; + } else { + return vars[key]; + } + } + if (key === "style" && typeof user === "object") { + str = vars.format.locale.value.dev.oldStyle; + for (s in user) { + print.warning(stringFormat(str, "\"" + s + "\"", s), s); + vars.self[s](user[s]); + } + } + if (key === "font") { + if (typeof user === "string") { + user = { + family: user + }; + } + starting = true; + checkValue = function(o, a, m, v) { + if (validObject(o[m]) && a in o[m]) { + if (validObject(o[m][a])) { + if (o[m][a].process) { + o[m][a].value = o[m][a].process(v); + } else { + o[m][a].value = v; + } + } else { + o[m][a] = v; + } + } + }; + checkFont = function(o, a, v) { + var m; + if (validObject(o)) { + if (starting) { + for (m in o) { + checkValue(o, a, m, v); + } + } else if ("font" in o) { + checkValue(o, a, "font", v); + } + starting = false; + for (m in o) { + checkFont(o[m], a, v); + } + } + }; + for (fontAttr in user) { + fontAttrValue = user[fontAttr]; + if (fontAttr !== "secondary") { + if (validObject(fontAttrValue)) { + fontAttrValue = fontAttrValue.value; + } + if (fontAttrValue) { + checkFont(vars, fontAttr, fontAttrValue); + } + } + } + } + checkObject(vars, key, vars, key, user); + if (typeof callback === "function") { + vars[key].callback = callback; + } + if (vars[key].chainable === false) { + return vars[key].value; + } else { + return vars.self; + } + }; +}; + +checkObject = function(vars, method, object, key, value) { + var approvedObject, d, objectOnly, passingObject; + if (["accepted", "changed", "initialized", "previous", "process"].indexOf(key) < 0) { + passingObject = validObject(value); + objectOnly = validObject(object[key]) && "objectAccess" in object[key] && object[key]["objectAccess"] === false; + approvedObject = passingObject && (objectOnly || ((!("value" in value)) && ((!validObject(object[key])) || (!(d3.keys(value)[0] in object[key]))))); + if (value === null || !passingObject || approvedObject) { + setMethod(vars, method, object, key, value); + } else if (passingObject) { + for (d in value) { + checkObject(vars, method, object[key], d, value[d]); + } + } + } +}; + + +},{"../../object/validate.coffee":172,"../../string/format.js":173,"../../util/copy.coffee":207,"../console/print.coffee":52,"./process/detect.coffee":88,"./set.coffee":94}],81:[function(require,module,exports){ +module.exports = function(g) { + if (!g) { + g = false; + } + return { + accepted: [false, Array, Function, Number, Object, String], + callback: { + accepted: [false, Function], + value: false + }, + global: g, + process: Array, + value: [] + }; +}; + + +},{}],82:[function(require,module,exports){ +var rtl; + +rtl = require("../../../client/rtl.coffee"); + +module.exports = function(align) { + var accepted; + accepted = ["left", "center", "right"]; + if (align === false) { + accepted.unshift(false); + } + if (accepted.indexOf(align) < 0) { + align = "left"; + } + return { + accepted: accepted, + process: function(value) { + if (rtl) { + if (value === "left") { + return "right"; + } else { + if (value === "right") { + return "left"; + } else { + return value; + } + } + } else { + return value; + } + }, + value: align + }; +}; + + +},{"../../../client/rtl.coffee":40}],83:[function(require,module,exports){ +module.exports = function(decoration) { + var accepted; + accepted = ["line-through", "none", "overline", "underline"]; + if (decoration === false) { + accepted.unshift(false); + } + if (accepted.indexOf(decoration) < 0) { + decoration = "none"; + } + return { + accepted: accepted, + value: decoration + }; +}; + + +},{}],84:[function(require,module,exports){ +var helvetica, validate; + +validate = require("../../../font/validate.coffee"); + +helvetica = ["Helvetica Neue", "HelveticaNeue", "Helvetica", "Arial", "sans-serif"]; + +module.exports = function(family) { + if (family === void 0) { + family = helvetica; + } + return { + process: validate, + value: family + }; +}; + + +},{"../../../font/validate.coffee":103}],85:[function(require,module,exports){ +module.exports = function(position) { + var accepted; + accepted = ["top", "middle", "bottom"]; + if (position === false) { + accepted.unshift(false); + } + if (accepted.indexOf(position) < 0) { + position = "bottom"; + } + return { + accepted: accepted, + mapping: { + top: "0ex", + middle: "0.5ex", + bottom: "1ex" + }, + process: function(value) { + this.text = value; + return this.mapping[value]; + }, + value: position + }; +}; + + +},{}],86:[function(require,module,exports){ +module.exports = function(transform) { + var accepted; + accepted = ["capitalize", "lowercase", "none", "uppercase"]; + if (transform === false) { + accepted.unshift(false); + } + if (accepted.indexOf(transform) < 0) { + transform = "none"; + } + return { + accepted: accepted, + value: transform + }; +}; + + +},{}],87:[function(require,module,exports){ +module.exports = function(value, vars, method) { + var elem; + if (vars.history) { + vars.history.reset(); + } + if (value.constructor === String) { + if (value.indexOf("/") >= 0) { + method.url = value; + return []; + } + elem = d3.selectAll(value); + if (elem.size()) { + return elem; + } + if (value.indexOf(".") >= 0) { + method.url = value; + } + return []; + } else { + return value; + } +}; + + +},{}],88:[function(require,module,exports){ +var copy, update; + +copy = require("../../../util/copy.coffee"); + +update = require("../../../array/update.coffee"); + +module.exports = function(vars, object, value) { + if (object.process === Array) { + return update(copy(object.value), value); + } else if (typeof object.process === "object" && typeof value === "string") { + return object.process[value]; + } else if (typeof object.process === "function") { + return object.process(value, vars, object); + } else { + return value; + } +}; + + +},{"../../../array/update.coffee":35,"../../../util/copy.coffee":207}],89:[function(require,module,exports){ +var stylesheet; + +stylesheet = require("../../../client/css.coffee"); + +module.exports = function(value, vars, method) { + if (value === false || value.indexOf("fa-") < 0 || (value.indexOf("fa-") === 0 && stylesheet("font-awesome"))) { + return value; + } else { + return method.fallback; + } +}; + + +},{"../../../client/css.coffee":36}],90:[function(require,module,exports){ +module.exports = function(value, self) { + var i, j, k, l, len, len1, len2, len3, m, results, side, sides, v; + if (typeof value === "string") { + value = value.split(" "); + for (i = j = 0, len = value.length; j < len; i = ++j) { + v = value[i]; + value[i] = parseFloat(v, 10); + } + if (value.length === 1) { + value = value[0]; + } else if (value.length === 2) { + value = { + top: value[0], + right: value[1], + bottom: value[0], + left: value[1] + }; + } else if (value.length === 3) { + value = { + top: value[0], + right: value[1], + bottom: value[2], + left: value[1] + }; + } else if (value.length === 4) { + value = { + top: value[0], + right: value[1], + bottom: value[2], + left: value[3] + }; + } else { + value = 0; + } + } + sides = ["top", "right", "bottom", "left"]; + if (typeof value === "number") { + for (k = 0, len1 = sides.length; k < len1; k++) { + side = sides[k]; + self[side] = value; + } + } else { + for (l = 0, len2 = sides.length; l < len2; l++) { + side = sides[l]; + self[side] = value[side]; + } + } + self.css = ""; + results = []; + for (i = m = 0, len3 = sides.length; m < len3; i = ++m) { + side = sides[i]; + if (i) { + self.css += " "; + } + results.push(self.css += self[side] + "px"); + } + return results; +}; + + +},{}],91:[function(require,module,exports){ +var contains, format, list, print; + +contains = require("../../array/contains.coffee"); + +format = require("../../string/format.js"); + +list = require("../../string/list.coffee"); + +print = require("../console/print.coffee"); + +module.exports = function(vars, accepted, value, method, text) { + var a, allowed, app, i, len, recs, str, val; + if (typeof accepted === "function") { + accepted = accepted(vars); + } + if (!(accepted instanceof Array)) { + accepted = [accepted]; + } + allowed = contains(accepted, value); + if (allowed === false && value !== void 0) { + recs = []; + val = JSON.stringify(value); + if (typeof value !== "string") { + val = "\"" + val + "\""; + } + for (i = 0, len = accepted.length; i < len; i++) { + a = accepted[i]; + if (typeof a === "string") { + recs.push("\"" + a + "\""); + } else if (typeof a === "function") { + recs.push(a.toString().split("()")[0].substring(9)); + } else if (a === void 0) { + recs.push("undefined"); + } else { + recs.push(JSON.stringify(a)); + } + } + recs = list(recs, vars.format.locale.value.ui.or); + if (vars.type && ["mode", "shape"].indexOf(method) >= 0) { + str = vars.format.locale.value.error.accepted; + app = vars.format.locale.value.visualization[vars.type.value] || vars.type.value; + print.warning(format(str, val, method, app, recs), method); + } else { + str = vars.format.locale.value.dev.accepted; + print.warning(format(str, val, text, recs), method); + } + } + return !allowed; +}; + + +},{"../../array/contains.coffee":33,"../../string/format.js":173,"../../string/list.coffee":174,"../console/print.coffee":52}],92:[function(require,module,exports){ +module.exports = function(rendering) { + var accepted; + accepted = ["auto", "optimizeSpeed", "crispEdges", "geometricPrecision"]; + if (!(accepted.indexOf(rendering) >= 0)) { + rendering = "crispEdges"; + } + return { + accepted: accepted, + value: rendering + }; +}; + + +},{}],93:[function(require,module,exports){ +var reset, validObject; + +validObject = require("../../object/validate.coffee"); + +reset = function(obj, method) { + var o; + if (obj.changed) { + obj.changed = false; + } + if (method === "draw") { + obj.frozen = false; + obj.update = true; + obj.first = false; + } + for (o in obj) { + if (o.indexOf("d3plus") < 0 && validObject(obj[o])) { + reset(obj[o], o); + } + } +}; + +module.exports = reset; + + +},{"../../object/validate.coffee":172}],94:[function(require,module,exports){ +var copy, d3selection, mergeObject, print, process, rejected, stringFormat, updateArray, validObject; + +copy = require("../../util/copy.coffee"); + +d3selection = require("../../util/d3selection.coffee"); + +validObject = require("../../object/validate.coffee"); + +mergeObject = require("../../object/merge.coffee"); + +print = require("../console/print.coffee"); + +process = require("./process/detect.coffee"); + +rejected = require("./rejected.coffee"); + +stringFormat = require("../../string/format.js"); + +updateArray = require("../../array/update.coffee"); + +module.exports = function(vars, method, object, key, value) { + var accepted, c, callback, d3object, hasValue, id, k, longArray, n, parentKey, str, text, typeFunction, valString; + if (key === "value" || !key || key === method) { + text = "." + method + "()"; + } else { + text = "\"" + key + "\" " + vars.format.locale.value.dev.of + " ." + method + "()"; + } + if (key === "value" && "accepted" in object) { + accepted = object.accepted; + } else if (validObject(object[key]) && "accepted" in object[key]) { + accepted = object[key].accepted; + } else { + accepted = [value]; + } + if (!rejected(vars, accepted, value, method, text)) { + if (validObject(object[key]) && "value" in object[key]) { + parentKey = key; + object = object[key]; + key = "value"; + } + if (key === "value" && "process" in object) { + value = process(vars, object, value); + } + if ((!(object[key] instanceof Array)) && object[key] === value && value !== void 0) { + str = vars.format.locale.value.dev.noChange; + if (vars.dev.value) { + print.comment(stringFormat(str, text)); + } + } else { + object.changed = true; + if (object.loaded) { + object.loaded = false; + } + if ("history" in vars && method !== "draw") { + c = copy(object); + c.method = method; + vars.history.chain.push(c); + } + object.previous = object[key]; + if ("id" in vars && key === "value" && "nesting" in object) { + if (method !== "id") { + if (typeof object.nesting !== "object") { + object.nesting = {}; + } + if (validObject(value)) { + for (id in value) { + if (typeof value[id] === "string") { + value[id] = [value[id]]; + } + } + object.nesting = mergeObject(object.nesting, value); + if (!(vars.id.value in object.nesting)) { + object.nesting[vars.id.value] = value[d3.keys(value)[0]]; + } + } else if (value instanceof Array) { + object.nesting[vars.id.value] = value; + } else { + object.nesting[vars.id.value] = [value]; + } + object[key] = object.nesting[vars.id.value][0]; + } else { + if (value instanceof Array) { + object.nesting = value; + if ("depth" in vars && vars.depth.value < value.length) { + object[key] = value[vars.depth.value]; + } else { + object[key] = value[0]; + if ("depth" in vars) { + vars.depth.value = 0; + } + } + } else { + object[key] = value; + object.nesting = [value]; + if ("depth" in vars) { + vars.depth.value = 0; + } + } + } + } else if (method === "depth") { + if (value >= vars.id.nesting.length) { + vars.depth.value = vars.id.nesting.length - 1; + } else if (value < 0) { + vars.depth.value = 0; + } else { + vars.depth.value = value; + } + vars.id.value = vars.id.nesting[vars.depth.value]; + if (typeof vars.text.nesting === "object") { + n = vars.text.nesting[vars.id.value]; + if (n) { + vars.text.nesting[vars.id.value] = typeof n === "string" ? [n] : n; + vars.text.value = (n instanceof Array ? n[0] : n); + } + } + } else if (validObject(object[key]) && validObject(value)) { + object[key] = mergeObject(object[key], value); + } else { + object[key] = value; + } + if (key === "value" && object.global) { + hasValue = object[key].length > 0; + k = parentKey || key; + if (k in vars && ((hasValue && vars.data[k].indexOf(method) < 0) || (!hasValue && vars.data[k].indexOf(method) >= 0))) { + vars.data[k] = updateArray(vars.data[k], method); + } + } + if (key === "value" && object.dataFilter && vars.data && vars.data.filters.indexOf(method) < 0) { + vars.data.filters.push(method); + } + if (vars.dev.value && object.changed && object[key] !== void 0) { + longArray = object[key] instanceof Array && object[key].length > 10; + d3object = d3selection(object[key]); + typeFunction = typeof object[key] === "function"; + valString = (!longArray && !d3object && !typeFunction ? (typeof object[key] === "string" ? object[key] : JSON.stringify(object[key])) : null); + if (valString !== null && valString.length < 260) { + str = vars.format.locale.value.dev.setLong; + print.log(stringFormat(str, text, "\"" + valString + "\"")); + } else { + str = vars.format.locale.value.dev.set; + print.log(stringFormat(str, text)); + } + } + } + if (key === "value" && object.callback && !object.url) { + callback = typeof object.callback === "function" ? object.callback : object.callback.value; + if (callback) { + callback(value, vars.self); + } + } + } +}; + + +},{"../../array/update.coffee":35,"../../object/merge.coffee":171,"../../object/validate.coffee":172,"../../string/format.js":173,"../../util/copy.coffee":207,"../../util/d3selection.coffee":208,"../console/print.coffee":52,"./process/detect.coffee":88,"./rejected.coffee":91}],95:[function(require,module,exports){ +var print = require("../console/print.coffee"), + stringFormat = require("../../string/format.js") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Cleans edges list and populates nodes list if needed +//------------------------------------------------------------------- +module.exports = function( vars ) { + + if ( vars.dev.value ) { + var timerString = "analyzing edges list" + print.time( timerString ) + } + + var appReqs = vars.types[vars.type.value].requirements + if (!(appReqs instanceof Array)) appReqs = [appReqs] + var createNodes = appReqs.indexOf("nodes") >= 0 && !vars.nodes.value + + if ( createNodes ) { + vars.nodes.value = [] + var placed = [] + vars.nodes.changed = true + } + + vars.edges.value.forEach(function(e){ + + ["source", "target"].forEach(function(dir){ + + var dirType = typeof e[vars.edges[dir]]; + + if (dirType !== "object") { + if (dirType === "number" && !createNodes && vars.data.keys[vars.id.value] !== "number") { + e[vars.edges[dir]] = vars.nodes.value[e[vars.edges[dir]]]; + } + else { + if (createNodes && placed.indexOf(e[vars.edges[dir]]) >= 0) { + e[vars.edges[dir]] = vars.nodes.value.filter(function(n){ + return n[vars.id.value] === e[vars.edges[dir]]; + })[0]; + } + else { + var obj = {}; + obj[vars.id.value] = e[vars.edges[dir]]; + e[vars.edges[dir]] = obj; + } + } + } + + var newNode = e[vars.edges[dir]]; + if (createNodes) { + if (placed.indexOf(newNode[vars.id.value]) < 0) { + placed.push(newNode[vars.id.value]); + vars.nodes.value.push(newNode); + } + } + }); + + if (!("keys" in vars.data)) { + vars.data.keys = {}; + } + + if (!(vars.id.value in vars.data.keys)) { + vars.data.keys[vars.id.value] = typeof e[vars.edges.source][vars.id.value]; + } + + }); + + vars.edges.value = vars.edges.value.filter(function(e){ + + var source = e[vars.edges.source][vars.id.value] + , target = e[vars.edges.target][vars.id.value] + + if ( source === target ) { + var str = vars.format.locale.value.dev.sameEdge + print.warning(stringFormat(str,"\""+source+"\"") , "edges" ) + return false + } + else { + return true + } + + }) + + vars.edges.linked = true + + if ( vars.dev.value ) print.timeEnd( timerString ) + +} + +},{"../../string/format.js":173,"../console/print.coffee":52}],96:[function(require,module,exports){ +var hideElement = require("./hideElement.js"); + +// Parses an HTML element for data +module.exports = function( vars ) { + + var attributes = [ vars.color.value + , vars.icon.value + , vars.keywords.value + , vars.alt.value + , "style" ] + + if (!vars.text.value) { + vars.self.text("text") + } + + attributes = attributes.concat(vars.id.nesting) + + function get_attributes( obj , elem ) { + [].forEach.call(elem.attributes, function(attr) { + if (/^data-/.test(attr.name)) { + var camelCaseName = attr.name.substr(5).replace(/-(.)/g, function ($0, $1) { + return $1.toUpperCase(); + }); + obj[camelCaseName] = attr.value; + } + }) + + attributes.forEach(function(a){ + + if ( elem.getAttribute(a) !== null ) { + obj[a] = elem.getAttribute(a) + } + + }) + + } + + vars.self.data({"element": vars.data.value}) + + var elementTag = vars.data.element.value.node().tagName.toLowerCase() + , elementType = vars.data.element.value.attr("type") + , elementData = [] + + if ( elementTag === "select" ) { + + var elementID = vars.data.element.value.node().id + if ( elementID ) { + vars.self.container({"id": elementID}) + } + + vars.data.element.value.selectAll("option") + .each(function( o , i ){ + + var data_obj = {} + + data_obj.text = d3.select(this).text(); + + get_attributes(data_obj,this) + + elementData.push(data_obj) + + if (this.selected) { + for (var i = vars.id.nesting.length-1; i >= 0; i--) { + var level = vars.id.nesting[i] + if (level in data_obj) { + vars.self.focus(data_obj[level]) + break + } + } + } + + }) + + } + else if ( elementTag === "input" && elementType === "radio" ) { + + var elementName = vars.data.element.value.node().getAttribute("name") + if ( elementName ) { + vars.self.container({"id": elementName}) + } + + vars.data.element.value + .each(function( o , i ){ + + var data_obj = {} + + get_attributes(data_obj,this) + + var id = data_obj[vars.id.value] || this.id || false + + if ( id && isNaN(parseFloat(id)) ) { + + var label = d3.select("label[for="+id+"]") + + if ( !label.empty() ) { + data_obj.text = label.html() + label.call(hideElement) + } + + } + + elementData.push(data_obj) + + if (this.checked) { + vars.self.focus(data_obj[vars.id.value]) + } + + }) + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Get focus from data, if it hasn't been found or set. + //---------------------------------------------------------------------------- + if ( !vars.focus.value.length && elementData.length ) { + + vars.data.element.value.node().selectedIndex = 0 + vars.self.focus(elementData[0][vars.id.value]) + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If a element exists, use it as the title. + //---------------------------------------------------------------------------- + var elementLegend = d3.select("legend[for="+vars.container.id+"]") + if ( !elementLegend.empty() ) { + + vars.self.title(elementLegend.html()) + elementLegend.call(hideElement) + + } + + var containerTag = vars.container.value + ? vars.container.value.node().tagName.toLowerCase() : false + + if ( vars.container.value === false || containerTag === "body" ) { + vars.container.value = d3.select(vars.data.element.value.node().parentNode) + } + + vars.data.element.value.call(hideElement) + + return elementData + +}; + +},{"./hideElement.js":97}],97:[function(require,module,exports){ +module.exports = function(elem) { + + elem + .style("position","absolute","important") + .style("clip","rect(1px 1px 1px 1px)","important") + .style("clip","rect(1px, 1px, 1px, 1px)","important") + .style("width","1px","important") + .style("height","1px","important") + .style("margin","-1px","important") + .style("padding","0","important") + .style("border","0","important") + .style("overflow","hidden","important"); + +} + +},{}],98:[function(require,module,exports){ +var print = require("../console/print.coffee"); + +// Calculates node positions, if needed for network. +module.exports = function(vars) { + + if (vars.type.value === "network") { + + if (vars.dev.value) { + var timerString = "analyzing node positions"; + print.time(timerString); + } + + var set = vars.nodes.value.filter(function(n){ + return typeof n.x === "number" && typeof n.y === "number"; + }).length; + + if (set === vars.nodes.value.length) { + vars.nodes.positions = true; + } + else { + + var force = d3.layout.force() + .size([vars.width.viz, vars.height.viz]) + .nodes(vars.nodes.value) + .links(vars.edges.value); + + var strength = vars.edges.strength.value; + if (strength) { + if (typeof strength === "string") { + force.linkStrength(function(e){ + return e[strength]; + }); + } + else { + force.linkStrength(strength); + } + } + + var iterations = 50, + threshold = 0.01; + + force.start(); // Defaults to alpha = 0.1 + for (var i = iterations; i > 0; --i) { + force.tick(); + if(force.alpha() < threshold) { + break; + } + } + force.stop(); + + vars.nodes.positions = true; + + } + + if (vars.dev.value) print.timeEnd(timerString); + + } + +} + +},{"../console/print.coffee":52}],99:[function(require,module,exports){ +var numeric; + +numeric = require('numeric'); + +module.exports = function(data, options) { + var N, X, Xfulltr, Xtr, bestResult, beta_hat, bic, degree, degrees, i, j, k, l, loglike, m, point, prevBIC, q, ref, ref1, residual, sigma2, sse, y, y_hat; + if (options == null) { + options = {}; + } + if (options.maxDegree == null) { + options.maxDegree = 5; + } + N = data.length; + prevBIC = Number.MAX_VALUE; + bestResult = null; + Xfulltr = (function() { + var l, ref, results; + results = []; + for (degree = l = 1, ref = options.maxDegree + 1; 1 <= ref ? l < ref : l > ref; degree = 1 <= ref ? ++l : --l) { + results.push((function() { + var len, m, results1; + results1 = []; + for (m = 0, len = data.length; m < len; m++) { + point = data[m]; + results1.push(Math.pow(point[0], degree)); + } + return results1; + })()); + } + return results; + })(); + y = (function() { + var l, len, results; + results = []; + for (l = 0, len = data.length; l < len; l++) { + point = data[l]; + results.push(point[1]); + } + return results; + })(); + for (i = l = 0, ref = 1 << options.maxDegree; 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) { + Xtr = [ + (function() { + var m, ref1, results; + results = []; + for (q = m = 0, ref1 = N; 0 <= ref1 ? m < ref1 : m > ref1; q = 0 <= ref1 ? ++m : --m) { + results.push(1); + } + return results; + })() + ]; + degrees = [0]; + for (j = m = 0, ref1 = options.maxDegree; 0 <= ref1 ? m < ref1 : m > ref1; j = 0 <= ref1 ? ++m : --m) { + if ((i & 1 << j) > 0) { + Xtr.push(Xfulltr[j]); + degrees.push(j + 1); + } + } + X = numeric.transpose(Xtr); + k = degrees.length; + beta_hat = numeric.dot(numeric.dot(numeric.inv(numeric.dot(Xtr, X)), Xtr), y); + y_hat = numeric.dot(X, beta_hat); + residual = numeric.sub(y, y_hat); + sse = numeric.dot(residual, residual); + sigma2 = sse / (N - k); + loglike = -0.5 * N * Math.log(2 * Math.PI) - 0.5 * N * Math.log(sigma2) - sse / (2 * sigma2); + bic = -2 * loglike + k * (Math.log(N) - Math.log(2 * Math.PI)); + if (bic < prevBIC) { + prevBIC = bic; + bestResult = [degrees, beta_hat, y_hat]; + } + } + return bestResult; +}; + + +},{"numeric":7}],100:[function(require,module,exports){ +var kdtree; + +kdtree = require('static-kdtree'); + +module.exports = function(points, K) { + var avg_lrd, i, j, kdists, ldr, ldrs, neighbors, p, reachDist, result, sqDist, tree; + if (K == null) { + K = 10; + } + tree = kdtree(points); + neighbors = (function() { + var k, len, results; + results = []; + for (k = 0, len = points.length; k < len; k++) { + p = points[k]; + results.push(tree.knn(p, K + 1).slice(1)); + } + return results; + })(); + sqDist = function(i, j) { + var A, B, delta, dist, k, ref; + A = points[i]; + B = points[j]; + dist = 0; + for (i = k = 0, ref = A.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) { + delta = A[i] - B[i]; + dist += delta * delta; + } + return dist; + }; + kdists = (function() { + var k, ref, results; + results = []; + for (i = k = 0, ref = points.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) { + results.push(sqDist(i, neighbors[i][K - 1])); + } + return results; + })(); + reachDist = function(i, j) { + return Math.max(sqDist(i, j), kdists[j]); + }; + ldr = function(i) { + var j, k, len, rDist, ref; + rDist = 0; + ref = neighbors[i]; + for (k = 0, len = ref.length; k < len; k++) { + j = ref[k]; + rDist += reachDist(i, j); + } + return K / rDist; + }; + ldrs = (function() { + var k, ref, results; + results = []; + for (i = k = 0, ref = points.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) { + results.push(ldr(i)); + } + return results; + })(); + result = (function() { + var k, l, len, ref, ref1, results; + results = []; + for (i = k = 0, ref = points.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) { + avg_lrd = 0; + ref1 = neighbors[i]; + for (l = 0, len = ref1.length; l < len; l++) { + j = ref1[l]; + avg_lrd += ldrs[j]; + } + avg_lrd /= K; + results.push([i, avg_lrd / ldrs[i]]); + } + return results; + })(); + return result.sort(function(a, b) { + return b[1] - a[1]; + }); +}; + + +},{"static-kdtree":9}],101:[function(require,module,exports){ +module.exports = function(points) { + var mad, median, result; + median = d3.median(points); + mad = d3.median(points.map(function(p) { + return Math.abs(p - median); + })); + result = points.map(function(p, i) { + return [i, Math.abs(p - median) / mad]; + }); + return result.sort(function(a, b) { + return b[1] - a[1]; + }); +}; + + +},{}],102:[function(require,module,exports){ +var fontTester; + +fontTester = require("../core/font/tester.coffee"); + +module.exports = function(words, style, opts) { + var attr, getHeight, getWidth, sizes, spacing, tester, tspans; + if (!opts) { + opts = {}; + } + style = style || {}; + tester = opts.parent || fontTester("svg").append("text"); + sizes = []; + if (!(words instanceof Array)) { + words = [words]; + } + tspans = tester.selectAll("tspan").data(words); + attr = { + left: "0px", + position: "absolute", + top: "0px", + x: 0, + y: 0 + }; + spacing = 0; + if ("letter-spacing" in style) { + spacing = parseFloat(style["letter-spacing"]); + delete style["letter-spacing"]; + } + getWidth = function(elem) { + var add; + add = 0; + if (spacing) { + add = (d3.select(elem).text().length - 1) * spacing; + } + return elem.getComputedTextLength() + add; + }; + getHeight = function(elem) { + return elem.parentNode.getBBox().height || elem.getBoundingClientRect().height; + }; + tspans.enter().append("tspan").text(String).style(style).attr(attr).each(function(d) { + if (typeof opts.mod === "function") { + return opts.mod(this); + } + }).each(function(d) { + var children, height, width; + children = d3.select(this).selectAll("tspan"); + if (children.size()) { + width = []; + children.each(function() { + return width.push(getWidth(this)); + }); + width = d3.max(width); + } else { + width = getWidth(this); + } + height = getHeight(this); + return sizes.push({ + height: height, + text: d, + width: width + }); + }); + tspans.remove(); + if (!opts.parent) { + tester.remove(); + } + return sizes; +}; + + +},{"../core/font/tester.coffee":68}],103:[function(require,module,exports){ +var fontTester, validate; + +fontTester = require("../core/font/tester.coffee"); + +validate = function(fontList) { + var completed, family, font, fontString, i, j, len, len1, monospace, proportional, testElement, testWidth, tester, valid; + if (!(fontList instanceof Array)) { + fontList = fontList.split(","); + } + for (i = 0, len = fontList.length; i < len; i++) { + font = fontList[i]; + font.trim(); + } + fontString = fontList.join(", "); + completed = validate.complete; + if (fontString in completed) { + return completed[fontString]; + } + testElement = function(font) { + return tester.append("span").style("font-family", font).style("font-size", "32px").style("padding", "0px").style("margin", "0px").text("abcdefghiABCDEFGHI_!@#$%^&*()_+1234567890"); + }; + testWidth = function(font, control) { + var elem, width1, width2; + elem = testElement(font); + width1 = elem.node().offsetWidth; + width2 = control.node().offsetWidth; + elem.remove(); + return width1 !== width2; + }; + tester = fontTester("div"); + monospace = testElement("monospace"); + proportional = testElement("sans-serif"); + for (j = 0, len1 = fontList.length; j < len1; j++) { + family = fontList[j]; + valid = testWidth(family + ",monospace", monospace); + if (!valid) { + valid = testWidth(family + ",sans-serif", proportional); + } + if (valid) { + valid = family; + break; + } + } + if (!valid) { + valid = "sans-serif"; + } + monospace.remove(); + proportional.remove(); + completed[fontString] = valid; + return valid; +}; + +validate.complete = {}; + +module.exports = validate; + + +},{"../core/font/tester.coffee":68}],104:[function(require,module,exports){ +var arraySort = require("../array/sort.coffee"), + attach = require("../core/methods/attach.coffee"), + dataFormat = require("../core/data/format.js"), + dataKeys = require("../core/data/keys.coffee"), + dataLoad = require("../core/data/load.coffee"), + fetchData = require("../core/fetch/data.js"), + ie = require("../client/ie.js"), + methodReset = require("../core/methods/reset.coffee"), + print = require("../core/console/print.coffee"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Form Element shell +//------------------------------------------------------------------------------ +module.exports = function() { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialize the global variable object. + //---------------------------------------------------------------------------- + var vars = { + "types": { + "auto": require("./types/auto.js"), + "button": require("./types/button/button.coffee"), + "drop": require("./types/drop/drop.coffee"), + "toggle": require("./types/toggle.js") + } + }; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create the main drawing function. + //---------------------------------------------------------------------------- + vars.self = function( selection ) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Set timing to 0 if it's the first time running this function or if the + // data length is longer than the "large" limit + //-------------------------------------------------------------------------- + var large = vars.data.value instanceof Array && vars.data.value.length > vars.data.large; + + vars.draw.timing = vars.draw.first || large || ie ? 0 : vars.timing.ui; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create/update the UI element + //-------------------------------------------------------------------------- + if ( vars.data.value instanceof Array ) { + + if ( vars.dev.value ) print.group("drawing \""+vars.type.value+"\""); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Analyze new data, if changed. + //------------------------------------------------------------------------ + if ( vars.data.changed ) { + vars.data.cache = {}; + dataKeys( vars , "data" ); + dataFormat( vars ); + } + + vars.data.viz = fetchData( vars ); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Sort the data, if needed. + //------------------------------------------------------------------------ + if (vars.data.sort.value && (vars.data.changed || vars.order.changed || vars.order.sort.changed) ) { + arraySort( vars.data.viz , vars.order.value || vars.text.value, + vars.order.sort.value , vars.color.value , vars ); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Set first element in data as focus if there is no focus set. + //------------------------------------------------------------------------ + if (vars.focus.value === false && ["auto", "button"].indexOf(vars.type.value) < 0) { + + var element = vars.data.element.value; + + if ( element && element.node().tagName.toLowerCase() === "select" ) { + var i = element.property("selectedIndex"); + i = i < 0 ? 0 : i; + var option = element.selectAll("option")[0][i], + val = option.getAttribute("data-"+vars.id.value) || option.getAttribute(vars.id.value); + if (val) vars.focus.value = val; + } + + if ( vars.focus.value === false && vars.data.viz.length ) { + vars.focus.value = vars.data.viz[0][vars.id.value]; + } + + if (vars.dev.value && vars.focus.value !== false) print.log("\"value\" set to \""+vars.focus.value+"\""); + + } + + var getLevel = function(d,depth) { + + depth = typeof depth !== "number" ? vars.id.nesting.length === 1 ? 0 : vars.id.nesting.length-1 : depth; + var level = vars.id.nesting[depth]; + + if ( depth > 0 && (!(level in d) || d[level] instanceof Array) ) { + return getLevel(d,depth-1); + } + else { + return level; + } + + }; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Run these things if the data has changed. + //------------------------------------------------------------------------ + if ( vars.data.changed ) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Determine if search box is needed. + //---------------------------------------------------------------------- + if ( vars.search.value === "auto" ) { + + if (vars.data.viz.length > 10) { + vars.search.enabled = true; + if ( vars.dev.value ) print.log("Search enabled."); + } + else { + vars.search.enabled = false; + if ( vars.dev.value ) print.log("Search disabled."); + } + + } + else { + + vars.search.enabled = vars.search.value; + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Update OPTION elements with the new data. + //---------------------------------------------------------------------- + var elementTag = vars.data.element.value ? vars.data.element.value.node().tagName.toLowerCase() : ""; + if ( vars.data.element.value && elementTag === "select" ) { + + var optionData = []; + for (var level in vars.data.nested.all) { + optionData = optionData.concat(vars.data.nested.all[level]); + } + + options = vars.data.element.value.selectAll("option") + .data(optionData,function(d){ + var level = d ? getLevel(d) : false; + return d && level in d ? d[level] : false; + }); + + options.exit().remove(); + + options.enter().append("option"); + + options + .each(function(d){ + + var level = getLevel(d), + textKey = level === vars.id.value ? vars.text.value || vars.id.value + : vars.text.nesting !== true && level in vars.text.nesting ? vars.text.nesting[level] : level; + + for ( var k in d ) { + + if ( typeof d[k] !== "object" ) { + + if ( k === textKey ) { + d3.select(this).html(d[k]); + } + + if ( ["alt","value"].indexOf(k) >= 0 ) { + d3.select(this).attr(k,d[k]); + } + else { + d3.select(this).attr("data-"+k,d[k]); + } + + } + + } + + if (d[level] === vars.focus.value) { + this.selected = true; + } + else { + this.selected = false; + } + + }); + + } + + } + else if (vars.focus.changed && vars.data.element.value) { + var tag = vars.data.element.value.node().tagName.toLowerCase(); + if (tag === "select") { + vars.data.element.value.selectAll("option") + .each(function(d){ + if (d[getLevel(d)] === vars.focus.value) { + this.selected = true; + } + else { + this.selected = false; + } + }); + } + else { + var tag = vars.data.element.value.attr("type").toLowerCase(); + if (tag === "radio") { + vars.data.element.value + .each(function(d){ + if (this.value === vars.focus.value) { + this.checked = true; + } + else { + this.checked = false; + } + }) + } + } + } + + if ( vars.type.value !== "auto" ) { + + if ( !vars.container.ui ) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Select container DIV for UI element + //---------------------------------------------------------------------- + vars.container.ui = vars.container.value + .selectAll("div#d3plus_"+vars.type.value+"_"+vars.container.id) + .data(["container"]); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create container DIV for UI element + //---------------------------------------------------------------------- + var before = vars.data.element.value ? vars.data.element.value[0][0] : null; + + if ( before ) { + + if ( before.id ) { + before = "#"+before.id; + } + else { + + var id = before.getAttribute(vars.id.value) ? vars.id.value : "data-"+vars.id.value; + + if ( before.getAttribute(id) ) { + before = "["+id+"="+before.getAttribute(id)+"]"; + } + else { + before = null; + } + + } + + } + + vars.container.ui.enter() + .insert("div",before) + .attr("id","d3plus_"+vars.type.value+"_"+vars.container.id) + .style("position","relative") + .style("overflow","visible") + .style("vertical-align","top"); + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Update Container + //------------------------------------------------------------------------ + vars.container.ui + .style("display", vars.ui.display.value); + + vars.container.ui.transition().duration(vars.draw.timing) + .style("margin", vars.ui.margin.css); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create title, if available. + //------------------------------------------------------------------------ + var title = vars.container.ui.selectAll("div.d3plus_title") + .data(vars.title.value ? [vars.title.value] : []); + + title.enter().insert("div","#d3plus_"+vars.type.value+"_"+vars.container.id) + .attr("class","d3plus_title") + .style("display","inline-block"); + + title + .style("color",vars.font.color) + .style("font-family",vars.font.family.value) + .style("font-size",vars.font.size+"px") + .style("font-weight",vars.font.weight) + .style("padding",vars.ui.padding.css) + .style("border-color","transparent") + .style("border-style","solid") + .style("border-width",vars.ui.border+"px") + .text(String) + .each(function(d){ + vars.margin.left = this.offsetWidth; + }); + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Call specific UI element type, if there is data. + //------------------------------------------------------------------------ + if ( vars.data.value.length ) { + + var app = vars.format.locale.value.visualization[vars.type.value]; + if ( vars.dev.value ) print.time("drawing "+ app); + vars.types[vars.type.value]( vars ); + if ( vars.dev.value ) print.timeEnd("drawing "+ app); + + } + else if ( vars.data.url && (!vars.data.loaded || vars.data.stream) ) { + + dataLoad( vars , "data" , vars.self.draw ); + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialization complete + //------------------------------------------------------------------------ + if (vars.dev.value) print.timeEnd("total draw time"); + methodReset( vars ); + + } + + }; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Define methods and expose public variables. + //---------------------------------------------------------------------------- + attach(vars, { + "active": require("./methods/active.coffee"), + "alt": require("./methods/alt.coffee"), + "color": require("./methods/color.coffee"), + "config": require("./methods/config.coffee"), + "container": require("./methods/container.coffee"), + "data": require("./methods/data.js"), + "depth": require("./methods/depth.coffee"), + "dev": require("./methods/dev.coffee"), + "draw": require("./methods/draw.js"), + "focus": require("./methods/focus.coffee"), + "font": require("./methods/font.coffee"), + "format": require("./methods/format.coffee"), + "height": require("./methods/height.coffee"), + "history": require("./methods/history.coffee"), + "hover": require("./methods/hover.coffee"), + "icon": require("./methods/icon.coffee"), + "id": require("./methods/id.coffee"), + "keywords": require("./methods/keywords.coffee"), + "margin": require("./methods/margin.coffee"), + "open": require("./methods/open.coffee"), + "order": require("./methods/order.coffee"), + "remove": require("./methods/remove.coffee"), + "search": require("./methods/search.coffee"), + "select": require("./methods/select.coffee"), + "selectAll": require("./methods/selectAll.coffee"), + "text": require("./methods/text.coffee"), + "timing": require("./methods/timing.coffee"), + "title": require("./methods/title.coffee"), + "type": require("./methods/type.coffee"), + "ui": require("./methods/ui.coffee"), + "width": require("./methods/width.coffee") + }); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Finally, return the main UI function to the user + //---------------------------------------------------------------------------- + return vars.self; + +}; + +},{"../array/sort.coffee":34,"../client/ie.js":37,"../core/console/print.coffee":52,"../core/data/format.js":56,"../core/data/keys.coffee":58,"../core/data/load.coffee":59,"../core/fetch/data.js":64,"../core/methods/attach.coffee":80,"../core/methods/reset.coffee":93,"./methods/active.coffee":105,"./methods/alt.coffee":106,"./methods/color.coffee":107,"./methods/config.coffee":108,"./methods/container.coffee":109,"./methods/data.js":110,"./methods/depth.coffee":111,"./methods/dev.coffee":112,"./methods/draw.js":113,"./methods/focus.coffee":114,"./methods/font.coffee":115,"./methods/format.coffee":116,"./methods/height.coffee":117,"./methods/history.coffee":118,"./methods/hover.coffee":119,"./methods/icon.coffee":120,"./methods/id.coffee":121,"./methods/keywords.coffee":122,"./methods/margin.coffee":123,"./methods/open.coffee":124,"./methods/order.coffee":125,"./methods/remove.coffee":126,"./methods/search.coffee":127,"./methods/select.coffee":128,"./methods/selectAll.coffee":129,"./methods/text.coffee":130,"./methods/timing.coffee":131,"./methods/title.coffee":132,"./methods/type.coffee":133,"./methods/ui.coffee":134,"./methods/width.coffee":135,"./types/auto.js":136,"./types/button/button.coffee":137,"./types/drop/drop.coffee":142,"./types/toggle.js":159}],105:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [false, Array, Function, Number, String], + value: false +}; + + +},{"../../core/methods/filter.coffee":81}],106:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [false, Array, Function, Object, String], + mute: filter(true), + solo: filter(true), + value: "alt" +}; + + +},{"../../core/methods/filter.coffee":81}],107:[function(require,module,exports){ +module.exports = { + accepted: [String], + value: "color" +}; + + +},{}],108:[function(require,module,exports){ +module.exports = { + accepted: [Object], + objectAccess: false, + process: function(value, vars) { + var method, setting; + for (method in value) { + setting = value[method]; + if (method in vars.self) { + vars.self[method](setting); + } + } + return value; + }, + value: {} +}; + + +},{}],109:[function(require,module,exports){ +var d3selection; + +d3selection = require("../../util/d3selection.coffee"); + +module.exports = { + accepted: [false, Array, Object, String], + element: false, + id: "default", + process: function(value) { + if (value === false) { + return d3.select("body"); + } else if (d3selection(value)) { + return value; + } else if (value instanceof Array) { + return d3.select(value[0][0]); + } else { + this.selector = value; + return d3.select(value); + } + }, + value: d3.select("body") +}; + + +},{"../../util/d3selection.coffee":208}],110:[function(require,module,exports){ +var d3selection = require("../../util/d3selection.coffee"), + process = require("../../core/methods/process/data.coffee"); + +module.exports = { + "accepted" : [ false , Array , Function , String ], + "delimiter" : { + "accepted" : [ String ], + "value" : "|" + }, + "element": { + "process": function(value, vars) { + + var element = false; + + if ( d3selection(value) ) { + element = value; + } + else if (typeof value === "string" && !d3.select(value).empty()) { + element = d3.select(value); + } + + if (element) { + vars.self.container(d3.select(element.node().parentNode)); + } + + return element; + + }, + "value": false + }, + "filetype" : { + "accepted" : [false, "json", "xml", "html", "csv", "dsv", "tsv", "txt"], + "value" : false + }, + "filters" : [], + "large": 400, + "mute" : [], + "process" : function(value, vars) { + + if ( vars.container.id === "default" && value.length ) { + vars.self.container({"id": "default"+value.length}); + } + + return process(value, vars, this); + }, + "solo" : [], + "sort": { + "accepted": [Boolean], + "value": false + }, + "value" : false +}; + +},{"../../core/methods/process/data.coffee":87,"../../util/d3selection.coffee":208}],111:[function(require,module,exports){ +module.exports = { + accepted: [Number], + value: 0 +}; + + +},{}],112:[function(require,module,exports){ +module.exports = { + accepted: [Boolean], + value: false +}; + + +},{}],113:[function(require,module,exports){ +var d3selection = require("../../util/d3selection.coffee"), + hideElement = require("../../core/parse/hideElement.js"), + parseElement = require("../../core/parse/element.js"), + print = require("../../core/console/print.coffee"), + stringFormat = require("../../string/format.js") + +module.exports = { + "accepted" : [ undefined , Function ], + "first" : true, + "frozen" : false, + "process" : function (value, vars) { + + if ( this.initialized === false ) { + this.initialized = true + return value + } + + if (vars.data.value && (!(vars.data.value instanceof Array) || d3selection(vars.data.value))) { + vars.data.value = parseElement( vars ) + } + else if (vars.data.element.value) { + vars.data.element.value.call(hideElement); + } + + if ( value === undefined && typeof this.value === "function" ) { + value = this.value + } + + if ( vars.container.value === false ) { + + var str = vars.format.locale.value.dev.setContainer + print.warning( str , "container" ) + + } + else if ( vars.container.value.empty() ) { + + var str = vars.format.locale.value.dev.noContainer + var selector = vars.container.selector || ""; + print.warning( stringFormat(str, "\"" + selector + "\"") , "container" ) + + } + else { + + if (vars.dev.value) print.time("total draw time"); + + vars.container.value.call(vars.self); + + } + + if ( typeof value === "function" && vars.history.chain.length ) { + + var changesObject = {} + vars.history.chain.forEach(function(c){ + var method = c.method + delete c.method + changesObject[method] = c + }) + + value(changesObject) + + vars.history.chain = [] + + } + + return value + + }, + "update" : true, + "value" : undefined +} + +},{"../../core/console/print.coffee":52,"../../core/parse/element.js":96,"../../core/parse/hideElement.js":97,"../../string/format.js":173,"../../util/d3selection.coffee":208}],114:[function(require,module,exports){ +module.exports = { + accepted: [false, Number, String], + deprecates: "highlight", + process: function(value, vars) { + var d, element, elementTag, elementType, i, j, k, len, len1, ref; + element = vars.data.element.value; + if (element && ["string", "number"].indexOf(typeof value) >= 0) { + elementTag = element.node().tagName.toLowerCase(); + elementType = element.attr("type"); + if (elementTag === "select") { + ref = element.selectAll("option"); + for (i = j = 0, len = ref.length; j < len; i = ++j) { + d = ref[i]; + if (d && d[vars.id.value] === value) { + element.node().selectedIndex = i; + } + } + } else if (elementTag === "input" && elementType === "radio") { + for (k = 0, len1 = element.length; k < len1; k++) { + d = element[k]; + this.checked = d && d[vars.id.value] === value; + } + } + } + return value; + }, + value: false +}; + + +},{}],115:[function(require,module,exports){ +var align, decoration, family, transform; + +family = require("../../core/methods/font/family.coffee"); + +align = require("../../core/methods/font/align.coffee"); + +decoration = require("../../core/methods/font/decoration.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +module.exports = { + align: align(), + color: "#444444", + decoration: decoration(), + family: family(), + secondary: { + align: align(), + color: "#444444", + decoration: decoration(), + family: family(), + size: 12, + spacing: 0, + transform: transform(), + weight: 200 + }, + size: 12, + spacing: 0, + transform: transform(), + weight: 200 +}; + + +},{"../../core/methods/font/align.coffee":82,"../../core/methods/font/decoration.coffee":83,"../../core/methods/font/family.coffee":84,"../../core/methods/font/transform.coffee":86}],116:[function(require,module,exports){ +var formatNumber, locale, mergeObject, titleCase; + +formatNumber = require("../../number/format.coffee"); + +locale = require("../../core/locale/locale.coffee"); + +mergeObject = require("../../object/merge.coffee"); + +titleCase = require("../../string/title.coffee"); + +module.exports = { + accepted: [Function, String], + affixes: { + accepted: [Object], + objectAccess: false, + value: {} + }, + deprecates: ["number_format", "text_format"], + locale: { + accepted: function() { + return d3.keys(locale); + }, + process: function(value) { + var defaultLocale, returnObject; + defaultLocale = "en_US"; + returnObject = locale[defaultLocale]; + if (value !== defaultLocale) { + returnObject = mergeObject(returnObject, locale[value]); + } + this.language = value; + return returnObject; + }, + value: "en_US" + }, + number: { + accepted: [false, Function], + value: false + }, + process: function(value, vars) { + if (typeof value === "string") { + vars.self.format({ + locale: value + }); + } else { + if (typeof value === "function") { + return value; + } + } + return this.value; + }, + text: { + accepted: [false, Function], + value: false + }, + value: function(value, opts) { + var f, v, vars; + if (!opts) { + opts = {}; + } + vars = opts.vars || {}; + if (vars.time && vars.time.value && opts.key === vars.time.value) { + v = value.constructor === Date ? value : new Date(value); + return vars.data.time.format(v); + } else if (typeof value === "number") { + f = this.number.value || formatNumber; + return f(value, opts); + } else if (typeof value === "string") { + f = this.text.value || titleCase; + return f(value, opts); + } else { + return JSON.stringify(value); + } + } +}; + + +},{"../../core/locale/locale.coffee":79,"../../number/format.coffee":170,"../../object/merge.coffee":171,"../../string/title.coffee":176}],117:[function(require,module,exports){ +module.exports = { + accepted: [false, Number], + max: 600, + secondary: false, + value: false +}; + + +},{}],118:[function(require,module,exports){ +module.exports = { + back: function() { + if (this.states.length) { + return this.states.pop()(); + } + }, + chain: [], + reset: function() { + var results; + results = []; + while (this.states.length) { + results.push(this.states.pop()()); + } + return results; + }, + states: [] +}; + + +},{}],119:[function(require,module,exports){ +module.exports = { + accepted: [Boolean, Number, String], + value: false +}; + + +},{}],120:[function(require,module,exports){ +var process; + +process = require("../../core/methods/process/icon.coffee"); + +module.exports = { + accepted: [false, Array, Function, Object, String], + back: { + accepted: [false, String], + fallback: "❮", + opacity: 1, + process: process, + rotate: 0, + value: "fa-angle-left" + }, + button: { + accepted: [false, String], + fallback: false, + opacity: 1, + process: process, + rotate: 0, + value: false + }, + drop: { + accepted: [false, String], + fallback: "❯", + opacity: 1, + process: process, + rotate: 0, + value: "fa-angle-down" + }, + next: { + accepted: [false, String], + fallback: "❯", + opacity: 1, + process: process, + rotate: 0, + value: "fa-angle-right" + }, + select: { + accepted: [false, String], + fallback: "✓", + opacity: 1, + process: process, + rotate: 0, + value: "fa-check" + }, + style: { + accepted: [Object, String], + value: "default" + }, + value: "icon" +}; + + +},{"../../core/methods/process/icon.coffee":89}],121:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [Array, String], + dataFilter: true, + mute: filter(true), + nesting: ["value"], + solo: filter(true), + value: "value" +}; + + +},{"../../core/methods/filter.coffee":81}],122:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [false, Array, Function, Object, String], + mute: filter(true), + solo: filter(true), + value: "keywords" +}; + + +},{"../../core/methods/filter.coffee":81}],123:[function(require,module,exports){ +var process; + +process = require("../../core/methods/process/margin.coffee"); + +module.exports = { + accepted: [Number, Object, String], + process: function(value) { + var userValue; + if (value === void 0) { + value = this.value; + } + userValue = value; + process(value, this); + return userValue; + }, + value: 0 +}; + + +},{"../../core/methods/process/margin.coffee":90}],124:[function(require,module,exports){ +module.exports = { + accepted: [Boolean], + flipped: { + accepted: [Boolean], + value: false + }, + value: false +}; + + +},{}],125:[function(require,module,exports){ +module.exports = { + accepted: [false, Function, String], + sort: { + accepted: ["asc", "desc"], + deprecates: ["sort"], + value: "asc" + }, + value: false +}; + + +},{}],126:[function(require,module,exports){ +module.exports = { + accepted: [void 0, Function], + process: function(value, vars) { + if (this.initialized) { + vars.container.ui.remove(); + } + delete vars.container.ui; + }, + value: void 0 +}; + + +},{}],127:[function(require,module,exports){ +module.exports = { + accepted: ["auto", Boolean], + process: function(value) { + if (typeof value === "Boolean") { + this.enabled = value; + } + return value; + }, + term: "", + value: "auto" +}; + + +},{}],128:[function(require,module,exports){ +module.exports = { + accepted: [String], + chainable: false, + process: function(value, vars) { + var container; + container = vars.container.value; + if (container && value) { + return container.select(value); + } else { + return value; + } + }, + value: void 0 +}; + + +},{}],129:[function(require,module,exports){ +module.exports = { + accepted: [String], + chainable: false, + process: function(value, vars) { + var container; + container = vars.container.value; + if (container && value) { + return container.selectAll(value); + } else { + return value; + } + }, + value: void 0 +}; + + +},{}],130:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [false, String], + nesting: true, + mute: filter(true), + solo: filter(true), + secondary: { + accepted: [false, String], + nesting: true, + value: false + }, + value: false +}; + + +},{"../../core/methods/filter.coffee":81}],131:[function(require,module,exports){ +module.exports = { + mouseevents: 60, + ui: 200 +}; + + +},{}],132:[function(require,module,exports){ +var decoration, family, stringStrip, transform; + +decoration = require("../../core/methods/font/decoration.coffee"); + +family = require("../../core/methods/font/family.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +stringStrip = require("../../string/strip.js"); + +module.exports = { + accepted: [false, Function, String], + font: { + align: "center", + color: "#444444", + decoration: decoration(), + family: family(), + size: 16, + transform: transform(), + weight: 400 + }, + link: false, + process: function(value, vars) { + var id; + if (vars.container.id.indexOf("default") === 0 && value) { + id = stringStrip(value).toLowerCase(); + vars.self.container({ + id: id + }); + } + return value; + }, + value: false +}; + + +},{"../../core/methods/font/decoration.coffee":83,"../../core/methods/font/family.coffee":84,"../../core/methods/font/transform.coffee":86,"../../string/strip.js":175}],133:[function(require,module,exports){ +module.exports = { + accepted: function(vars) { + return d3.keys(vars.types); + }, + value: "auto" +}; + + +},{}],134:[function(require,module,exports){ +var align, decoration, family, margin, transform; + +family = require("../../core/methods/font/family.coffee"); + +align = require("../../core/methods/font/align.coffee"); + +decoration = require("../../core/methods/font/decoration.coffee"); + +margin = require("../../core/methods/process/margin.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +module.exports = { + align: align("center"), + border: 1, + color: { + primary: { + process: function(value, vars) { + var primary; + primary = this.value; + if (!vars.ui.color.secondary.value) { + vars.ui.color.secondary.value = d3.rgb(primary).darker(0.75).toString(); + } + return value; + }, + value: "#ffffff" + }, + secondary: { + value: false + } + }, + display: { + acceped: ["block", "inline-block"], + value: "inline-block" + }, + font: { + align: align("center"), + color: "#444", + decoration: decoration(), + family: family(), + size: 11, + transform: transform(), + weight: 200 + }, + margin: { + process: function(value) { + var userValue; + if (value === void 0) { + value = this.value; + } + userValue = value; + margin(value, this); + return userValue; + }, + value: 5 + }, + padding: { + process: function(value) { + var userValue; + if (value === void 0) { + value = this.value; + } + userValue = value; + margin(value, this); + return userValue; + }, + value: 5 + } +}; + + +},{"../../core/methods/font/align.coffee":82,"../../core/methods/font/decoration.coffee":83,"../../core/methods/font/family.coffee":84,"../../core/methods/font/transform.coffee":86,"../../core/methods/process/margin.coffee":90}],135:[function(require,module,exports){ +module.exports = { + accepted: [false, Number], + secondary: false, + value: false +}; + + +},{}],136:[function(require,module,exports){ +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Determines form type based on data length. +//------------------------------------------------------------------------------ +module.exports = function( vars ) { + + var dataLength = vars.data.value.length + + if ( dataLength === 1 ) { + vars.self.type("button").draw() + } + else if ( dataLength < 5 ) { + vars.self.type("toggle").draw() + } + else { + vars.self.type("drop").draw() + } + +} + +},{}],137:[function(require,module,exports){ +module.exports = function(vars) { + var button, checks, color, icons, mouseevents, print, style, updatedButtons; + print = require("../../../core/console/print.coffee"); + color = require("./functions/color.coffee"); + icons = require("./functions/icons.js"); + mouseevents = require("./functions/mouseevents.coffee"); + style = require("./functions/style.js"); + button = vars.container.ui.selectAll('div.d3plus_node').data(vars.data.viz, function(d) { + return d[vars.id.value]; + }); + if (vars.dev.value) { + print.time("enter"); + } + button.enter().append("div").attr("class", "d3plus_node").call(color, vars).call(style, vars).call(icons, vars).call(mouseevents, vars); + if (vars.dev.value) { + print.timeEnd("enter"); + } + if (vars.draw.update || vars.draw.timing) { + if (vars.dev.value) { + print.time("ordering"); + } + button.order(); + if (vars.dev.value) { + print.timeEnd("ordering"); + } + updatedButtons = button; + } else { + checks = [vars.focus.previous, vars.focus.value, vars.hover.previous, vars.hover.value].filter(function(c) { + return c; + }); + updatedButtons = button.filter(function(b) { + return checks.indexOf(b[vars.id.value]) >= 0; + }); + } + if (vars.dev.value) { + print.time("update"); + } + updatedButtons.classed("d3plus_button_active", function(d) { + return vars.focus.value === d[vars.id.value]; + }); + if (vars.draw.timing) { + updatedButtons.transition().duration(vars.draw.timing).call(color, vars).call(style, vars); + } else { + updatedButtons.call(color, vars).call(style, vars); + } + updatedButtons.call(icons, vars).call(mouseevents, vars); + if (vars.dev.value) { + print.timeEnd("update"); + } + return button.exit().remove(); +}; + + +},{"../../../core/console/print.coffee":52,"./functions/color.coffee":138,"./functions/icons.js":139,"./functions/mouseevents.coffee":140,"./functions/style.js":141}],138:[function(require,module,exports){ +module.exports = function(elem, vars) { + var legible, lighter, textColor; + legible = require("../../../../color/legible.coffee"); + lighter = require("../../../../color/lighter.coffee"); + textColor = require("../../../../color/text.coffee"); + return elem.style("background-color", function(d) { + var color; + if (vars.focus.value === d[vars.id.value]) { + color = vars.ui.color.secondary.value; + } else { + color = vars.ui.color.primary.value; + } + if (vars.hover.value === d[vars.id.value]) { + color = d3.rgb(color).darker(0.15).toString(); + } + return color; + }).style("color", function(d) { + var bg, color, image, opacity; + if (vars.focus.value === d[vars.id.value]) { + opacity = 0.75; + } else { + opacity = 1; + } + image = d[vars.icon.value] && vars.data.viz.length < vars.data.large; + if (!image && d[vars.color.value]) { + color = legible(d[vars.color.value]); + } else { + if (vars.focus.value === d[vars.id.value]) { + bg = vars.ui.color.secondary.value; + } else { + bg = vars.ui.color.primary.value; + } + if (vars.hover.value === d[vars.id.value]) { + bg = d3.rgb(bg).darker(0.15).toString(); + } + color = textColor(bg); + } + color = d3.rgb(color); + return "rgba(" + color.r + "," + color.g + "," + color.b + "," + opacity + ")"; + }).style('border-color', vars.ui.color.secondary.value); +}; + + +},{"../../../../color/legible.coffee":44,"../../../../color/lighter.coffee":45,"../../../../color/text.coffee":50}],139:[function(require,module,exports){ +var prefix = require("../../../../client/prefix.coffee"), + rtl = require("../../../../client/rtl.coffee") + +module.exports = function ( elem , vars ) { + + var reversed = (vars.font.align.value === "right" && !rtl) + || (rtl && vars.font.align.value === "right") + + elem + .each(function(d,i){ + + var children = ["label"] + + if ( d[vars.icon.value] && vars.data.viz.length <= vars.data.large ) { + children.push("icon") + } + + var iconGraphic = vars.icon.button.value + if ( d[vars.id.value] === vars.focus.value && vars.icon.select.value ) { + iconGraphic = vars.icon.select.value + children.push("selected") + } + else if ( iconGraphic && d.d3plus.icon !== false ) { + children.push("selected") + } + + var buffer = 0 + + var items = d3.select(this).selectAll("div.d3plus_button_element") + .data(children,function(c){ + return c + }) + + items.enter().append("div") + .style("display",function(c){ + return c === "label" ? "block" : "absolute" + }) + + items.order() + .attr("class",function(c){ + var extra = "" + if ( c === "selected" && iconGraphic.indexOf("fa-") === 0 ) { + extra = " fa "+iconGraphic + } + return "d3plus_button_element d3plus_button_" + c + extra + }) + .html(function(c){ + if ( c === "label" ) { + var k = vars.text.value && vars.text.value in d && !(d[vars.text.value] instanceof Array) + ? vars.text.value : vars.id.value + return vars.format.value(d[k]) + } + return c === "selected" && iconGraphic.indexOf("fa-") < 0 + ? iconGraphic : "" + }) + .style("background-image",function(c){ + if (c === "icon") { + return "url('"+d[vars.icon.value]+"')" + } + return "none" + }) + .style("background-color",function(c){ + if (c === "icon" && d.style === "knockout") { + return d[vars.color.value] || vars.ui.color.primary.value + } + return "transparent" + }) + .style("background-size","100%") + .style("text-align",function(c){ + return c === "label" ? vars.font.align.value : "center" + }) + .style("position",function(c){ + return c == "label" ? "static" : "absolute" + }) + .style("width",function(c){ + + if ( c === "label" ) { + return "auto" + } + + if (vars.height.value) { + buffer = (vars.height.value-(vars.ui.padding.top + vars.ui.padding.bottom)-(vars.ui.border*2)); + } + else { + buffer = vars.font.size+vars.ui.border; + } + return buffer+"px" + }) + .style("height",function(c){ + if ( c === "icon" ) { + return buffer+"px" + } + return "auto" + }) + .style("margin-top",function(c){ + if ( c === "label" ) { + return "0px" + } + if (this.offsetHeight || this.getBoundingClientRect().height) { + var h = this.offsetHeight || this.getBoundingClientRect().height + } + else if ( c === "selected" ) { + var h = vars.font.size + } + else { + var h = buffer + } + return -h/2+"px" + }) + .style("top",function(c){ + return c === "label" ? "auto" : "50%" + }) + .style("left",function(c){ + if ((c === "icon" && !reversed) || (c === "selected" && reversed)) { + return vars.ui.padding.left+"px" + } + return "auto" + }) + .style("right",function(c){ + if ((c === "icon" && reversed) || (c === "selected" && !reversed)) { + return vars.ui.padding.right+"px" + } + return "auto" + }) + .style(prefix()+"transition",function(c){ + return c === "selected" ? (vars.draw.timing/1000)+"s" : "none" + }) + .style(prefix()+"transform",function(c){ + var degree = c === "selected" ? vars.icon.select.rotate : "none" + return typeof degree === "string" ? degree : "rotate("+degree+"deg)" + }) + .style("opacity",function(c){ + return c === "selected" ? vars.icon.select.opacity : 1 + }) + + items.exit().remove() + + var text = d3.select(this).selectAll(".d3plus_button_label") + + if (buffer > 0) { + + var p = vars.ui.padding; + + if (children.length === 3) { + p = p.top+"px "+(p.right*2+buffer)+"px "+p.bottom+"px "+(p.left*2+buffer)+"px"; + } + else if ((children.indexOf("icon") >= 0 && !rtl) || (children.indexOf("selected") >= 0 && rtl)) { + p = p.top+"px "+p.right+"px "+p.bottom+"px "+(p.left*2+buffer)+"px"; + } + else { + p = p.top+"px "+(p.right*2+buffer)+"px "+p.bottom+"px "+p.left+"px"; + } + + text.style("padding", p) + + } + else { + text.style("padding",vars.ui.padding.css) + } + + if (typeof vars.width.value === "number") { + var width = vars.width.value + width -= parseFloat(text.style("padding-left"),10) + width -= parseFloat(text.style("padding-right"),10) + width -= vars.ui.border*2 + width += "px" + } + else { + var width = "auto" + } + + text.style("width",width) + + }) + +} + +},{"../../../../client/prefix.coffee":39,"../../../../client/rtl.coffee":40}],140:[function(require,module,exports){ +module.exports = function(elem, vars, color) { + var events, ie; + color = require("./color.coffee"); + events = require("../../../../client/pointer.coffee"); + ie = require("../../../../client/ie.js"); + return elem.on(events.over, function(d, i) { + vars.self.hover(d[vars.id.value]); + if (ie || !vars.draw.timing) { + return d3.select(this).style("cursor", "pointer").call(color, vars); + } else { + return d3.select(this).style("cursor", "pointer").transition().duration(vars.timing.mouseevents).call(color, vars); + } + }).on(events.out, function(d) { + vars.self.hover(false); + if (ie || !vars.draw.timing) { + return d3.select(this).style("cursor", "auto").call(color, vars); + } else { + return d3.select(this).style("cursor", "auto").transition().duration(vars.timing.mouseevents).call(color, vars); + } + }).on(events.click, function(d) { + if (vars.focus.value !== false) { + return vars.self.focus(d[vars.id.value]).draw(); + } else if (vars.focus.callback) { + return vars.focus.callback(d, vars.self); + } + }); +}; + + +},{"../../../../client/ie.js":37,"../../../../client/pointer.coffee":38,"./color.coffee":138}],141:[function(require,module,exports){ +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// +//------------------------------------------------------------------------------ +module.exports = function ( elem , vars ) { + + elem + .style("position","relative") + .style("margin",vars.ui.margin.css) + .style("display",vars.ui.display.value) + .style("border-style","solid") + .style("border-width",vars.ui.border+"px") + .style("font-family",vars.font.family.value) + .style("font-size",vars.font.size+"px") + .style("font-weight",vars.font.weight) + .style("letter-spacing",vars.font.spacing+"px") + +} + +},{}],142:[function(require,module,exports){ +module.exports = function(vars) { + var button, data, element, keyboard, list, search, selector, title, update, width, windowevent; + element = require("./functions/element.coffee"); + keyboard = require("./functions/keyboard.coffee"); + windowevent = require("./functions/window.js"); + width = require("./functions/width.js"); + button = require("./functions/button.js"); + selector = require("./functions/selector.js"); + title = require("./functions/title.js"); + search = require("./functions/search.js"); + list = require("./functions/list.js"); + data = require("./functions/data.js"); + update = require("./functions/update.js"); + vars.margin.top = 0; + vars.margin.title = 0; + element(vars); + keyboard(vars); + windowevent(vars); + width(vars); + button(vars); + selector(vars); + title(vars); + search(vars); + list(vars); + data(vars); + return update(vars); +}; + + +},{"./functions/button.js":145,"./functions/data.js":146,"./functions/element.coffee":147,"./functions/keyboard.coffee":150,"./functions/list.js":151,"./functions/search.js":153,"./functions/selector.js":154,"./functions/title.js":155,"./functions/update.js":156,"./functions/width.js":157,"./functions/window.js":158}],143:[function(require,module,exports){ +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Checks to see if a given variable is allowed to be selected. +//------------------------------------------------------------------------------ +module.exports = function ( vars , value , active ) { + + var ret = [] + , active = active || vars.active.value + + if ( active instanceof Array ) { + + for (var i = 0; i < active.length; i++) { + ret.push(this(vars,value,active[i])) + } + + } + else { + + var t = typeof active + + if (t === "number") { + ret.push(vars.depth.value === active) + } + else if (t === "function") { + ret.push(active(value)) + } + else { + ret.push(value === active) + } + + } + + return ret.indexOf(true) >= 0 + +} + +},{}],144:[function(require,module,exports){ +var print = require("../../../../core/console/print.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Toggles the state of the dropdown menu. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + if ( vars.dev.value ) print.time("rotating arrow") + + var offset = vars.icon.drop.value === "❯" ? 90 : 0 + + if (vars.open.value != vars.open.flipped.value) { + var rotate = 180 + offset + } + else { + var rotate = offset + } + + vars.container.button + .icon({ + "select": { + "opacity": vars.open.value ? 0.5 : 1, + "rotate": rotate + } + }) + .draw() + + if ( vars.dev.value ) print.timeEnd("rotating arrow") + +} + +},{"../../../../core/console/print.coffee":52}],145:[function(require,module,exports){ +var copy = require("../../../../util/copy.coffee"), + events = require("../../../../client/pointer.coffee"), + form = require("../../../form.js"), + print = require("../../../../core/console/print.coffee") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates and styles the main drop button. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + if ( !("button" in vars.container) ) { + + if ( vars.dev.value ) print.time("creating main button") + + vars.container.button = form() + .container(vars.container.ui) + .type("button") + .ui({ + "margin": 0 + }) + + if ( vars.dev.value ) print.timeEnd("creating main button") + + } + + if ( vars.focus.changed || vars.data.changed || vars.depth.changed ) { + + var depth = vars.depth.value + + var buttonData = copy(vars.data.value.filter(function(d){ + var match = false + for ( var i = 0 ; i < vars.id.nesting.length ; i++ ) { + var level = vars.id.nesting[i] + match = level in d && d[level] === vars.focus.value + if (match) { + depth = i + break + } + } + return match + })[0]) + + if ( !buttonData ) { + buttonData = vars.container.button.data()[0] || vars.data.viz[0] + } + + vars.container.button + .data([buttonData]) + .id( vars.id.nesting ) + .depth(depth) + + } + + var hover = vars.hover.value === true ? vars.focus.value : false; + + vars.container.button + .draw({ + "update": vars.draw.update + }) + .focus("") + .font( vars.font ) + .format(vars.format) + .hover(hover) + .icon({ + "button": vars.icon.drop.value, + "select": vars.icon.drop.value, + "value": vars.icon.value + }) + .text( vars.text.value ) + .timing({ + "ui": vars.draw.timing + }) + .ui({ + "border": vars.ui.border, + "color": vars.ui.color, + "padding": vars.ui.padding.css + }) + .width(vars.width.value) + .draw() + + var button = vars.container.button.container(Object).ui + + vars.margin.top += button.node().offsetHeight || button.node().getBoundingClientRect().height + + button.on(events.click,function(){ + vars.self.open(!vars.open.value).draw() + }) + +} + +},{"../../../../client/pointer.coffee":38,"../../../../core/console/print.coffee":52,"../../../../util/copy.coffee":207,"../../../form.js":104}],146:[function(require,module,exports){ +var stringFormat = require("../../../../string/format.js"), + stringStrip = require("../../../../string/strip.js"); + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates and populates the dropdown list of items. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + if ( vars.data.url && !vars.data.loaded ) { + var loadingObject = {}; + loadingObject[vars.text.value || vars.id.value] = vars.format.value(vars.format.locale.value.ui.loading); + vars.data.filtered = [loadingObject]; + vars.data.changed = vars.data.lastFilter !== "loading"; + vars.data.lastFilter = "loading"; + } + else if (vars.open.value) { + + if (!vars.search.term) { + vars.data.filtered = vars.data.viz; + vars.data.changed = vars.data.lastFilter !== "viz"; + vars.data.lastFilter = "viz"; + if (vars.id.nesting.length > 1 && vars.depth.value < vars.id.nesting.length-1) { + vars.data.filtered = vars.data.filtered.filter(function(d){ + if ("endPoint" in d.d3plus && d.d3plus.endPoint === vars.depth.value) { + d.d3plus.icon = false; + } + return true; + }); + vars.data.changed = vars.data.lastFilter !== "depth"; + vars.data.lastFilter = "depth"; + } + } + else { + + var searchWords = stringStrip(vars.search.term).split("_"), + searchKeys = [vars.id.value, vars.text.value, vars.alt.value, vars.keywords.value ]; + + searchKeys = searchKeys.filter(function(t){ return t; }); + searchWords = searchWords.filter(function(t){ return t !== ""; }); + + var startMatches = [], + exactMatches = [], + softMatches = [], + searchData = []; + + vars.id.nesting.forEach(function(n){ + searchData = searchData.concat(vars.data.nested.all[n]); + }); + + searchData.forEach(function(d){ + + var match = false; + + searchKeys.forEach(function(key){ + + if ( !match && key in d && typeof d[key] === "string" ) { + + var text = d[key].toLowerCase(); + + if ( [vars.text.value,vars.id.value].indexOf(key) >= 0 && text.indexOf(vars.search.term) === 0 ) { + startMatches.push(d); + match = true; + } + else if ( text.indexOf(vars.search.term) >= 0 ) { + exactMatches.push(d); + match = true; + } + else { + + var texts = stringStrip(text).split("_"); + + for (var t in texts) { + + if ( !match ) { + + for (var s in searchWords) { + if (texts[t].indexOf(searchWords[s]) === 0) { + softMatches.push(d); + match = true; + break; + } + } + + } + else { + break; + } + + } + + } + } + + }); + + }); + + vars.data.filtered = d3.merge([ startMatches , exactMatches , softMatches ]); + + vars.data.filtered.forEach(function(d,i){ + d.d3plus_order = i; + }); + + vars.data.changed = true; + vars.data.lastFilter = "search"; + + if ( vars.data.filtered.length === 0 ) { + + var noData = {}, str = vars.format.value(vars.format.locale.value.ui.noResults); + noData[vars.text.value || vars.id.value] = stringFormat(str,"\""+vars.search.term+"\""); + vars.data.filtered = [ noData ]; + + } + + } + + } + else { + vars.data.filtered = []; + } + +}; + +},{"../../../../string/format.js":173,"../../../../string/strip.js":175}],147:[function(require,module,exports){ +module.exports = function(vars) { + if (vars.data.element.value) { + vars.data.element.value.on("focus." + vars.container.id, function() { + return vars.self.hover(true).draw(); + }); + vars.data.element.value.on("blur." + vars.container.id, function() { + var search; + if (vars.search.enabled) { + search = d3.event.relatedTarget !== vars.container.value.select('input').node(); + } else { + search = true; + } + if (search) { + return vars.self.open(false).hover(false).draw(); + } + }); + vars.data.element.value.on("change." + vars.container.id, function() { + return vars.self.focus(this.value).draw(); + }); + return vars.data.element.value.on("keydown.cancel_" + vars.container.id, function() { + if (d3.event.keyCode !== 9) { + return d3.event.preventDefault(); + } + }); + } +}; + + +},{}],148:[function(require,module,exports){ +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Calculates the height and orientation of the dropdown list, based on +// available screen space. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + var height = vars.height.secondary, + button = vars.container.button.container().node().getBoundingClientRect(), + available = window.innerHeight - button.bottom - vars.ui.border * 2 - + vars.ui.margin.top - vars.ui.margin.bottom - + vars.ui.padding.top - vars.ui.padding.bottom; + + if (available < button.height * 3) { + available = button.top-10; + vars.self.open({"flipped": true}); + } + // else { + // vars.self.open({"flipped": false}); + // } + + if (typeof height !== "number") { + height = available; + } + + if (height > vars.height.max) { + height = vars.height.max; + } + + vars.self.height({"secondary": height}); + +}; + +},{}],149:[function(require,module,exports){ +var active, copy, form, print; + +active = require("./active.js"); + +copy = require("../../../../util/copy.coffee"); + +form = require("../../../form.js"); + +print = require("../../../../core/console/print.coffee"); + +module.exports = function(vars) { + var deepest, large, order; + if (vars.open.value) { + if (vars.dev.value) { + print.time("updating list items"); + } + if (!("items" in vars.container)) { + vars.container.items = form().container(vars.container.list).type("button").ui({ + border: 0, + display: "block", + margin: 0 + }).width(false); + } + large = vars.draw.timing ? vars.data.large : 1; + order = copy(vars.order); + order.value = vars.search.term.length ? "d3plus_order" : vars.order.value; + deepest = vars.depth.value === vars.id.nesting.length - 1; + if (vars.focus.changed || vars.container.items.focus() === false) { + vars.container.items.focus(vars.focus.value, function(value) { + var change, data, depth, solo; + data = vars.data.filtered.filter(function(f) { + return f[vars.id.value] === value; + })[0]; + if (vars.depth.value < vars.id.nesting.length - 1 && vars.id.nesting[vars.depth.value + 1] in data) { + depth = vars.depth.value; + solo = vars.id.solo.value; + vars.history.states.push(function() { + return vars.self.depth(depth).id({ + solo: solo + }).draw(); + }); + vars.self.depth(vars.depth.value + 1).id({ + solo: [value] + }).draw(); + } else { + if (!vars.depth.changed) { + vars.self.open(false); + } + change = value !== vars.focus.value; + if (change && vars.active.value) { + change = active(vars, value); + } + if (change) { + vars.self.focus(value).draw(); + } + } + }); + } + vars.container.items.active(vars.active.value).data({ + large: large, + sort: vars.data.sort.value, + value: vars.data.filtered + }).draw({ + update: vars.draw.update + }).font(vars.font.secondary).format(vars.format).hover(vars.hover.value).id(vars.id.value).icon({ + button: (deepest ? false : vars.icon.next), + select: (deepest ? vars.icon.select : false), + value: vars.icon.value + }).order(order).text(vars.text.secondary.value || vars.text.value).timing({ + ui: vars.draw.timing + }).ui({ + color: { + primary: (vars.id.nesting.length === 1 ? vars.ui.color.primary.value : vars.ui.color.secondary.value), + secondary: vars.ui.color.secondary.value + }, + padding: vars.ui.padding.css + }).draw(); + if (vars.dev.value) { + print.timeEnd("updating list items"); + } + } +}; + + +},{"../../../../core/console/print.coffee":52,"../../../../util/copy.coffee":207,"../../../form.js":104,"./active.js":143}],150:[function(require,module,exports){ +module.exports = function(vars) { + return d3.select(window).on("keydown." + vars.container.id, function() { + var d, data, depth, hist, hover, i, index, j, key, len, matchKey, ref, solo; + key = d3.event.keyCode; + if (vars.open.value || vars.hover.value === true) { + matchKey = vars.hover.value === true ? "focus" : "hover"; + index = false; + ref = vars.data.filtered; + for (i = j = 0, len = ref.length; j < len; i = ++j) { + d = ref[i]; + if (d[vars.id.value] === vars[matchKey].value) { + index = i; + break; + } + } + if (key === 9 && vars.open.value && (!vars.search.enabled || (vars.search.enabled && !d3.event.shiftKey))) { + return vars.self.open(false).hover(false).draw(); + } else if ([38, 40].indexOf(key) >= 0) { + if (index === false) { + index = 0; + } else if (key === 38) { + if (vars.open.value) { + if (index <= 0) { + index = vars.data.filtered.length - 1; + } else { + index -= 1; + } + } + } else if (key === 40) { + if (vars.open.value) { + if (index >= vars.data.filtered.length - 1) { + index = 0; + } else { + index += 1; + } + } + } + if (typeof vars.hover.value !== "boolean") { + hover = vars.data.filtered[index][vars.id.value]; + } else { + hover = vars.focus.value; + } + return vars.self.hover(hover).open(true).draw(); + } else if (key === 13) { + if (typeof vars.hover.value !== "boolean") { + data = vars.data.filtered.filter(function(f) { + return f[vars.id.value] === vars.hover.value; + })[0]; + depth = vars.depth.value; + if (depth < vars.id.nesting.length - 1 && vars.id.nesting[depth + 1] in data) { + solo = vars.id.solo.value; + hist = function() { + return vars.self.depth(depth).id({ + solo: solo + }).draw(); + }; + vars.history.states.push(hist); + return vars.self.depth(vars.depth.value + 1).id({ + solo: [vars.hover.value] + }).draw(); + } else { + return vars.self.focus(vars.hover.value).hover(true).draw(); + } + } else { + return vars.self.hover(vars.focus.value).open(true).draw(); + } + } else if (key === 27) { + if (vars.open.value) { + return vars.self.open(false).hover(true).draw(); + } else if (vars.hover.value === true) { + return vars.self.hover(false).draw(); + } + } + } + }); +}; + + +},{}],151:[function(require,module,exports){ +var print = require("../../../../core/console/print.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates and populates the dropdown list of items. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + if ( vars.dev.value ) print.time("populating list") + + vars.container.list = vars.container.selector.selectAll("div.d3plus_drop_list") + .data(["list"]) + + vars.container.list.enter().append("div") + .attr("class","d3plus_drop_list") + .attr("id","d3plus_drop_list_"+vars.container.id) + .style("overflow-y","auto") + .style("overflow-x","hidden") + + if ( vars.dev.value ) print.timeEnd("populating list") + +} + +},{"../../../../core/console/print.coffee":52}],152:[function(require,module,exports){ +var print = require("../../../../core/console/print.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Calculates scroll position of list. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + if (vars.open.value) { + + if ( vars.dev.value ) print.time("calculating height") + + var hidden = false + if (vars.container.selector.style("display") == "none") { + var hidden = true + } + + if (hidden) vars.container.selector.style("display","block") + + var old_height = vars.container.selector.style("height"), + old_scroll = vars.container.selector.property("scrollTop"), + list_height = vars.container.list.style("max-height"), + list_scroll = vars.container.list.property("scrollTop") + + vars.container.selector.style("height","auto") + vars.container.list.style("max-height","200000px") + + vars.container.listHeight = parseFloat(vars.container.selector.style("height"),10) + + vars.container.list + .style("max-height",list_height) + .property("scrollTop",list_scroll) + + vars.container.selector + .style("height",old_height) + .property("scrollTop",old_scroll) + + var scrolling = false + if (vars.container.listHeight > vars.height.secondary) { + vars.container.listHeight = vars.height.secondary + scrolling = true + } + + if (hidden) vars.container.selector.style("display","none") + + if ( vars.dev.value ) print.timeEnd("calculating height") + + if (scrolling) { + + if ( vars.dev.value ) print.time("calculating scroll position") + + var options = vars.container.list.select("div").selectAll("div.d3plus_node") + var option = options[0][0] + var matchID = typeof vars.hover.value !== "boolean" ? vars.hover.value : vars.focus.value; + options.each(function(d,i){ + if (d[vars.id.value] === matchID) { + option = this + } + }) + + var hidden = false + if (vars.container.selector.style("display") === "none") { + hidden = true + vars.container.selector.style("display","block") + } + + var button_top = option.offsetTop, + button_height = option.offsetHeight || option.getBoundingClientRect().height, + list_top = vars.container.list.property("scrollTop") + + if (hidden) vars.container.selector.style("display","none") + + if ( hidden || vars.data.changed || vars.depth.changed ) { + + vars.container.listScroll = button_top + + } + else { + + vars.container.listScroll = list_top; + + if (button_top < list_top) { + vars.container.listScroll = button_top + } + else if (button_top+button_height > list_top+vars.height.secondary-vars.search.height) { + vars.container.listScroll = button_top - (vars.height.secondary-button_height-vars.search.height) + } + + } + + if ( vars.dev.value ) print.timeEnd("calculating scroll position") + + } + else { + vars.container.listScroll = 0 + } + + } + else { + vars.container.listScroll = vars.container.list.property("scrollTop") + vars.container.listHeight = 0 + } + +} + +},{"../../../../core/console/print.coffee":52}],153:[function(require,module,exports){ +var prefix = require("../../../../client/prefix.coffee"), + print = require("../../../../core/console/print.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates and styles the search box, if enabled. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + if ( vars.dev.value ) print.time("creating search") + + var data = require("./data.js") + , items = require("./items.coffee") + , update = require("./update.js") + + vars.container.search = vars.container.selector.selectAll("div.d3plus_drop_search") + .data(vars.search.enabled ? ["search"] : []) + + function searchStyle(elem) { + + elem + .style("padding",vars.ui.padding.css) + .style("display","block") + .style("background-color",d3.rgb(vars.ui.color.primary.value).darker(0.15).toString()) + + } + + function inputStyle(elem) { + + var width = vars.width.secondary - vars.ui.padding.left*2 - vars.ui.padding.right*2 + vars.ui.border*2 + + elem + .style("padding",vars.ui.padding.left/2+vars.ui.padding.right/2+"px") + .style("width",width+"px") + .style("border-width","0px") + .style("font-family",vars.font.secondary.family.value) + .style("font-size",vars.font.secondary.size+"px") + .style("font-weight",vars.font.secondary.weight) + .style("text-align",vars.font.secondary.align) + .style("outline","none") + .style(prefix()+"border-radius","0") + .attr("placeholder",vars.format.value(vars.format.locale.value.method.search)) + + } + + if (vars.draw.timing) { + + vars.container.search.transition().duration(vars.draw.timing) + .call(searchStyle) + + vars.container.search.select("input").transition().duration(vars.draw.timing) + .call(inputStyle) + + } + else { + + vars.container.search + .call(searchStyle) + + vars.container.search.select("input") + .call(inputStyle) + + } + + vars.container.search.enter() + .insert("div","#d3plus_drop_list_"+vars.container.id) + .attr("class","d3plus_drop_search") + .attr("id","d3plus_drop_search_"+vars.container.id) + .call(searchStyle) + .append("input") + .attr("id","d3plus_drop_input_"+vars.container.id) + .style("-webkit-appearance","none") + .call(inputStyle) + + vars.container.search.select("input").on("keyup."+vars.container.id,function(d){ + var term = this.value; + if (vars.search.term !== term) { + vars.search.term = term; + data(vars); + items(vars); + update(vars); + } + }); + + vars.container.search.exit().remove() + + var oldDisplay = vars.container.selector.style("display") + vars.container.selector.style("display", "block") + vars.search.height = vars.search.enabled ? vars.container.search.node().offsetHeight || + vars.container.search.node().getBoundingClientRect().height : 0; + vars.container.selector.style("display", oldDisplay) + + if ( vars.search.enabled ) { + vars.margin.title += vars.search.height + } + + if ( vars.dev.value ) print.timeEnd("creating search") + +} + +},{"../../../../client/prefix.coffee":39,"../../../../core/console/print.coffee":52,"./data.js":146,"./items.coffee":149,"./update.js":156}],154:[function(require,module,exports){ +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates and styles the div that holds the search box and item list. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + vars.container.selector = vars.container.ui + .selectAll("div.d3plus_drop_selector") + .data(["selector"]) + + vars.container.selector.enter().append("div") + .attr("class","d3plus_drop_selector") + .style("position","absolute") + .style("top","0px") + .style("z-index","-1") + .style("overflow","hidden") + + vars.container.selector + .style("padding",vars.ui.border+"px") + +} + +},{}],155:[function(require,module,exports){ +var events = require("../../../../client/pointer.coffee"), + lighter = require("../../../../color/lighter.coffee"), + print = require("../../../../core/console/print.coffee"), + textColor = require("../../../../color/text.coffee") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates and styles the title and back button. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + if ( vars.open.value ) { + + if ( vars.dev.value ) print.time("creating title and back button") + + var self = this + , enabled = vars.id.solo.value.length === 1 && vars.depth.value > 0 + , title = enabled + , focus = vars.container.button.data(Object).viz[0] + + title = true + for (var i = 0; i < vars.id.nesting.length; i++) { + var level = vars.id.nesting[i] + if ( level in focus && focus[level] === vars.focus.value ) { + title = false + break; + } + } + + vars.container.title = vars.container.selector.selectAll("div.d3plus_drop_title") + .data(enabled ? ["title"] : []) + + function boxStyle(elem) { + + elem + .style("padding",vars.ui.padding.css) + .style("display","block") + .style("background-color",vars.ui.color.secondary.value) + .style("font-family",vars.font.secondary.family.value) + .style("font-size",vars.font.secondary.size+"px") + .style("font-weight",vars.font.secondary.weight) + .style("text-align",vars.font.secondary.align) + .style("color",textColor(vars.ui.color.secondary.value)) + + } + + function backStyle(elem) { + + if ( !elem.empty() ) { + + var className = vars.icon.back.value.indexOf("fa-") === 0 ? " fa "+vars.icon.back.value : "" + className = "d3plus_drop_back" + className + + var text = vars.icon.back.value.indexOf("fa-") === 0 ? "" : vars.icon.back.value + + elem + .style("position","absolute") + .attr("class",className) + .style("top",vars.ui.padding.top+(vars.font.secondary.size/2)/2.5+"px") + .html(text) + + } + + } + + function titleStyle(elem) { + + var text = title ? vars.focus.value : vars.format.locale.value.ui.back + + elem + .text(vars.format.value(text)) + .style("padding","0px "+(vars.ui.padding.left+vars.ui.padding.right)+"px") + + } + + if (vars.draw.timing) { + + vars.container.title.transition().duration(vars.draw.timing) + .call(boxStyle) + + vars.container.title.select("div.d3plus_drop_title_text") + .transition().duration(vars.draw.timing) + .call(titleStyle) + + } + else { + + vars.container.title + .call(boxStyle) + + vars.container.title.select("div.d3plus_drop_title_text") + .call(titleStyle) + + } + + vars.container.title.select("span.d3plus_drop_back") + .call(backStyle) + + var enter = vars.container.title.enter() + .insert("div","#d3plus_drop_list_"+vars.container.id) + .attr("class","d3plus_drop_title") + .attr("id","d3plus_drop_title_"+vars.container.id) + .call(boxStyle) + + enter.append("span") + .attr("id","d3plus_drop_back_"+vars.container.id) + .attr("class","d3plus_drop_back") + .call(backStyle) + + enter.append("div") + .attr("id","d3plus_drop_title_text_"+vars.container.id) + .attr("class","d3plus_drop_title_text") + .call(titleStyle) + + vars.container.title + .on(events.over,function(d,i){ + + var color = lighter(vars.ui.color.secondary.value) + + d3.select(this).style("cursor","pointer") + .transition().duration(vars.timing.mouseevents) + .style("background-color",color) + .style("color",textColor(color)) + + }) + .on(events.out,function(d){ + + var color = vars.ui.color.secondary.value + + d3.select(this).style("cursor","auto") + .transition().duration(vars.timing.mouseevents) + .style("background-color",color) + .style("color",textColor(color)) + + }) + .on(events.click,function(d){ + vars.history.back() + }) + + vars.container.title.exit().remove() + + if ( enabled ) { + vars.margin.title += vars.container.title.node().offsetHeight || vars.container.title.node().getBoundingClientRect().height + } + + if ( vars.dev.value ) print.timeEnd("creating title and back button") + + } + +} + +},{"../../../../client/pointer.coffee":38,"../../../../color/lighter.coffee":45,"../../../../color/text.coffee":50,"../../../../core/console/print.coffee":52}],156:[function(require,module,exports){ +var items = require("./items.coffee"), + height = require("./height.js"), + print = require("../../../../core/console/print.coffee"), + scrolllist = require("./scroll.js"), + arrow = require("./arrow.js") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Redraws only the drop down list. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If the menu is open, set the container element's z-index to '9999'. + //---------------------------------------------------------------------------- + if ( vars.draw.timing ) { + + vars.container.ui.transition().duration(vars.draw.timing) + .each("start",function(){ + if (vars.open.value) { + d3.select(this).style("z-index",9999) + } + }) + .style("margin",vars.ui.margin.css) + .each("end",function(){ + if (!vars.open.value) { + d3.select(this).style("z-index","auto") + } + }) + + } + else { + + vars.container.ui + .style("margin",vars.ui.margin.css) + .style("z-index",function(){ + if (vars.open.value) { + return 9999 + } + else { + return "auto" + } + }) + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Update list items based on filtered data. + //---------------------------------------------------------------------------- + items( vars ) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Calculate the height and orientation of the dropdown list. + //---------------------------------------------------------------------------- + height( vars ) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Calculate scroll position of dropdown menu. + //---------------------------------------------------------------------------- + scrolllist( vars ) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Rotate the dropdown button arrow appropriately. + //---------------------------------------------------------------------------- + arrow( vars ) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Update List + //---------------------------------------------------------------------------- + if ( vars.dev.value ) print.time("drawing list") + + function position(elem) { + var flipped = vars.open.flipped.value + elem + .style("top",function(){ + return flipped ? "auto" : vars.margin.top-vars.ui.border+"px"; + }) + .style("bottom",function(){ + return flipped ? vars.margin.top+vars.ui.border+"px" : "auto"; + }); + } + + function update(elem) { + + elem + .style("left",function(){ + if (vars.font.align.value === "left") { + return vars.margin.left+"px"; + } + else if (vars.font.align.value === "center") { + return vars.margin.left-((vars.width.secondary-vars.width.value)/2)+"px"; + } + else { + return "auto"; + } + }) + .style("right",function(){ + return vars.font.align.value === "right" ? "0px" : "auto"; + }) + .style("height",vars.container.listHeight+"px") + .style("padding",vars.ui.border+"px") + .style("background-color",vars.ui.color.secondary.value) + .style("z-index",function(){ + return vars.open.value ? "9999" : "-1"; + }) + .style("width",(vars.width.secondary-(vars.ui.border*2))+"px") + .style("opacity",vars.open.value ? 1 : 0) + .call(position); + + } + + function finish(elem) { + + elem.style("display", vars.open.value ? null : "none") + .call(position); + + + if (vars.search.enabled && vars.open.value) { + vars.container.selector.select("div.d3plus_drop_search input").node().focus() + } + + } + + var max_height = vars.open.value ? vars.height.secondary - vars.margin.title: 0; + + if (!vars.draw.timing) { + + vars.container.selector.call(update).call(finish) + + vars.container.list + .style("width",vars.width.secondary-vars.ui.border*2+"px") + .style("max-height", max_height + "px") + .property("scrollTop",vars.container.listScroll); + + } + else { + vars.container.selector.transition().duration(vars.draw.timing) + .each("start",function(){ + d3.select(this) + .style("display",vars.open.value ? "block" : null) + }) + .call(update) + .each("end",function(){ + + d3.select(this).transition().duration(vars.draw.timing) + .call(finish) + + }) + + function scrollTopTween(scrollTop) { + return function() { + var i = d3.interpolateNumber(this.scrollTop, scrollTop); + return function(t) { this.scrollTop = i(t); }; + }; + } + + vars.container.list.transition().duration(vars.draw.timing) + .style("width",vars.width.secondary-vars.ui.border*2+"px") + .style("max-height",max_height+"px") + .tween("scroll",scrollTopTween(vars.container.listScroll)) + } + + if ( vars.dev.value ) print.timeEnd("drawing list") + +} + +},{"../../../../core/console/print.coffee":52,"./arrow.js":144,"./height.js":148,"./items.coffee":149,"./scroll.js":152}],157:[function(require,module,exports){ +var copy = require("../../../../util/copy.coffee"), + fontTester = require("../../../../core/font/tester.coffee"), + form = require("../../../form.js"), + print = require("../../../../core/console/print.coffee"), + validObject = require("../../../../object/validate.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// If no widths are defined, then this calculates the width needed to fit the +// longest entry in the list. +//------------------------------------------------------------------------------ +module.exports = function ( vars ) { + + var data = [], buffer = 0 + for ( var level in vars.data.nested.all ) { + var newData = vars.data.nested.all[level] + , key = validObject(vars.text.nesting) && level in vars.text.nesting + ? vars.text.nesting[level][0] : level + + if ( [vars.id.value,vars.text.value].indexOf(key) < 0 ) { + newData = copy(newData) + newData.forEach(function(d){ + d[vars.text.value || vars.id.value] = d[key] + }) + } + data = data.concat( newData ) + } + + function getWidth( type ) { + + var key = type === "primary" ? "value" : type + , icon = key === "value" ? vars.icon.drop.value + : vars.icon.select.value || vars.icon.drop.value + , text = key === "value" ? vars.text.value + : vars.text.secondary.value || vars.text.value + , font = key === "value" ? vars.font : vars.font.secondary + + if ( vars.dev.value ) print.time("calculating "+type+" width") + + var button = form() + .container( fontTester() ) + .data({ + "large": 9999, + "value": data + }) + .draw({ "update": false }) + .font( font ) + .format(vars.format) + .icon({ "button": icon, "value": vars.icon.value }) + .id(vars.id.value) + .timing({ + "ui": 0 + }) + .text( text || vars.id.value ) + .type( "button" ) + .ui({ + "border": type === "primary" ? vars.ui.border : 0, + "display": "inline-block", + "margin": 0, + "padding": vars.ui.padding.css + }) + .width(false) + .draw() + + var w = [] + button.selectAll("div.d3plus_node").each(function(o){ + w.push(this.offsetWidth + 1) + }).remove() + + var dropWidth = {} + dropWidth[key] = d3.max(w) + + vars.self.width( dropWidth ) + + if ( vars.dev.value ) print.timeEnd("calculating "+type+" width") + + } + + if ( typeof vars.width.value !== "number" ) { + + getWidth( "primary" ) + + } + + if ( typeof vars.width.secondary !== "number" ) { + + if ( !vars.text.secondary.value || vars.text.value === vars.text.secondary.value ) { + vars.self.width({"secondary": vars.width.value}) + } + else { + getWidth( "secondary" ) + } + + } + +} + +},{"../../../../core/console/print.coffee":52,"../../../../core/font/tester.coffee":68,"../../../../object/validate.coffee":172,"../../../../util/copy.coffee":207,"../../../form.js":104}],158:[function(require,module,exports){ +var child = require("../../../../util/child.coffee") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Recursive function that applies a click event to all parent windows that +// will close the dropdown if it is open. +//------------------------------------------------------------------------------ +var windowEvents = function ( vars , elem ) { + + if ( elem === undefined ) { + var elem = window + } + + d3.select(elem).on("click."+vars.container.id,function(){ + + var element = d3.event.target || d3.event.toElement + , parent = element.parentNode + + if ( parent && ["d3plus_node","d3plus_drop_title"].indexOf(parent.className) >= 0 ) { + element = parent.parentNode + } + + if (element && parent && !child(vars.container.ui, element) && (vars.open.value || vars.hover.value)) { + vars.self.open(false).hover(false).draw() + } + + }) + + try { + var same_origin = window.parent.location.host === window.location.host; + } + catch (e) { + var same_origin = false + } + + if (same_origin) { + if (elem.self !== window.top) { + windowEvents( vars , elem.parent ) + } + } + +} + +module.exports = windowEvents + +},{"../../../../util/child.coffee":205}],159:[function(require,module,exports){ +var form = require("../form.js") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates a set of Toggle Buttons +//------------------------------------------------------------------------------ +module.exports = function( vars ) { + + if ( !("buttons" in vars.container) ) { + + vars.container.buttons = form() + .container(vars.container.ui) + .type("button") + + } + + var dataLength = vars.data.viz.length + , buttonWidth = vars.width.value + ? vars.width.value/dataLength + : false + + var toggles = vars.container.ui.selectAll("div.d3plus_toggle") + .data(vars.data.viz,function(d){ + return d[vars.id.value]; + }) + + toggles.exit().remove(); + + toggles.enter().append("div") + .attr("class","d3plus_toggle") + .style("display","inline-block") + .style("vertical-align","top") + + toggles.order() + .each(function(d){ + + if (!("form" in d.d3plus)) { + d.d3plus.form = form().container(d3.select(this)) + } + + var id = vars.id.nesting.length > vars.depth.value ? vars.id.nesting[vars.depth.value+1] : vars.id.value + + if (d[id] instanceof Array) { + d.d3plus.form + .container({"id": vars.container.id+"_"+d[vars.id.value]}) + .data(d[id]) + .id(vars.id.nesting.slice(1)) + .type("drop") + } + else { + d.d3plus.form + .data([d]) + .id(vars.id.value) + .type("button") + } + + d.d3plus.form + .color(vars.color) + .focus(vars.focus.value,function(value){ + + if (value !== vars.focus.value) { + vars.self.focus(value).draw() + } + + }) + .hover(vars.hover.value) + .icon({ + "select": false, + "value": vars.icon.value + }) + .font(vars.font) + .format(vars.format) + .order(vars.order) + .text(vars.text.value) + .ui({ + "border": vars.ui.border, + "color": vars.ui.color, + "display": "inline-block", + "margin": 0, + "padding": vars.ui.padding.css + }) + .width(buttonWidth) + .draw() + + }) + + if (vars.data.element.value) { + vars.data.element.value + .on("focus."+vars.container.id, function(){ + vars.self.focus(this.value).hover(this.value).draw(); + }) + .on("blur."+vars.container.id, function(){ + vars.self.hover(false).draw(); + }) + } + +} + +},{"../form.js":104}],160:[function(require,module,exports){ +var intersectPoints, lineIntersection, pointInPoly, pointInSegmentBox, polyInsidePoly, rayIntersectsSegment, rotatePoint, rotatePoly, segmentsIntersect, simplify, squaredDist; + +simplify = require("simplify-js"); + +module.exports = function(poly, options) { + var aRatio, aRatios, angle, angleRad, angleStep, angles, area, aspectRatioStep, aspectRatios, bBox, boxHeight, boxWidth, centroid, events, height, i, insidePoly, j, k, l, left, len, len1, len2, len3, m, maxArea, maxAspectRatio, maxHeight, maxRect, maxWidth, maxx, maxy, minAspectRatio, minSqDistH, minSqDistW, minx, miny, modifOrigins, origOrigin, origin, origins, p, p1H, p1W, p2H, p2W, rectPoly, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, right, rndPoint, rndX, rndY, tempPoly, tolerance, width, widthStep, x0, y0; + if (poly.length < 3) { + return null; + } + events = []; + aspectRatioStep = 0.5; + angleStep = 5; + if (options == null) { + options = {}; + } + if (options.maxAspectRatio == null) { + options.maxAspectRatio = 15; + } + if (options.minWidth == null) { + options.minWidth = 0; + } + if (options.minHeight == null) { + options.minHeight = 0; + } + if (options.tolerance == null) { + options.tolerance = 0.02; + } + if (options.nTries == null) { + options.nTries = 20; + } + if (options.angle != null) { + if (options.angle instanceof Array) { + angles = options.angle; + } else if (typeof options.angle === 'number') { + angles = [options.angle]; + } else if (typeof options.angle === 'string' && !isNaN(options.angle)) { + angles = [Number(options.angle)]; + } + } + if (angles == null) { + angles = d3.range(-90, 90 + angleStep, angleStep); + } + if (options.aspectRatio != null) { + if (options.aspectRatio instanceof Array) { + aspectRatios = options.aspectRatio; + } else if (typeof options.aspectRatio === 'number') { + aspectRatios = [options.aspectRatio]; + } else if (typeof options.aspectRatio === 'string' && !isNaN(options.aspectRatio)) { + aspectRatios = [Number(options.aspectRatio)]; + } + } + if (options.origin != null) { + if (options.origin instanceof Array) { + if (options.origin[0] instanceof Array) { + origins = options.origin; + } else { + origins = [options.origin]; + } + } + } + area = Math.abs(d3.geom.polygon(poly).area()); + if (area === 0) { + return null; + } + ref = d3.extent(poly, function(d) { + return d[0]; + }), minx = ref[0], maxx = ref[1]; + ref1 = d3.extent(poly, function(d) { + return d[1]; + }), miny = ref1[0], maxy = ref1[1]; + tolerance = Math.min(maxx - minx, maxy - miny) * options.tolerance; + tempPoly = (function() { + var j, len, results; + results = []; + for (j = 0, len = poly.length; j < len; j++) { + p = poly[j]; + results.push({ + x: p[0], + y: p[1] + }); + } + return results; + })(); + if (tolerance > 0) { + tempPoly = simplify(tempPoly, tolerance); + poly = (function() { + var j, len, results; + results = []; + for (j = 0, len = tempPoly.length; j < len; j++) { + p = tempPoly[j]; + results.push([p.x, p.y]); + } + return results; + })(); + } + if (options.vdebug) { + events.push({ + type: 'simplify', + poly: poly + }); + } + ref2 = d3.extent(poly, function(d) { + return d[0]; + }), minx = ref2[0], maxx = ref2[1]; + ref3 = d3.extent(poly, function(d) { + return d[1]; + }), miny = ref3[0], maxy = ref3[1]; + bBox = [[minx, miny], [maxx, miny], [maxx, maxy], [minx, maxy]]; + ref4 = [maxx - minx, maxy - miny], boxWidth = ref4[0], boxHeight = ref4[1]; + widthStep = Math.min(boxWidth, boxHeight) / 50; + if (origins == null) { + origins = []; + centroid = d3.geom.polygon(poly).centroid(); + if (pointInPoly(centroid, poly)) { + origins.push(centroid); + } + while (origins.length < options.nTries) { + rndX = Math.random() * boxWidth + minx; + rndY = Math.random() * boxHeight + miny; + rndPoint = [rndX, rndY]; + if (pointInPoly(rndPoint, poly)) { + origins.push(rndPoint); + } + } + } + if (options.vdebug) { + events.push({ + type: 'origins', + points: origins + }); + } + maxArea = 0; + maxRect = null; + for (j = 0, len = angles.length; j < len; j++) { + angle = angles[j]; + angleRad = -angle * Math.PI / 180; + if (options.vdebug) { + events.push({ + type: 'angle', + angle: angle + }); + } + for (i = k = 0, len1 = origins.length; k < len1; i = ++k) { + origOrigin = origins[i]; + ref5 = intersectPoints(poly, origOrigin, angleRad), p1W = ref5[0], p2W = ref5[1]; + ref6 = intersectPoints(poly, origOrigin, angleRad + Math.PI / 2), p1H = ref6[0], p2H = ref6[1]; + modifOrigins = []; + if ((p1W != null) && (p2W != null)) { + modifOrigins.push([(p1W[0] + p2W[0]) / 2, (p1W[1] + p2W[1]) / 2]); + } + if ((p1H != null) && (p2H != null)) { + modifOrigins.push([(p1H[0] + p2H[0]) / 2, (p1H[1] + p2H[1]) / 2]); + } + if (options.vdebug) { + events.push({ + type: 'modifOrigin', + idx: i, + p1W: p1W, + p2W: p2W, + p1H: p1H, + p2H: p2H, + modifOrigins: modifOrigins + }); + } + for (l = 0, len2 = modifOrigins.length; l < len2; l++) { + origin = modifOrigins[l]; + if (options.vdebug) { + events.push({ + type: 'origin', + cx: origin[0], + cy: origin[1] + }); + } + ref7 = intersectPoints(poly, origin, angleRad), p1W = ref7[0], p2W = ref7[1]; + if (p1W === null || p2W === null) { + continue; + } + minSqDistW = Math.min(squaredDist(origin, p1W), squaredDist(origin, p2W)); + maxWidth = 2 * Math.sqrt(minSqDistW); + ref8 = intersectPoints(poly, origin, angleRad + Math.PI / 2), p1H = ref8[0], p2H = ref8[1]; + if (p1H === null || p2H === null) { + continue; + } + minSqDistH = Math.min(squaredDist(origin, p1H), squaredDist(origin, p2H)); + maxHeight = 2 * Math.sqrt(minSqDistH); + if (maxWidth * maxHeight < maxArea) { + continue; + } + if (aspectRatios != null) { + aRatios = aspectRatios; + } else { + minAspectRatio = Math.max(1, options.minWidth / maxHeight, maxArea / (maxHeight * maxHeight)); + maxAspectRatio = Math.min(options.maxAspectRatio, maxWidth / options.minHeight, (maxWidth * maxWidth) / maxArea); + aRatios = d3.range(minAspectRatio, maxAspectRatio + aspectRatioStep, aspectRatioStep); + } + for (m = 0, len3 = aRatios.length; m < len3; m++) { + aRatio = aRatios[m]; + left = Math.max(options.minWidth, Math.sqrt(maxArea * aRatio)); + right = Math.min(maxWidth, maxHeight * aRatio); + if (right * maxHeight < maxArea) { + continue; + } + if ((right - left) >= widthStep) { + if (options.vdebug) { + events.push({ + type: 'aRatio', + aRatio: aRatio + }); + } + } + while ((right - left) >= widthStep) { + width = (left + right) / 2; + height = width / aRatio; + x0 = origin[0], y0 = origin[1]; + rectPoly = [[x0 - width / 2, y0 - height / 2], [x0 + width / 2, y0 - height / 2], [x0 + width / 2, y0 + height / 2], [x0 - width / 2, y0 + height / 2]]; + rectPoly = rotatePoly(rectPoly, angleRad, origin); + if (polyInsidePoly(rectPoly, poly)) { + insidePoly = true; + maxArea = width * height; + maxRect = { + cx: x0, + cy: y0, + width: width, + height: height, + angle: angle + }; + left = width; + } else { + insidePoly = false; + right = width; + } + if (options.vdebug) { + events.push({ + type: 'rectangle', + cx: x0, + cy: y0, + width: width, + height: height, + areaFraction: (width * height) / area, + angle: angle, + insidePoly: insidePoly + }); + } + } + } + } + } + } + return [maxRect, maxArea, events]; +}; + +squaredDist = function(a, b) { + var deltax, deltay; + deltax = b[0] - a[0]; + deltay = b[1] - a[1]; + return deltax * deltax + deltay * deltay; +}; + +rayIntersectsSegment = function(p, p1, p2) { + var a, b, mAB, mAP, ref; + ref = p1[1] < p2[1] ? [p1, p2] : [p2, p1], a = ref[0], b = ref[1]; + if (p[1] === b[1] || p[1] === a[1]) { + p[1] += Number.MIN_VALUE; + } + if (p[1] > b[1] || p[1] < a[1]) { + return false; + } else if (p[0] > a[0] && p[0] > b[0]) { + return false; + } else if (p[0] < a[0] && p[0] < b[0]) { + return true; + } else { + mAB = (b[1] - a[1]) / (b[0] - a[0]); + mAP = (p[1] - a[1]) / (p[0] - a[0]); + return mAP > mAB; + } +}; + +pointInPoly = function(p, poly) { + var a, b, c, i, n; + i = -1; + n = poly.length; + b = poly[n - 1]; + c = 0; + while (++i < n) { + a = b; + b = poly[i]; + if (rayIntersectsSegment(p, a, b)) { + c++; + } + } + return c % 2 !== 0; +}; + +pointInSegmentBox = function(p, p1, q1) { + var eps, px, py; + eps = 1e-9; + px = p[0], py = p[1]; + if (px < Math.min(p1[0], q1[0]) - eps || px > Math.max(p1[0], q1[0]) + eps || py < Math.min(p1[1], q1[1]) - eps || py > Math.max(p1[1], q1[1]) + eps) { + return false; + } + return true; +}; + +lineIntersection = function(p1, q1, p2, q2) { + var cross1, cross2, denom, dx1, dx2, dy1, dy2, eps, px, py; + eps = 1e-9; + dx1 = p1[0] - q1[0]; + dy1 = p1[1] - q1[1]; + dx2 = p2[0] - q2[0]; + dy2 = p2[1] - q2[1]; + denom = dx1 * dy2 - dy1 * dx2; + if (Math.abs(denom) < eps) { + return null; + } + cross1 = p1[0] * q1[1] - p1[1] * q1[0]; + cross2 = p2[0] * q2[1] - p2[1] * q2[0]; + px = (cross1 * dx2 - cross2 * dx1) / denom; + py = (cross1 * dy2 - cross2 * dy1) / denom; + return [px, py]; +}; + +segmentsIntersect = function(p1, q1, p2, q2) { + var p; + p = lineIntersection(p1, q1, p2, q2); + if (p == null) { + return false; + } + return pointInSegmentBox(p, p1, q1) && pointInSegmentBox(p, p2, q2); +}; + +polyInsidePoly = function(polyA, polyB) { + var aA, aB, bA, bB, iA, iB, nA, nB; + iA = -1; + nA = polyA.length; + nB = polyB.length; + bA = polyA[nA - 1]; + while (++iA < nA) { + aA = bA; + bA = polyA[iA]; + iB = -1; + bB = polyB[nB - 1]; + while (++iB < nB) { + aB = bB; + bB = polyB[iB]; + if (segmentsIntersect(aA, bA, aB, bB)) { + return false; + } + } + } + return pointInPoly(polyA[0], polyB); +}; + +rotatePoint = function(p, alpha, origin) { + var cosAlpha, sinAlpha, xshifted, yshifted; + if (origin == null) { + origin = [0, 0]; + } + xshifted = p[0] - origin[0]; + yshifted = p[1] - origin[1]; + cosAlpha = Math.cos(alpha); + sinAlpha = Math.sin(alpha); + return [cosAlpha * xshifted - sinAlpha * yshifted + origin[0], sinAlpha * xshifted + cosAlpha * yshifted + origin[1]]; +}; + +rotatePoly = function(poly, alpha, origin) { + var j, len, point, results; + results = []; + for (j = 0, len = poly.length; j < len; j++) { + point = poly[j]; + results.push(rotatePoint(point, alpha, origin)); + } + return results; +}; + +intersectPoints = function(poly, origin, alpha) { + var a, b, closestPointLeft, closestPointRight, eps, i, idx, minSqDistLeft, minSqDistRight, n, p, shiftedOrigin, sqDist, x0, y0; + eps = 1e-9; + origin = [origin[0] + eps * Math.cos(alpha), origin[1] + eps * Math.sin(alpha)]; + x0 = origin[0], y0 = origin[1]; + shiftedOrigin = [x0 + Math.cos(alpha), y0 + Math.sin(alpha)]; + idx = 0; + if (Math.abs(shiftedOrigin[0] - x0) < eps) { + idx = 1; + } + i = -1; + n = poly.length; + b = poly[n - 1]; + minSqDistLeft = Number.MAX_VALUE; + minSqDistRight = Number.MAX_VALUE; + closestPointLeft = null; + closestPointRight = null; + while (++i < n) { + a = b; + b = poly[i]; + p = lineIntersection(origin, shiftedOrigin, a, b); + if ((p != null) && pointInSegmentBox(p, a, b)) { + sqDist = squaredDist(origin, p); + if (p[idx] < origin[idx]) { + if (sqDist < minSqDistLeft) { + minSqDistLeft = sqDist; + closestPointLeft = p; + } + } else if (p[idx] > origin[idx]) { + if (sqDist < minSqDistRight) { + minSqDistRight = sqDist; + closestPointRight = p; + } + } + } + } + return [closestPointLeft, closestPointRight]; +}; + + +},{"simplify-js":8}],161:[function(require,module,exports){ +module.exports = function(radians, distance, shape) { + var adjacentLegLength, coords, diagonal, oppositeLegLength; + coords = { + x: 0, + y: 0 + }; + if (radians < 0) { + radians = Math.PI * 2 + radians; + } + if (shape === "square") { + diagonal = 45 * (Math.PI / 180); + if (radians <= Math.PI) { + if (radians < (Math.PI / 2)) { + if (radians < diagonal) { + coords.x += distance; + oppositeLegLength = Math.tan(radians) * distance; + coords.y += oppositeLegLength; + } else { + coords.y += distance; + adjacentLegLength = distance / Math.tan(radians); + coords.x += adjacentLegLength; + } + } else { + if (radians < (Math.PI - diagonal)) { + coords.y += distance; + adjacentLegLength = distance / Math.tan(Math.PI - radians); + coords.x -= adjacentLegLength; + } else { + coords.x -= distance; + oppositeLegLength = Math.tan(Math.PI - radians) * distance; + coords.y += oppositeLegLength; + } + } + } else { + if (radians < (3 * Math.PI / 2)) { + if (radians < (diagonal + Math.PI)) { + coords.x -= distance; + oppositeLegLength = Math.tan(radians - Math.PI) * distance; + coords.y -= oppositeLegLength; + } else { + coords.y -= distance; + adjacentLegLength = distance / Math.tan(radians - Math.PI); + coords.x -= adjacentLegLength; + } + } else { + if (radians < (2 * Math.PI - diagonal)) { + coords.y -= distance; + adjacentLegLength = distance / Math.tan(2 * Math.PI - radians); + coords.x += adjacentLegLength; + } else { + coords.x += distance; + oppositeLegLength = Math.tan(2 * Math.PI - radians) * distance; + coords.y -= oppositeLegLength; + } + } + } + } else { + coords.x += distance * Math.cos(radians); + coords.y += distance * Math.sin(radians); + } + return coords; +}; + + +},{}],162:[function(require,module,exports){ +var offset; + +offset = require("../geom/offset.coffee"); + +module.exports = function(path) { + var angle, i, j, last, len, length, o, obtuse, p, poly, prev, radius, segments, start, step, width; + if (!path) { + return []; + } + path = path.slice(1).slice(0, -1).split(/L|A/); + poly = []; + for (j = 0, len = path.length; j < len; j++) { + p = path[j]; + p = p.split(" "); + if (p.length === 1) { + poly.push(p[0].split(",").map(function(d) { + return parseFloat(d); + })); + } else { + prev = poly[poly.length - 1]; + last = p.pop().split(",").map(function(d) { + return parseFloat(d); + }); + radius = parseFloat(p.shift().split(",")[0]); + width = Math.sqrt(Math.pow(last[0] - prev[0], 2) + Math.pow(last[1] - prev[1], 2)); + angle = Math.acos((radius * radius + radius * radius - width * width) / (2 * radius * radius)); + obtuse = p[1].split(",")[0] === "1"; + if (obtuse) { + angle = Math.PI * 2 - angle; + } + length = angle / (Math.PI * 2) * (radius * Math.PI * 2); + segments = length / 5; + start = Math.atan2(-prev[1], -prev[0]) - Math.PI; + step = angle / segments; + i = step; + while (i < angle) { + o = offset(start + i, radius); + poly.push([o.x, o.y]); + i += step; + } + poly.push(last); + } + } + return poly; +}; + + +},{"../geom/offset.coffee":161}],163:[function(require,module,exports){ + +/** + * @class d3plus + */ +var d3plus, message, stylesheet; + +d3plus = {}; + + +/** + * The current version of **D3plus** you are using. Returns a string in + * [semantic versioning](http://semver.org/) format. + * @property d3plus.version + * @for d3plus + * @type String + * @static + */ + +d3plus.version = "1.9.8 - Cornflower"; + + +/** + * The URL for the repo, used internally for certain error messages. + * @property d3plus.repo + * @for d3plus + * @type String + * @static + */ + +d3plus.repo = "https://github.com/alexandersimoes/d3plus/"; + + +/** + * Utilities related to modifying arrays. + * @class d3plus.array + * @for d3plus + * @static + */ + +d3plus.array = { + comparator: require("./array/comparator.coffee"), + contains: require("./array/contains.coffee"), + sort: require("./array/sort.coffee"), + update: require("./array/update.coffee") +}; + + +/** + * Utilities related to the client's browser. + * @class d3plus.client + * @for d3plus + * @static + */ + +d3plus.client = { + css: require("./client/css.coffee"), + ie: require("./client/ie.js"), + pointer: require("./client/pointer.coffee"), + prefix: require("./client/prefix.coffee"), + rtl: require("./client/rtl.coffee"), + scroll: require("./client/scroll.js"), + scrollbar: require("./client/scrollbar.coffee"), + touch: require("./client/touch.coffee") +}; + + +/** + * Utilities related to color manipulation. + * @class d3plus.color + * @for d3plus + * @static + */ + +d3plus.color = { + legible: require("./color/legible.coffee"), + lighter: require("./color/lighter.coffee"), + mix: require("./color/mix.coffee"), + random: require("./color/random.coffee"), + scale: require("./color/scale.coffee"), + sort: require("./color/sort.coffee"), + text: require("./color/text.coffee"), + validate: require("./color/validate.coffee") +}; + + +/** + * Utilities related to manipulating data. + * @class d3plus.data + * @for d3plus + * @static + */ + +d3plus.data = { + bestRegress: require("./data/bestRegress.coffee"), + lof: require("./data/lof.coffee"), + mad: require("./data/mad.coffee") +}; + + +/** + * Utilities related to fonts. + * @class d3plus.font + * @for d3plus + * @static + */ + +d3plus.font = { + sizes: require("./font/sizes.coffee"), + validate: require("./font/validate.coffee") +}; + + +/** + * D3plus Forms + * @class d3plus.form + * @for d3plus + */ + +d3plus.form = require("./form/form.js"); + + +/** + * Utilities related to geometric algorithms. + * @class d3plus.geom + * @for d3plus + * @static + */ + +d3plus.geom = { + largestRect: require("./geom/largestRect.coffee"), + offset: require("./geom/offset.coffee"), + path2poly: require("./geom/path2poly.coffee") +}; + + +/** + * Utilities related to network graphs. + * @class d3plus.network + * @for d3plus + * @static + */ + +d3plus.network = { + cluster: require("./network/cluster.coffee"), + distance: require("./network/distance.coffee"), + normalize: require("./network/normalize.coffee"), + shortestPath: require("./network/shortestPath.coffee"), + smallestGap: require("./network/smallestGap.coffee"), + subgraph: require("./network/subgraph.coffee") +}; + + +/** + * Utilities that process numbers. + * @class d3plus.number + * @for d3plus + * @static + */ + +d3plus.number = { + format: require("./number/format.coffee") +}; + + +/** + * D3plus features a set of methods that relate to various object properties. These methods may be used outside of the normal constraints of the visualizations. + * @class d3plus.object + * @for d3plus + * @static + */ + +d3plus.object = { + merge: require("./object/merge.coffee"), + validate: require("./object/validate.coffee") +}; + + +/** + * Utilities that process strings. + * @class d3plus.string + * @for d3plus + * @static + */ + +d3plus.string = { + format: require("./string/format.js"), + list: require("./string/list.coffee"), + strip: require("./string/strip.js"), + title: require("./string/title.coffee") +}; + + +/** + * D3plus SVG Textwrapping + * @class d3plus.textwrap + * @for d3plus + */ + +d3plus.textwrap = require("./textwrap/textwrap.coffee"); + + +/** + * D3plus Tooltips + * @class d3plus.tooltip + * @for d3plus + */ + +d3plus.tooltip = { + create: require("./tooltip/create.js"), + move: require("./tooltip/move.coffee"), + remove: require("./tooltip/remove.coffee") +}; + + +/** + * D3plus features Utilities that can be used to help with some common javascript processes. + * @class d3plus.util + * @for d3plus + * @static + */ + +d3plus.util = { + buckets: require("./util/buckets.coffee"), + child: require("./util/child.coffee"), + closest: require("./util/closest.coffee"), + copy: require("./util/copy.coffee"), + d3selection: require("./util/d3selection.coffee"), + dataurl: require("./util/dataURL.coffee"), + uniques: require("./util/uniques.coffee") +}; + + +/** + * D3plus Visualizations + * @class d3plus.viz + * @for d3plus + */ + +d3plus.viz = require("./viz/viz.coffee"); + +stylesheet = require("./client/css.coffee"); + +message = require("./core/console/print.coffee"); + +if (stylesheet("d3plus.css")) { + message.warning("d3plus.css has been deprecated, you do not need to load this file.", d3plus.repo + "releases/tag/v1.4.0"); +} + +if (typeof window !== "undefined") { + window.d3plus = d3plus; +} + +module.exports = d3plus; + + +},{"./array/comparator.coffee":32,"./array/contains.coffee":33,"./array/sort.coffee":34,"./array/update.coffee":35,"./client/css.coffee":36,"./client/ie.js":37,"./client/pointer.coffee":38,"./client/prefix.coffee":39,"./client/rtl.coffee":40,"./client/scroll.js":41,"./client/scrollbar.coffee":42,"./client/touch.coffee":43,"./color/legible.coffee":44,"./color/lighter.coffee":45,"./color/mix.coffee":46,"./color/random.coffee":47,"./color/scale.coffee":48,"./color/sort.coffee":49,"./color/text.coffee":50,"./color/validate.coffee":51,"./core/console/print.coffee":52,"./data/bestRegress.coffee":99,"./data/lof.coffee":100,"./data/mad.coffee":101,"./font/sizes.coffee":102,"./font/validate.coffee":103,"./form/form.js":104,"./geom/largestRect.coffee":160,"./geom/offset.coffee":161,"./geom/path2poly.coffee":162,"./network/cluster.coffee":164,"./network/distance.coffee":165,"./network/normalize.coffee":166,"./network/shortestPath.coffee":167,"./network/smallestGap.coffee":168,"./network/subgraph.coffee":169,"./number/format.coffee":170,"./object/merge.coffee":171,"./object/validate.coffee":172,"./string/format.js":173,"./string/list.coffee":174,"./string/strip.js":175,"./string/title.coffee":176,"./textwrap/textwrap.coffee":200,"./tooltip/create.js":201,"./tooltip/move.coffee":202,"./tooltip/remove.coffee":203,"./util/buckets.coffee":204,"./util/child.coffee":205,"./util/closest.coffee":206,"./util/copy.coffee":207,"./util/d3selection.coffee":208,"./util/dataURL.coffee":209,"./util/uniques.coffee":210,"./viz/viz.coffee":333}],164:[function(require,module,exports){ +var normalize; + +normalize = require("./normalize.coffee"); + +module.exports = function(edges, options) { + var Q, a, b, cid, commSize, commSizes, communities, community, deltaQ, distance, edge, endpoint, events, i, id, iter, j, k, len, len1, linksMap, m, maxa, maxb, node, nodeid, nodes, nodesMap, ref, ref1, result, startpoint; + events = []; + if (options == null) { + options = {}; + } + if ((options.nodes == null) || typeof options.nodes !== 'object') { + ref = normalize(edges, options), edges = ref[0], options = ref[1]; + if (options === null) { + return null; + } + } + distance = options.distance, nodeid = options.nodeid, startpoint = options.startpoint, endpoint = options.endpoint, nodes = options.nodes; + nodesMap = {}; + for (id in nodes) { + nodesMap[id] = { + node: nodes[id].node, + degree: 0 + }; + } + m = 0; + linksMap = {}; + for (i = 0, len = edges.length; i < len; i++) { + edge = edges[i]; + a = nodeid(startpoint(edge)); + b = nodeid(endpoint(edge)); + if (!(a in linksMap)) { + linksMap[a] = {}; + } + if (!(b in linksMap)) { + linksMap[b] = {}; + } + if (!(b in linksMap[a])) { + linksMap[a][b] = 0; + linksMap[b][a] = 0; + m++; + nodesMap[a].degree += 1; + nodesMap[b].degree += 1; + } + } + communities = {}; + Q = 0; + for (id in nodesMap) { + node = nodesMap[id]; + communities[id] = { + score: node.degree / (2.0 * m), + nodes: [id] + }; + } + for (a in linksMap) { + for (b in linksMap[a]) { + linksMap[a][b] = 1.0 / (2 * m) - (nodesMap[a].degree * nodesMap[b].degree) / (4.0 * m * m); + } + } + iter = 0; + while (iter < 1000) { + deltaQ = -1; + maxa = void 0; + maxb = void 0; + for (a in linksMap) { + for (b in linksMap[a]) { + if (linksMap[a][b] > deltaQ) { + deltaQ = linksMap[a][b]; + maxa = a; + maxb = b; + } + } + } + if (deltaQ < 0) { + break; + } + for (k in linksMap[maxa]) { + if (k !== maxb) { + if (k in linksMap[maxb]) { + linksMap[maxb][k] += linksMap[maxa][k]; + } else { + linksMap[maxb][k] = linksMap[maxa][k] - 2 * communities[maxb].score * communities[k].score; + } + linksMap[k][maxb] = linksMap[maxb][k]; + } + delete linksMap[k][maxa]; + } + for (k in linksMap[maxb]) { + if (!(k in linksMap[maxa]) && k !== maxb) { + linksMap[maxb][k] -= 2 * communities[maxa].score * communities[k].score; + linksMap[k][maxb] = linksMap[maxb][k]; + } + } + ref1 = communities[maxa].nodes; + for (j = 0, len1 = ref1.length; j < len1; j++) { + node = ref1[j]; + communities[maxb].nodes.push(node); + } + communities[maxb].score += communities[maxa].score; + if (options.vdebug) { + events.push({ + type: 'merge', + father: maxb, + child: maxa, + nodes: communities[maxb].nodes + }); + } + delete communities[maxa]; + delete linksMap[maxa]; + Q += deltaQ; + iter++; + } + commSizes = (function() { + var results; + results = []; + for (cid in communities) { + community = communities[cid]; + results.push([cid, community.nodes.length]); + } + return results; + })(); + commSizes.sort(function(a, b) { + return b[1] - a[1]; + }); + result = (function() { + var l, len2, results; + results = []; + for (l = 0, len2 = commSizes.length; l < len2; l++) { + commSize = commSizes[l]; + results.push(communities[commSize[0]].nodes); + } + return results; + })(); + return [result, events]; +}; + + +},{"./normalize.coffee":166}],165:[function(require,module,exports){ +module.exports = function(n1, n2) { + var xx, yy; + if (!(n1 instanceof Array)) { + n1 = [n1.x, n1.y]; + } + if (!(n2 instanceof Array)) { + n2 = [n2.x, n2.y]; + } + xx = Math.abs(n1[0] - n2[0]); + yy = Math.abs(n1[1] - n2[1]); + return Math.sqrt((xx * xx) + (yy * yy)); +}; + + +},{}],166:[function(require,module,exports){ +var print; + +print = require("../core/console/print.coffee"); + +module.exports = function(edges, options) { + var K, a, b, directed, distance, edge, edge2distance, endpoint, errormsg, i, id, id1, idA, idB, j, k, l, len, len1, len2, node, nodeA, nodeB, nodeid, nodes, ref, ref1, source, startpoint, target, vdebug; + source = options.source, target = options.target, directed = options.directed, distance = options.distance, nodeid = options.nodeid, startpoint = options.startpoint, endpoint = options.endpoint, K = options.K, vdebug = options.vdebug; + if (!directed) { + directed = false; + } + if (K == null) { + K = 1; + } + if (nodeid == null) { + nodeid = function(node) { + return node; + }; + } else if (typeof nodeid === 'string') { + nodeid = (function(nodeid) { + return function(node) { + return node[nodeid]; + }; + })(nodeid); + } + if ((source != null) && typeof source === 'object') { + source = nodeid(source); + } + if ((target != null) && typeof target === 'object') { + target = nodeid(target); + } + if (startpoint == null) { + startpoint = function(edge) { + return edge.source; + }; + } else if (typeof startpoint === 'string') { + startpoint = (function(startpoint) { + return function(edge) { + return edge[startpoint]; + }; + })(startpoint); + } + if (endpoint == null) { + endpoint = function(edge) { + return edge.target; + }; + } else if (typeof endpoint === 'string') { + endpoint = (function(endpoint) { + return function(edge) { + return edge[endpoint]; + }; + })(endpoint); + } + if (distance == null) { + distance = function(edge) { + return 1; + }; + } else if (typeof distance === 'number') { + distance = (function(distance) { + return function(edge) { + return distance; + }; + })(distance); + } else if (typeof distance === 'string') { + distance = (function(distance) { + return function(edge) { + return edge[distance]; + }; + })(distance); + } else if (distance instanceof Array) { + edge2distance = {}; + for (i = j = 0, len = edges.length; j < len; i = ++j) { + edge = edges[i]; + a = nodeid(startpoint(edge)); + b = nodeid(endpoint(edge)); + edge2distance[a + '_' + b] = distance[i]; + } + distance = function(edge) { + a = nodeid(startpoint(edge)); + b = nodeid(endpoint(edge)); + return edge2distance[a + '_' + b]; + }; + } + nodes = {}; + for (k = 0, len1 = edges.length; k < len1; k++) { + edge = edges[k]; + nodeA = startpoint(edge); + nodeB = endpoint(edge); + idA = nodeid(nodeA); + idB = nodeid(nodeB); + ref = [nodeA, nodeB]; + for (l = 0, len2 = ref.length; l < len2; l++) { + node = ref[l]; + id = nodeid(node); + if (!(id in nodes)) { + nodes[id] = { + node: node, + outedges: [] + }; + } + } + nodes[idA].outedges.push(edge); + if (!directed) { + nodes[idB].outedges.push(edge); + } + } + errormsg = null; + if (edges.length === 0) { + errormsg = 'The length of edges is 0'; + } else if (K < 0) { + errormsg = 'K can not have negative value'; + } else if (distance(edges[0]) == null) { + errormsg = 'Check the distance function/attribute'; + } else if (startpoint(edges[0]) == null) { + errormsg = 'Check the startpoint function/attribute'; + } else if (endpoint(edges[0]) == null) { + errormsg = 'Check the endpoint function/attribute'; + } else { + id1 = nodeid(startpoint(edges[0])); + if ((id1 == null) || ((ref1 = typeof id1) !== 'string' && ref1 !== 'number')) { + errormsg = 'Check the nodeid function/attribute'; + } else if ((source != null) && !(source in nodes)) { + errormsg = 'The source is not in the graph'; + } else if ((target != null) && !(target in nodes)) { + errormsg = 'The target is not in the graph'; + } + } + if (errormsg != null) { + print.error(errormsg); + return null; + } + return [ + edges, { + source: source, + target: target, + directed: directed, + distance: distance, + nodeid: nodeid, + startpoint: startpoint, + endpoint: endpoint, + K: K, + nodes: nodes, + vdebug: vdebug + } + ]; +}; + + +},{"../core/console/print.coffee":52}],167:[function(require,module,exports){ +var Heap, normalize; + +Heap = require('heap'); + +normalize = require("./normalize.coffee"); + +module.exports = function(edges, source, options) { + var K, a, alt, b, directed, distance, edge, endpoint, getPath, heap, i, id, j, len, len1, maxsize, node, nodeid, nodes, path, ref, ref1, ref2, res, result, startpoint, target, u, visited; + if (options == null) { + options = {}; + } + options.source = source; + if ((options.nodes == null) || typeof options.nodes !== 'object') { + ref = normalize(edges, options), edges = ref[0], options = ref[1]; + if (options === null) { + return null; + } + } + source = options.source, target = options.target, directed = options.directed, distance = options.distance, nodeid = options.nodeid, startpoint = options.startpoint, endpoint = options.endpoint, K = options.K, nodes = options.nodes; + for (id in nodes) { + node = nodes[id]; + node.count = 0; + } + heap = new Heap(function(a, b) { + return a.distance - b.distance; + }); + visited = {}; + if (target == null) { + visited[source] = true; + } + heap.push({ + edge: null, + target: source, + distance: 0 + }); + maxsize = 0; + result = []; + while (!heap.empty()) { + maxsize = Math.max(maxsize, heap.size()); + path = heap.pop(); + u = path.target; + nodes[u].count++; + if (target == null) { + result.push(path); + } else if (u === target) { + result.push(path); + } + if (result.length === K) { + break; + } + if (nodes[u].count <= K) { + ref1 = nodes[u].outedges; + for (i = 0, len = ref1.length; i < len; i++) { + edge = ref1[i]; + a = nodeid(startpoint(edge)); + b = nodeid(endpoint(edge)); + if (!directed && b === u) { + ref2 = [b, a], a = ref2[0], b = ref2[1]; + } + if (target == null) { + if (visited[b]) { + continue; + } + visited[b] = true; + } + alt = path.distance + distance(edge); + heap.push({ + edge: edge, + previous: path, + target: b, + distance: alt + }); + } + } + } + getPath = function(path) { + edges = []; + while (path.edge != null) { + edges.push(path.edge); + path = path.previous; + } + return edges.reverse(); + }; + for (j = 0, len1 = result.length; j < len1; j++) { + res = result[j]; + if (target != null) { + delete res.target; + res.edges = getPath(res); + } + delete res.edge; + delete res.previous; + } + return result; +}; + + +},{"./normalize.coffee":166,"heap":3}],168:[function(require,module,exports){ +var distance; + +distance = require("./distance.coffee"); + +module.exports = function(arr, opts) { + var distances, quad; + if (!opts) { + opts = {}; + } + distances = []; + quad = d3.geom.quadtree().x(function(d) { + if (opts.accessor) { + return opts.accessor(d)[0]; + } else { + return d[0]; + } + }).y(function(d) { + if (opts.accessor) { + return opts.accessor(d)[1]; + } else { + return d[1]; + } + }); + quad(arr).visit(function(node) { + var i, j, len, len1, n1, n2, ref, ref1; + if (!node.leaf) { + ref = node.nodes; + for (i = 0, len = ref.length; i < len; i++) { + n1 = ref[i]; + if (n1 && n1.point) { + if (opts.origin) { + distances.push(distance(n1, opts)); + } else { + ref1 = node.nodes; + for (j = 0, len1 = ref1.length; j < len1; j++) { + n2 = ref1[j]; + if (n2 && n2.point && n2.point !== n1.point) { + distances.push(distance(n1, n2)); + } + } + } + } + } + } + return false; + }); + if (opts.all) { + return distances.sort(function(aa, bb) { + return aa - bb; + }); + } else { + return d3.min(distances); + } +}; + + +},{"./distance.coffee":165}],169:[function(require,module,exports){ +var normalize; + +normalize = require("./normalize.coffee"); + +module.exports = function(edges, source, options) { + var K, dfs, directed, distance, edge, endpoint, id, nodeid, nodes, ref, startpoint, visited; + if (options == null) { + options = {}; + } + options.source = source; + if ((options.nodes == null) || typeof options.nodes !== 'object') { + ref = normalize(edges, options), edges = ref[0], options = ref[1]; + if (options === null) { + return null; + } + } + source = options.source, directed = options.directed, distance = options.distance, nodeid = options.nodeid, startpoint = options.startpoint, endpoint = options.endpoint, K = options.K, nodes = options.nodes; + visited = {}; + visited[source] = true; + dfs = function(origin, curr_distance) { + var a, b, edge, i, len, new_distance, ref1, ref2, results; + ref1 = nodes[origin].outedges; + results = []; + for (i = 0, len = ref1.length; i < len; i++) { + edge = ref1[i]; + a = nodeid(startpoint(edge)); + b = nodeid(endpoint(edge)); + if (!directed && b === origin) { + ref2 = [b, a], a = ref2[0], b = ref2[1]; + } + if (!(b in visited)) { + new_distance = curr_distance + distance(edge); + if (new_distance <= K) { + visited[b] = true; + results.push(dfs(b, new_distance)); + } else { + results.push(void 0); + } + } else { + results.push(void 0); + } + } + return results; + }; + dfs(source, 0); + return { + nodes: (function() { + var results; + results = []; + for (id in visited) { + results.push(nodes[id].node); + } + return results; + })(), + edges: (function() { + var i, len, results; + results = []; + for (i = 0, len = edges.length; i < len; i++) { + edge = edges[i]; + if (nodeid(startpoint(edge)) in visited && nodeid(endpoint(edge)) in visited) { + results.push(edge); + } + } + return results; + })() + }; +}; + + +},{"./normalize.coffee":166}],170:[function(require,module,exports){ +var defaultLocale; + +defaultLocale = require("../core/locale/languages/en_US.coffee"); + +module.exports = function(number, opts) { + var affixes, format, key, labels, length, locale, ret, sigs, symbol, time, vars, zeros; + if (number === void 0 || number === null || number === false) { + return ""; + } + if (!opts) { + opts = {}; + } + if ("locale" in opts) { + locale = opts.locale; + } else { + locale = defaultLocale; + } + time = locale.time.slice(); + format = d3.locale(locale.format); + if (!opts) { + opts = {}; + } + vars = opts.vars || {}; + key = opts.key; + labels = "labels" in opts ? opts.labels : true; + length = number.toString().split(".")[0].length; + if (vars.time && vars.time.value) { + time.push(vars.time.value); + } + if (typeof key === "string" && time.indexOf(key.toLowerCase()) >= 0) { + ret = number; + } else if (key === "share") { + if (number === 0) { + ret = 0; + } else if (number >= 100) { + ret = format.numberFormat(",f")(number); + } else if (number > 99) { + ret = format.numberFormat(".3g")(number); + } else { + ret = format.numberFormat(".2g")(number); + } + ret += "%"; + } else if (number < 10 && number > -10) { + length = number.toString().split("."); + sigs = 1; + if (length.length > 1) { + sigs = d3.min([parseFloat(length[1]).toString().length, 2]); + if (!((-1 < number && number < 1))) { + zeros = length[1].length - parseFloat(length[1]).toString().length; + sigs += 1 + zeros; + } + } + ret = format.numberFormat("." + sigs + "g")(number); + } else if (length > 3) { + symbol = d3.formatPrefix(number).symbol; + symbol = symbol.replace("G", "B"); + number = d3.formatPrefix(number).scale(number); + number = format.numberFormat(".3g")(number); + number = number.replace(locale.format.decimal, "."); + number = parseFloat(number) + ""; + number = number.replace(".", locale.format.decimal); + ret = number + symbol; + } else if (length === 3) { + ret = format.numberFormat(",f")(number); + } else if (number === 0) { + ret = 0; + } else { + if (number === parseInt(number, 10)) { + ret = format.numberFormat(".2")(number); + } else { + ret = format.numberFormat(".3g")(number); + } + } + if (ret.length > 2 && "" + ret.indexOf(".0") === ret.length - 2) { + ret = ret.slice(0, ret.length - 2); + } + if (labels && key && "format" in vars && key in vars.format.affixes.value) { + affixes = vars.format.affixes.value[key]; + return affixes[0] + ret + affixes[1]; + } else { + return ret; + } +}; + + +},{"../core/locale/languages/en_US.coffee":70}],171:[function(require,module,exports){ +var d3selection, validate; + +d3selection = require("../util/d3selection.coffee"); + +validate = require("./validate.coffee"); + + +/** + * Given any two objects, this method will merge the two objects together, returning a new third object. The values of the second object always overwrite the first. + * @method d3plus.object.merge + * @for d3plus.object + * @param obj1 {Object} The primary object. + * @param obj2 {Object} The secondary object to merge into the first. + * @return {Object} + */ + +module.exports = function(obj1, obj2) { + var copyObject, obj3; + copyObject = function(obj, ret, shallow) { + var k, results, v; + results = []; + for (k in obj) { + v = obj[k]; + if (typeof v !== "undefined") { + if (!shallow && validate(v)) { + if (typeof ret[k] !== "object") { + ret[k] = {}; + } + results.push(copyObject(v, ret[k], k.indexOf("d3plus") === 0)); + } else if (!d3selection(v) && v instanceof Array) { + results.push(ret[k] = v.slice(0)); + } else { + results.push(ret[k] = v); + } + } else { + results.push(void 0); + } + } + return results; + }; + obj3 = {}; + if (obj1) { + copyObject(obj1, obj3); + } + if (obj2) { + copyObject(obj2, obj3); + } + return obj3; +}; + + +},{"../util/d3selection.coffee":208,"./validate.coffee":172}],172:[function(require,module,exports){ + +/** + * This function returns true if the variable passed is a literal javascript keyed Object. It's a small, simple function, but it catches some edge-cases that can throw off your code (such as Arrays and `null`). + * @method d3plus.object.validate + * @for d3plus.object + * @param obj {Object} The object to validate. + * @return {Boolean} + */ +module.exports = function(obj) { + return obj && obj.constructor === Object; +}; + + +},{}],173:[function(require,module,exports){ +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Formats a string similar to Python's "format" +//------------------------------------------------------------------------------ +module.exports = function() { + + var args = Array.prototype.slice.call(arguments) + , str = args.shift() + + str.unkeyed_index = 0; + return str.replace(/\{(\w*)\}/g, function(match, key) { + if (key === '') { + key = str.unkeyed_index; + str.unkeyed_index++ + } + if (key == +key) { + return args[key] !== 'undefined' + ? args[key] + : match; + } else { + for (var i = 0; i < args.length; i++) { + if (typeof args[i] === 'object' && typeof args[i][key] !== 'undefined') { + return args[i][key]; + } + } + return match; + } + }.bind(str)); + +} + +},{}],174:[function(require,module,exports){ +var format, locale; + +format = require("./format.js"); + +locale = require("../core/locale/languages/en_US.coffee").ui; + +module.exports = function(list, andText, max, moreText) { + var amount; + if (!(list instanceof Array)) { + return list; + } else { + list = list.slice(0); + } + if (!andText) { + andText = locale.and; + } + if (!moreText) { + moreText = locale.moreText; + } + if (list.length === 2) { + return list.join(" " + andText + " "); + } else { + if (max && list.length > max) { + amount = list.length - max + 1; + list = list.slice(0, max - 1); + list[max - 1] = format(moreText, amount); + } + if (list.length > 1) { + list[list.length - 1] = andText + " " + list[list.length - 1]; + } + return list.join(", "); + } +}; + + +},{"../core/locale/languages/en_US.coffee":70,"./format.js":173}],175:[function(require,module,exports){ +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Removes all non ASCII characters +//------------------------------------------------------------------------------ +module.exports = function(str) { + + var removed = [ "!","@","#","$","%","^","&","*","(",")", + "[","]","{","}",".",",","/","\\","|", + "'","\"",";",":","<",">","?","=","+"]; + + var diacritics = [ + [/[\300-\306]/g, "A"], + [/[\340-\346]/g, "a"], + [/[\310-\313]/g, "E"], + [/[\350-\353]/g, "e"], + [/[\314-\317]/g, "I"], + [/[\354-\357]/g, "i"], + [/[\322-\330]/g, "O"], + [/[\362-\370]/g, "o"], + [/[\331-\334]/g, "U"], + [/[\371-\374]/g, "u"], + [/[\321]/g, "N"], + [/[\361]/g, "n"], + [/[\307]/g, "C"], + [/[\347]/g, "c"] + ]; + + str += ""; + + return ""+str.replace(/[^A-Za-z0-9\-_]/g, function(chr) { + + if (" " === chr) { + return "_"; + } + else if (removed.indexOf(chr) >= 0) { + return ""; + } + + var ret = chr; + for (var d = 0; d < diacritics.length; d++) { + if (new RegExp(diacritics[d][0]).test(chr)) { + ret = diacritics[d][1]; + break; + } + } + + return ret; + + }); + +}; + +},{}],176:[function(require,module,exports){ +var defaultLocale; + +defaultLocale = require("../core/locale/languages/en_US.coffee"); + +module.exports = function(text, opts) { + var biglow, bigs, key, locale, smalls; + if (!text) { + return ""; + } + if (!opts) { + opts = {}; + } + key = opts.key; + if (text.charAt(text.length - 1) === ".") { + return text.charAt(0).toUpperCase() + text.substr(1); + } + locale = "locale" in this ? this.locale.value : defaultLocale; + smalls = locale.lowercase.map(function(b) { + return b.toLowerCase(); + }); + bigs = locale.uppercase; + bigs = bigs.concat(bigs.map(function(b) { + return b + "s"; + })); + biglow = bigs.map(function(b) { + return b.toLowerCase(); + }); + return text.replace(/[^\s!-#%&(-\x2A,-:;\x3F@\x5B-\x5D_\x7B}\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E3B\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]*/g, function(txt, i) { + var bigindex, new_txt; + if (txt) { + bigindex = biglow.indexOf(txt.toLowerCase()); + if (bigindex >= 0) { + return new_txt = bigs[bigindex]; + } else if (smalls.indexOf(txt.toLowerCase()) >= 0 && i !== 0 && i !== text.length - 1) { + return new_txt = txt.toLowerCase(); + } else { + return new_txt = txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); + } + } else { + return ""; + } + }); +}; + + +},{"../core/locale/languages/en_US.coffee":70}],177:[function(require,module,exports){ +var foreign, tspan; + +foreign = require("./foreign.coffee"); + +tspan = require("./tspan.coffee"); + +module.exports = function(vars) { + if (vars.text.html.value) { + foreign(vars); + } else { + tspan(vars); + } +}; + + +},{"./foreign.coffee":178,"./tspan.coffee":181}],178:[function(require,module,exports){ +module.exports = function(vars) { + var anchor, color, family, opacity, text; + text = vars.container.value; + family = text.attr("font-family") || text.style("font-family"); + anchor = vars.align.value || text.attr("text-anchor") || text.style("text-anchor"); + color = text.attr("fill") || text.style("fill"); + opacity = text.attr("opacity") || text.style("opacity"); + anchor = anchor === "end" ? "right" : (anchor === "middle" ? "center" : "left"); + d3.select(text.node().parentNode).append("foreignObject").attr("width", vars.width.value + "px").attr("height", vars.height.value + "px").attr("x", "0px").attr("y", "0px").append("xhtml:div").style("font-family", family).style("font-size", vars.size.value[1] + "px").style("color", color).style("text-align", anchor).style("opacity", opacity).text(vars.text.current); +}; + + +},{}],179:[function(require,module,exports){ +module.exports = function(vars) { + var diff, elem, height, prev, radius, shape, size, width, x, y; + elem = vars.container.value; + prev = elem.node().previousElementSibling; + shape = prev ? prev.tagName.toLowerCase() : ""; + if (prev) { + prev = d3.select(prev); + } + vars.container.x = vars.x.value || parseFloat(elem.attr("x"), 10); + vars.container.y = vars.y.value || parseFloat(elem.attr("y"), 10); + if (prev) { + if (vars.shape.accepted.indexOf(shape) >= 0) { + vars.self.shape(shape); + } + if (shape === "rect") { + x = parseFloat(prev.attr("x"), 10) || 0; + y = parseFloat(prev.attr("y"), 10) || 0; + if (vars.padding.value === false) { + diff = Math.abs(x - vars.container.x); + if (diff) { + vars.self.padding(diff); + } + } + if (!vars.container.x) { + vars.container.x = x + vars.padding.value; + } + if (!vars.container.y) { + vars.container.y = y + vars.padding.value; + } + if (!vars.width.value) { + width = parseFloat(prev.attr("width" || prev.style("width", 10))); + vars.self.width(width); + } + if (!vars.height.value) { + height = parseFloat(prev.attr("height" || prev.style("height", 10))); + vars.self.height(height); + } + } else if (shape === "circle") { + radius = parseFloat(prev.attr("r"), 10); + x = parseFloat(prev.attr("cx"), 10) || 0; + x -= radius; + y = parseFloat(prev.attr("cy"), 10) || 0; + y -= radius; + if (vars.padding.value === false) { + diff = Math.abs(x - vars.container.x); + if (diff) { + vars.self.padding(diff); + } + } + if (!vars.container.x) { + vars.container.x = x + vars.padding.value; + } + if (!vars.container.y) { + vars.container.y = y + vars.padding.value; + } + if (!vars.width.value) { + vars.self.width(radius * 2, 10); + } + if (!vars.height.value) { + vars.self.height(radius * 2, 10); + } + } else { + if (!vars.width.value) { + vars.self.width(500); + } + if (!vars.height.value) { + vars.self.height(500); + } + } + } + if (!vars.container.x) { + vars.container.x = 0; + } + if (!vars.container.y) { + vars.container.y = 0; + } + vars.width.inner = vars.width.value - vars.padding.value * 2; + vars.height.inner = vars.height.value - vars.padding.value * 2; + size = elem.attr("font-size") || elem.style("font-size"); + size = parseFloat(size, 10); + vars.container.fontSize = size; + vars.container.dy = parseFloat(elem.attr("dy"), 10); + if (!vars.size.value) { + if (vars.resize.value) { + return vars.self.size([4, 80]); + } else { + return vars.self.size([size / 2, size]); + } + } +}; + + +},{}],180:[function(require,module,exports){ +module.exports = function(vars) { + var text; + if (!vars.text.value) { + text = vars.container.value.text(); + if (text) { + if (text.indexOf("tspan") >= 0) { + text.replace(/\<\/tspan\>\/g, " "); + text.replace(/\<\/tspan\>/g, ""); + text.replace(/\/g, ""); + } + text = text.replace(/(\r\n|\n|\r)/gm, ""); + text = text.replace(/^\s+|\s+$/g, ""); + vars.self.text(text); + } + } + if (vars.text.value instanceof Array) { + vars.text.phrases = vars.text.value.filter(function(t) { + return ["string", "number"].indexOf(typeof t) >= 0; + }); + } else { + vars.text.phrases = [vars.text.value + ""]; + } + if (!vars.align.value) { + return vars.container.align = vars.container.value.style("text-anchor") || vars.container.value.attr("text-anchor"); + } +}; + + +},{}],181:[function(require,module,exports){ +var rtl; + +rtl = require("../../client/rtl.coffee"); + +module.exports = function(vars) { + var anchor, dy, ellipsis, fontSize, h, height, line, lineWidth, lines, mirror, newLine, placeWord, progress, reverse, rmod, rotate, rx, ry, space, start, textBox, translate, truncate, valign, width, words, wrap, x, xOffset, y, yOffset; + newLine = function(first) { + var tspan; + if (!reverse || first) { + tspan = vars.container.value.append("tspan"); + } else { + tspan = vars.container.value.insert("tspan", "tspan"); + } + return tspan.attr("x", x + "px").attr("dy", dy + "px").style("baseline-shift", "0%").attr("dominant-baseline", "alphabetic"); + }; + mirror = vars.rotate.value === -90 || vars.rotate.value === 90; + width = mirror ? vars.height.inner : vars.width.inner; + height = mirror ? vars.width.inner : vars.height.inner; + if (vars.shape.value === "circle") { + anchor = "middle"; + } else { + anchor = vars.align.value || vars.container.align || "start"; + } + if (anchor === "end" || (anchor === "start" && rtl)) { + xOffset = width; + } else if (anchor === "middle") { + xOffset = width / 2; + } else { + xOffset = 0; + } + valign = vars.valign.value || "top"; + x = vars.container.x + xOffset; + fontSize = vars.resize.value ? vars.size.value[1] : vars.container.fontSize || vars.size.value[0]; + dy = vars.container.dy || fontSize * 1.1; + textBox = null; + progress = null; + words = null; + reverse = false; + yOffset = 0; + if (vars.shape.value === "circle") { + if (valign === "middle") { + yOffset = ((height / dy % 1) * dy) / 2; + } else if (valign === "end") { + yOffset = (height / dy % 1) * dy; + } + } + vars.container.value.attr("text-anchor", anchor).attr("font-size", fontSize + "px").style("font-size", fontSize + "px").attr("x", vars.container.x).attr("y", vars.container.y); + truncate = function() { + textBox.remove(); + if (reverse) { + line++; + textBox = vars.container.value.select("tspan"); + } else { + line--; + textBox = d3.select(vars.container.value.node().lastChild); + } + if (!textBox.empty()) { + words = textBox.text().match(/[^\s-]+-?/g); + return ellipsis(); + } + }; + lineWidth = function() { + var b; + if (vars.shape.value === "circle") { + b = ((line - 1) * dy) + yOffset; + if (b > height / 2) { + b += dy; + } + return 2 * Math.sqrt(b * ((2 * (width / 2)) - b)); + } else { + return width; + } + }; + ellipsis = function() { + var lastChar, lastWord; + if (words && words.length) { + lastWord = words.pop(); + lastChar = lastWord.charAt(lastWord.length - 1); + if (lastWord.length === 1 && vars.text.split.value.indexOf(lastWord) >= 0) { + return ellipsis(); + } else { + if (vars.text.split.value.indexOf(lastChar) >= 0) { + lastWord = lastWord.substr(0, lastWord.length - 1); + } + textBox.text(words.join(" ") + " " + lastWord + "..."); + if (textBox.node().getComputedTextLength() > lineWidth()) { + return ellipsis(); + } + } + } else { + return truncate(); + } + }; + placeWord = function(word) { + var current, i, joiner, next_char; + current = textBox.text(); + next_char = ""; + if (reverse) { + next_char = vars.text.current.charAt(vars.text.current.length - progress.length - 1); + if (next_char === " ") { + joiner = ""; + i = 2; + while (next_char === " ") { + joiner += " "; + next_char = vars.text.current.charAt(vars.text.current.length - progress.length - i); + i++; + } + } else { + joiner = ""; + } + progress = word + joiner + progress; + textBox.text(word + joiner + current); + } else { + next_char = vars.text.current.charAt(progress.length); + if (next_char === " ") { + joiner = ""; + i = 1; + while (next_char === " ") { + joiner += " "; + next_char = vars.text.current.charAt(progress.length + i); + i++; + } + } else { + joiner = ""; + } + progress += joiner + word; + textBox.text(current + joiner + word); + } + if (Math.floor(textBox.node().getComputedTextLength()) > lineWidth() || next_char === "\n") { + textBox.text(current); + if (current.length) { + textBox = newLine(); + } + textBox.text(word); + if (reverse) { + return line--; + } else { + return line++; + } + } + }; + start = 1; + line = null; + lines = null; + wrap = function() { + var i, j, len, next_char, unsafe, word; + vars.container.value.text("").html(""); + words = vars.text.words.slice(); + if (reverse) { + words.reverse(); + } + progress = ""; + textBox = newLine(true); + line = start; + for (j = 0, len = words.length; j < len; j++) { + word = words[j]; + if (line * dy > height) { + truncate(); + break; + } + placeWord(word); + unsafe = true; + while (unsafe) { + next_char = vars.text.current.charAt(progress.length); + i = 1; + while (next_char === " ") { + next_char = vars.text.current.charAt(progress.length + i); + i++; + } + unsafe = vars.text.split.value.indexOf(next_char) >= 0; + if (unsafe) { + placeWord(next_char); + } + } + } + if (line * dy > height) { + truncate(); + } + return lines = Math.abs(line - start) + 1; + }; + wrap(); + lines = 0; + vars.container.value.selectAll("tspan").each(function() { + if (d3.select(this).text().length) { + return lines++; + } + }); + if (vars.shape.value === "circle") { + space = height - lines * dy; + if (space > dy) { + if (valign === "middle") { + start = (space / dy / 2 >> 0) + 1; + wrap(); + } else if (valign === "bottom") { + reverse = true; + start = height / dy >> 0; + wrap(); + } + } + } + lines = 0; + vars.container.value.selectAll("tspan").each(function() { + if (d3.select(this).text().length) { + return lines++; + } + }); + if (valign === "top") { + y = 0; + } else { + h = lines * dy; + y = valign === "middle" ? height / 2 - h / 2 : height - h; + } + y -= dy * 0.2; + translate = "translate(0," + y + ")"; + if (vars.rotate.value === 180 || vars.rotate.value === -180) { + rx = vars.container.x + width / 2; + ry = vars.container.y + height / 2; + } else { + rmod = vars.rotate.value < 0 ? width : height; + rx = vars.container.x + rmod / 2; + ry = vars.container.y + rmod / 2; + } + rotate = "rotate(" + vars.rotate.value + ", " + rx + ", " + ry + ")"; + return vars.container.value.attr("transform", rotate + translate); +}; + + +},{"../../client/rtl.coffee":40}],182:[function(require,module,exports){ +var flow, fontSizes, resize, wrap; + +flow = require("./flow.coffee"); + +fontSizes = require("../../font/sizes.coffee"); + +wrap = function(vars) { + var firstChar; + if (vars.text.phrases.length) { + vars.text.current = vars.text.phrases.shift() + ""; + vars.text.words = vars.text.current.match(vars.text.split["break"]); + firstChar = vars.text.current.charAt(0); + if (firstChar !== vars.text.words[0].charAt(0)) { + vars.text.words[0] = firstChar + vars.text.words[0]; + } + vars.container.value.html(""); + if (vars.resize.value) { + resize(vars); + } else { + flow(vars); + } + } +}; + +module.exports = wrap; + +resize = function(vars) { + var addon, areaMod, areaRatio, boxArea, height, heightMax, i, lineWidth, maxWidth, mirror, sizeMax, sizeRatio, sizes, textArea, width, widthRatio, words; + words = []; + i = 0; + while (i < vars.text.words.length) { + addon = (i === vars.text.words.length - 1 ? "" : " "); + words.push(vars.text.words[i] + addon); + i++; + } + mirror = vars.rotate.value === -90 || vars.rotate.value === 90; + width = mirror ? vars.height.inner : vars.width.inner; + height = mirror ? vars.width.inner : vars.height.inner; + sizeMax = Math.floor(vars.size.value[1]); + lineWidth = vars.shape.value === "circle" ? width * 0.75 : width; + sizes = fontSizes(words, { + "font-size": sizeMax + "px" + }, { + parent: vars.container.value + }); + maxWidth = d3.max(sizes, function(d) { + return d.width; + }); + areaMod = 1.165 + (width / height * 0.11); + textArea = d3.sum(sizes, function(d) { + var h; + h = vars.container.dy || sizeMax * 1.2; + return d.width * h; + }) * areaMod; + if (vars.shape.value === "circle") { + boxArea = Math.PI * Math.pow(width / 2, 2); + } else { + boxArea = lineWidth * height; + } + if (maxWidth > lineWidth || textArea > boxArea) { + areaRatio = Math.sqrt(boxArea / textArea); + widthRatio = lineWidth / maxWidth; + sizeRatio = d3.min([areaRatio, widthRatio]); + sizeMax = d3.max([vars.size.value[0], Math.floor(sizeMax * sizeRatio)]); + } + heightMax = Math.floor(height * 0.8); + if (sizeMax > heightMax) { + sizeMax = heightMax; + } + if (maxWidth * (sizeMax / vars.size.value[1]) <= lineWidth) { + if (sizeMax !== vars.size.value[1]) { + vars.self.size([vars.size.value[0], sizeMax]); + } + flow(vars); + } else { + wrap(vars); + } +}; + + +},{"../../font/sizes.coffee":102,"./flow.coffee":177}],183:[function(require,module,exports){ +module.exports = { + accepted: [false, "start", "middle", "end", "left", "center", "right"], + process: function(value) { + var css; + css = ["left", "center", "right"].indexOf(value); + if (css >= 0) { + value = this.accepted[css + 1]; + } + return value; + }, + value: false +}; + + +},{}],184:[function(require,module,exports){ +arguments[4][108][0].apply(exports,arguments) +},{"dup":108}],185:[function(require,module,exports){ +var d3selection; + +d3selection = require("../../util/d3selection.coffee"); + +module.exports = { + accepted: [false, Array, Object, String], + element: false, + id: "default", + process: function(value) { + if (value === false) { + return false; + } else if (d3selection(value)) { + return value; + } else if (value instanceof Array) { + return d3.select(value[0][0]); + } else { + this.selector = value; + return d3.select(value); + } + }, + value: false +}; + + +},{"../../util/d3selection.coffee":208}],186:[function(require,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"dup":112}],187:[function(require,module,exports){ +var print, stringFormat; + +print = require("../../core/console/print.coffee"); + +stringFormat = require("../../string/format.js"); + +module.exports = { + accepted: [void 0], + process: function(value, vars) { + var selector, str; + if (this.initialized === false) { + return value; + } + if (vars.container.value === false) { + str = vars.format.locale.value.dev.setContainer; + print.warning(str, "container"); + } else if (vars.container.value.empty()) { + str = vars.format.locale.value.dev.noContainer; + selector = vars.container.selector || ""; + print.warning(stringFormat(str, "\"" + selector + "\""), "container"); + } else { + if (vars.dev.value) { + print.time("total draw time"); + } + vars.container.value.call(vars.self); + } + return value; + }, + value: void 0 +}; + + +},{"../../core/console/print.coffee":52,"../../string/format.js":173}],188:[function(require,module,exports){ +var locale, mergeObject; + +locale = require("../../core/locale/locale.coffee"); + +mergeObject = require("../../object/merge.coffee"); + +module.exports = { + accepted: [Function, String], + locale: { + accepted: function() { + return d3.keys(locale); + }, + process: function(value) { + var defaultLocale, returnObject; + defaultLocale = "en_US"; + returnObject = locale[defaultLocale]; + if (value !== defaultLocale) { + returnObject = mergeObject(returnObject, locale[value]); + } + this.language = value; + return returnObject; + }, + value: "en_US" + }, + process: function(value, vars) { + if (this.initialized && typeof value === "string") { + vars.self.format({ + locale: value + }); + } else { + if (typeof value === "function") { + return value; + } + } + return this.value; + }, + value: "en_US" +}; + + +},{"../../core/locale/locale.coffee":79,"../../object/merge.coffee":171}],189:[function(require,module,exports){ +module.exports = { + accepted: [false, Number], + value: false +}; + + +},{}],190:[function(require,module,exports){ +arguments[4][189][0].apply(exports,arguments) +},{"dup":189}],191:[function(require,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"dup":112}],192:[function(require,module,exports){ +module.exports = { + accepted: [-180, -90, 0, 90, 180], + value: 0 +}; + + +},{}],193:[function(require,module,exports){ +module.exports = { + accepted: ["circle", "square"], + value: false +}; + + +},{}],194:[function(require,module,exports){ +module.exports = { + accepted: [Array, false], + value: false +}; + + +},{}],195:[function(require,module,exports){ +module.exports = { + accepted: [false, Array, Number, String], + html: { + accepted: [Boolean], + value: false + }, + init: function(vars) { + var s; + s = this.split.value; + this.split["break"] = new RegExp("[^\\s\\" + s.join("\\") + "]+\\" + s.join("?\\") + "?", "g"); + return false; + }, + split: { + accepted: [Array], + process: function(s) { + this["break"] = new RegExp("[^\\s\\" + s.join("\\") + "]+\\" + s.join("?\\") + "?", "g"); + return s; + }, + value: ["-", "/", ";", ":", "&"] + } +}; + + +},{}],196:[function(require,module,exports){ +module.exports = { + accepted: [false, "top", "middle", "bottom"], + value: false +}; + + +},{}],197:[function(require,module,exports){ +arguments[4][189][0].apply(exports,arguments) +},{"dup":189}],198:[function(require,module,exports){ +arguments[4][189][0].apply(exports,arguments) +},{"dup":189}],199:[function(require,module,exports){ +arguments[4][189][0].apply(exports,arguments) +},{"dup":189}],200:[function(require,module,exports){ +var attach, print, sizes, text, wrap; + +attach = require("../core/methods/attach.coffee"); + +sizes = require("./helpers/parseSize.coffee"); + +print = require("../core/console/print.coffee"); + +text = require("./helpers/parseText.coffee"); + +wrap = require("./helpers/wrap.coffee"); + +module.exports = function() { + var vars; + vars = { + self: function(selection) { + selection.each(function() { + sizes(vars); + if (vars.size.value[0] <= vars.height.inner) { + text(vars); + wrap(vars); + } else { + vars.container.value.html(""); + } + if (vars.dev.value) { + print.timeEnd("total draw time"); + } + }); + return vars.self; + } + }; + attach(vars, { + align: require("./methods/align.coffee"), + config: require("./methods/config.coffee"), + container: require("./methods/container.coffee"), + dev: require("./methods/dev.coffee"), + draw: require("./methods/draw.coffee"), + format: require("./methods/format.coffee"), + height: require("./methods/height.coffee"), + padding: require("./methods/padding.coffee"), + resize: require("./methods/resize.coffee"), + rotate: require("./methods/rotate.coffee"), + text: require("./methods/text.coffee"), + shape: require("./methods/shape.coffee"), + size: require("./methods/size.coffee"), + valign: require("./methods/valign.coffee"), + width: require("./methods/width.coffee"), + x: require("./methods/x.coffee"), + y: require("./methods/y.coffee") + }); + return vars.self; +}; + + +},{"../core/console/print.coffee":52,"../core/methods/attach.coffee":80,"./helpers/parseSize.coffee":179,"./helpers/parseText.coffee":180,"./helpers/wrap.coffee":182,"./methods/align.coffee":183,"./methods/config.coffee":184,"./methods/container.coffee":185,"./methods/dev.coffee":186,"./methods/draw.coffee":187,"./methods/format.coffee":188,"./methods/height.coffee":189,"./methods/padding.coffee":190,"./methods/resize.coffee":191,"./methods/rotate.coffee":192,"./methods/shape.coffee":193,"./methods/size.coffee":194,"./methods/text.coffee":195,"./methods/valign.coffee":196,"./methods/width.coffee":197,"./methods/x.coffee":198,"./methods/y.coffee":199}],201:[function(require,module,exports){ +var defaultLocale = require("../core/locale/languages/en_US.coffee"), + events = require("../client/pointer.coffee"), + legible = require("../color/legible.coffee"), + move = require("./move.coffee"), + prefix = require("../client/prefix.coffee"), + rtl = require("../client/rtl.coffee"), + removeTooltip = require("./remove.coffee"), + scroll = require("../client/scroll.js"), + scrollBar = require("../client/scrollbar.coffee"), + stringList = require("../string/list.coffee"), + textColor = require("../color/text.coffee") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Create a Tooltip +//------------------------------------------------------------------- +module.exports = function(params) { + + var default_width = params.fullscreen ? 250 : 200 + , vendor = prefix() + params.width = params.width || default_width + params.max_width = params.max_width || 386 + params.id = params.id || "default" + params.size = params.fullscreen || params.html ? "large" : "small" + params.offset = params.offset || 0 + params.arrow_offset = params.arrow ? 8 : 0 + params.x = params.x || 0 + params.y = params.y || 0 + params.parent = params.parent || d3.select("body") + params.curtain = params.curtain || "#fff" + params.curtainopacity = params.curtainopacity || 0.8 + params.background = params.background || "#fff" + params.fontcolor = params.fontcolor || "#444" + params.fontfamily = params.fontfamily || "sans-serif" + params.fontweight = params.fontweight || "normal" + params.fontsize = params.fontsize || "12px" + params.style = params.style || "default" + params.zindex = params.size == "small" ? 2000 : 500 + params.locale = params.locale || defaultLocale + params.stacked = params.stacked || false; + + + var parentHeight = params.parent ? params.parent.node().offsetHeight + || params.parent.node().getBoundingClientRect().height : 0 + + if (!params.iconsize) { + params.iconsize = params.size == "small" ? 22 : 50 + } + + if (params.parent.node() === document.body) { + params.limit = [window.innerWidth + scroll.x(), window.innerHeight + scroll.y()]; + var sb = scrollBar(); + if (document.body.scrollHeight > window.innerHeight) params.limit[0] -= sb; + } + else { + params.limit = [ + parseFloat(params.parent.style("width"),10), + parseFloat(params.parent.style("height"),10) + ]; + } + + if ( params.title instanceof Array ) { + + var and = params.locale.ui.and + , more = params.locale.ui.more + + params.title = stringList( params.title , and , 3 , more ) + + } + + removeTooltip(params.id) + + params.anchor = {} + if (params.fullscreen) { + params.anchor.x = "center" + params.anchor.y = "center" + params.x = params.parent ? params.parent.node().offsetWidth/2 : window.innerWidth/2 + params.y = params.parent ? parentHeight/2 : window.innerHeight/2 + } + else if (params.align) { + var a = params.align.split(" ") + params.anchor.y = a[0] + if (a[1]) params.anchor.x = a[1] + else params.anchor.x = "center" + } + else { + params.anchor.x = "center" + params.anchor.y = "top" + } + + var title_width = params.width - 30 + + if (params.fullscreen) { + var curtain = params.parent.append("div") + .attr("id","d3plus_tooltip_curtain_"+params.id) + .attr("class","d3plus_tooltip_curtain") + .style("background-color",params.curtain) + .style("opacity",params.curtainopacity) + .style("position","absolute") + .style("z-index",499) + .style("top","0px") + .style("right","0px") + .style("bottom","0px") + .style("left","0px") + .on(events.click,function(){ + removeTooltip(params.id) + }) + } + + var tooltip = params.parent.append("div") + .datum(params) + .attr("id","d3plus_tooltip_id_"+params.id) + .attr("class","d3plus_tooltip d3plus_tooltip_"+params.size) + .style("color",params.fontcolor) + .style("font-family",params.fontfamily) + .style("font-weight",params.fontweight) + .style("font-size",params.fontsize+"px") + .style(vendor+"box-shadow","0px 1px 3px rgba(0, 0, 0, 0.25)") + .style("position","absolute") + // .style("z-index",params.zindex) + .on(events.out, close_descriptions) + + if (params.max_height) { + tooltip.style("max-height",params.max_height+"px") + } + + if (params.fixed) { + tooltip.style("z-index",500) + params.mouseevents = true + } + else { + tooltip.style("z-index",2000) + } + + var container = tooltip.append("div") + .datum(params) + .attr("class","d3plus_tooltip_container") + .style("background-color",params.background) + .style("padding","6px") + + if (params.fullscreen && params.html && !params.stacked) { + + w = params.parent ? params.parent.node().offsetWidth*0.75 : window.innerWidth*0.75 + h = params.parent ? parentHeight*0.75 : window.innerHeight*0.75 + + container + .style("width",w+"px") + .style("height",h+"px") + + var body = container.append("div") + .attr("class","d3plus_tooltip_body") + .style("padding-right","6px") + .style("display","inline-block") + .style("z-index",1) + .style("width",params.width+"px") + + } + else { + + if (params.width == "auto") { + var w = "auto" + container.style("max-width",params.max_width+"px") + } + else var w = params.width-14+"px" + + var body = container + .style("width",w) + + } + + if (params.title || params.icon) { + var header = body.append("div") + .attr("class","d3plus_tooltip_header") + .style("position","relative") + .style("z-index",1) + } + + if (params.fullscreen) { + var close = tooltip.append("div") + .attr("class","d3plus_tooltip_close") + .style("background-color",params.color) + .style("color",textColor(params.color)) + .style("position","absolute") + .style(vendor+"box-shadow","0 1px 3px rgba(0, 0, 0, 0.25)") + .style("font-size","20px") + .style("height","18px") + .style("line-height","14px") + .style("text-align","center") + .style("right","16px") + .style("top","-10px") + .style("width","18px") + .style("z-index",10) + .html("\×") + .on(events.over,function(){ + d3.select(this) + .style("cursor","pointer") + .style(vendor+"box-shadow","0 1px 3px rgba(0, 0, 0, 0.5)") + }) + .on(events.out,function(){ + d3.select(this) + .style("cursor","auto") + .style(vendor+"box-shadow","0 1px 3px rgba(0, 0, 0, 0.25)") + }) + .on(events.click,function(){ + removeTooltip(params.id) + }) + + d3.select("body").on("keydown.esc_" + params.id, function(){ + if (d3.event.keyCode === 27) { + removeTooltip(params.id); + d3.select("body").on("keydown.esc_" + params.id, null); + } + }) + + } + + if (!params.mouseevents) { + tooltip.style("pointer-events","none") + } + else if (params.mouseevents !== true) { + + var oldout = d3.select(params.mouseevents).on(events.out) + + var newout = function() { + + var target = d3.event.toElement || d3.event.relatedTarget + if (target) { + var c = typeof target.className == "string" ? target.className : target.className.baseVal + var istooltip = c.indexOf("d3plus_tooltip") == 0 + } + else { + var istooltip = false + } + if (!target || (!ischild(tooltip.node(),target) && !ischild(params.mouseevents,target) && !istooltip)) { + oldout(d3.select(params.mouseevents).datum()) + close_descriptions() + d3.select(params.mouseevents).on(events.out,oldout) + } + } + + var ischild = function(parent, child) { + var node = child.parentNode; + while (node !== null) { + if (node == parent) { + return true; + } + node = node.parentNode; + } + return false; + } + + d3.select(params.mouseevents).on(events.out,newout) + tooltip.on(events.out,newout) + + var move_event = d3.select(params.mouseevents).on(events.move) + if (move_event) { + tooltip.on(events.move,move_event) + } + + } + + if (params.arrow) { + var arrow = tooltip.append("div") + .attr("class","d3plus_tooltip_arrow") + .style("background-color",params.background) + .style(vendor+"box-shadow","0px 1px 3px rgba(0, 0, 0, 0.25)") + .style("position","absolute") + .style("bottom","-5px") + .style("height","10px") + .style("left","50%") + .style("margin-left","-5px") + .style("width","10px") + .style(vendor+"transform","rotate(45deg)") + .style("z-index",-1) + } + + if (params.icon) { + + var title_icon = header.append("div") + .attr("class","d3plus_tooltip_icon") + .style("width",params.iconsize+"px") + .style("height",params.iconsize+"px") + .style("z-index",1) + .style("background-position","50%") + .style("background-size","100%") + .style("background-image","url("+params.icon+")") + .style("display","inline-block") + .style("margin","0px 3px 3px 0px") + + if (params.style == "knockout") { + title_icon.style("background-color",params.color) + } + + title_width -= title_icon.node().offsetWidth + } + + if (params.title) { + var mw = params.max_width-6 + if ( params.icon ) mw -= (params.iconsize+6) + mw += "px" + + var title = header.append("div") + .attr("class","d3plus_tooltip_title") + .style("max-width",mw) + .style("color",!params.icon ? legible(params.color) : params.fontcolor) + .style("vertical-align","top") + .style("width",title_width+"px") + .style("display","inline-block") + .style("overflow","hidden") + .style("text-overflow","ellipsis") + .style("word-wrap","break-word") + .style("z-index",1) + .style("font-size",params.size === "large" ? "18px" : "16px") + .style("line-height",params.size === "large" ? "20px" : "17px") + .style("padding",params.size === "large" ? "3px 6px" : "3px") + .text(params.title) + } + + if (params.description) { + var description = body.append("div") + .attr("class","d3plus_tooltip_description") + .style("font-size","12px") + .style("padding","6px") + .text(params.description) + } + + if (params.data || params.html && !params.fullscreen) { + + var data_container = body.append("div") + .attr("class","d3plus_tooltip_data_container") + .style("overflow-y","auto") + .style("z-index",-1) + } + + if (params.data) { + + var val_width = 0, val_heights = {} + + var last_group = null + params.data.forEach(function(d,i){ + + if (d.group) { + if (last_group != d.group) { + last_group = d.group + data_container.append("div") + .attr("class","d3plus_tooltip_data_title") + .style("font-size","12px") + .style("font-weight","bold") + .style("padding","6px 3px 0px 3px") + .text(d.group) + } + } + + var block = data_container.append("div") + .attr("class","d3plus_tooltip_data_block") + .style("font-size","12px") + .style("padding","3px 6px") + .style("position","relative") + .datum(d) + + if ( d.highlight === true ) { + block.style("color",legible(params.color)) + } + else if ( d.allColors || d.highlight !== params.color ) { + block.style("color",legible(d.highlight)) + } + + var name = block.append("div") + .attr("class","d3plus_tooltip_data_name") + .style("display","inline-block") + .html(d.name) + .on(events.out,function(){ + d3.event.stopPropagation() + }) + + if (d.link) { + name + .style("cursor","pointer") + .on(events.click,d.link) + } + + if ( d.value instanceof Array ) { + + var and = params.locale.ui.and + , more = params.locale.ui.more + + d.value = list( d.value , and , 3 , more ) + + } + + var val = block.append("div") + .attr("class","d3plus_tooltip_data_value") + .style("display","block") + .style("position","absolute") + .style("text-align","right") + .style("top","3px") + .html(d.value) + .on(events.out,function(){ + d3.event.stopPropagation() + }) + + if (rtl) { + val.style("left","6px") + } + else { + val.style("right","6px") + } + + if (params.mouseevents && d.desc) { + var desc = block.append("div") + .attr("class","d3plus_tooltip_data_desc") + .style("color","#888") + .style("overflow","hidden") + .style(vendor+"transition","height 0.5s") + .style("width","85%") + .text(d.desc) + .on(events.out,function(){ + d3.event.stopPropagation() + }) + + var dh = desc.node().offsetHeight || desc.node().getBoundingClientRect().height + + desc.style("height","0px") + + var help = name.append("div") + .attr("class","d3plus_tooltip_data_help") + .style("background-color","#ccc") + .style(vendor+"border-radius","5px") + .style("color","#fff") + .style("cursor","pointer") + .style("display","inline-block") + .style("font-size","8px") + .style("font-weight","bold") + .style("height","10px") + .style("margin","3px 0px 0px 3px") + .style("padding-right","1px") + .style("text-align","center") + .style("width","10px") + .style("vertical-align","top") + .style(prefix+"transition","background-color 0.5s") + .text("?") + .on(events.over,function(){ + var c = d3.select(this.parentNode.parentNode).style("color") + d3.select(this).style("background-color",c) + desc.style("height",dh+"px") + }) + .on(events.out,function(){ + d3.event.stopPropagation() + }) + + name + .style("cursor","pointer") + .on(events.over,function(){ + close_descriptions() + var c = d3.select(this.parentNode).style("color") + help.style("background-color",c) + desc.style("height",dh+"px") + }) + + block.on(events.out,function(){ + d3.event.stopPropagation() + close_descriptions() + }) + } + + var w = parseFloat(val.style("width"),10) + if (w > params.width/2) w = params.width/2 + if (w > val_width) val_width = w + + if (i != params.data.length-1) { + if ((d.group && d.group == params.data[i+1].group) || !d.group && !params.data[i+1].group) + data_container.append("div") + .attr("class","d3plus_tooltip_data_seperator") + .style("background-color","#ddd") + .style("display","block") + .style("height","1px") + .style("margin","0px 3px") + } + + }) + + data_container.selectAll(".d3plus_tooltip_data_name") + .style("width",function(){ + var w = parseFloat(d3.select(this.parentNode).style("width"),10) + return (w-val_width-30)+"px" + }) + + data_container.selectAll(".d3plus_tooltip_data_value") + .style("width",val_width+"px") + .each(function(d){ + var h = parseFloat(d3.select(this).style("height"),10) + val_heights[d.name] = h + }) + + data_container.selectAll(".d3plus_tooltip_data_name") + .style("min-height",function(d){ + return val_heights[d.name]+"px" + }) + + } + + if (params.html && (!params.fullscreen || params.stacked)) { + data_container.append("div") + .html(params.html) + if (params.js) { + params.js(container) + } + } + + var footer = body.append("div") + .attr("class","d3plus_tooltip_footer") + .style("font-size","10px") + .style("position","relative") + .style("text-align","center") + + if (params.footer) { + footer.html(params.footer) + } + + params.height = tooltip.node().offsetHeight || tooltip.node().getBoundingClientRect().height + + if (params.html && params.fullscreen && !params.stacked) { + var h = params.height-12 + var w = tooltip.node().offsetWidth-params.width-44 + container.append("div") + .attr("class","d3plus_tooltip_html") + .style("width",w+"px") + .style("height",h+"px") + .style("display","inline-block") + .style("vertical-align","top") + .style("overflow-y","auto") + .style("padding","0px 12px") + .style("position","absolute") + .html(params.html) + if (params.js) { + params.js(container) + } + } + + params.width = tooltip.node().offsetWidth + + if (params.anchor.y != "center") params.height += params.arrow_offset + else params.width += params.arrow_offset + + if (params.data || ((!params.fullscreen || params.stacked) && params.html)) { + + if (!params.fullscreen || params.stacked) { + var limit = params.fixed ? parentHeight-params.y-10 : parentHeight-10 + var h = params.height < limit ? params.height : limit + } + else { + var h = params.height + } + h -= parseFloat(container.style("padding-top"),10) + h -= parseFloat(container.style("padding-bottom"),10) + if (header) { + h -= header.node().offsetHeight || header.node().getBoundingClientRect().height + h -= parseFloat(header.style("padding-top"),10) + h -= parseFloat(header.style("padding-bottom"),10) + } + if (footer) { + h -= footer.node().offsetHeight || footer.node().getBoundingClientRect().height + h -= parseFloat(footer.style("padding-top"),10) + h -= parseFloat(footer.style("padding-bottom"),10) + } + + data_container + .style("max-height",h+"px") + } + + params.height = tooltip.node().offsetHeight || tooltip.node().getBoundingClientRect().height + + move(params.x, params.y, params.id); + +} + + + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Function that closes ALL Descriptions +//------------------------------------------------------------------- +function close_descriptions() { + d3.selectAll("div.d3plus_tooltip_data_desc").style("height","0px"); + d3.selectAll("div.d3plus_tooltip_data_help").style("background-color","#ccc"); +} + +},{"../client/pointer.coffee":38,"../client/prefix.coffee":39,"../client/rtl.coffee":40,"../client/scroll.js":41,"../client/scrollbar.coffee":42,"../color/legible.coffee":44,"../color/text.coffee":50,"../core/locale/languages/en_US.coffee":70,"../string/list.coffee":174,"./move.coffee":202,"./remove.coffee":203}],202:[function(require,module,exports){ +var arrowStyle, scroll; + +scroll = require("../client/scroll.js"); + +module.exports = function(x, y, id) { + var d, mins, tooltip; + if (!id) { + id = "default"; + } + tooltip = d3.select("div#d3plus_tooltip_id_" + id); + if (tooltip.node()) { + d = tooltip.datum(); + d.cx = x; + d.cy = y; + if (!d.fixed) { + if (d.parent.node().tagName.toLowerCase() === "body") { + mins = [scroll.x(), scroll.y()]; + } else { + mins = [0, 0]; + } + if (d.anchor.y !== "center") { + if (d.anchor.x === "right") { + d.x = d.cx - d.arrow_offset - 4; + } else if (d.anchor.x === "center") { + d.x = d.cx - d.width / 2; + } else { + if (d.anchor.x === "left") { + d.x = d.cx - d.width + d.arrow_offset + 2; + } + } + if (d.anchor.y === "bottom") { + d.flip = d.cy + d.height + d.offset <= d.limit[1]; + } else { + if (d.anchor.y === "top") { + d.flip = d.cy - d.height - d.offset < mins[1]; + } + } + if (d.flip) { + d.y = d.cy + d.offset + d.arrow_offset; + } else { + d.y = d.cy - d.height - d.offset - d.arrow_offset; + } + } else { + d.y = d.cy - d.height / 2; + if (d.anchor.x === "right") { + d.flip = d.cx + d.width + d.offset <= d.limit[0]; + } else { + if (d.anchor.x === "left") { + d.flip = d.cx - d.width - d.offset < mins[0]; + } + } + if (d.anchor.x === "center") { + d.flip = false; + d.x = d.cx - d.width / 2; + } else if (d.flip) { + d.x = d.cx + d.offset + d.arrow_offset; + } else { + d.x = d.cx - d.width - d.offset; + } + } + if (d.x < mins[0]) { + d.x = mins[0]; + } else { + if (d.x + d.width > d.limit[0]) { + d.x = d.limit[0] - d.width; + } + } + if (d.y < mins[1]) { + d.y = mins[1]; + } else { + if (d.y + d.height > d.limit[1]) { + d.y = d.limit[1] - d.height; + } + } + } + tooltip.style("top", d.y + "px").style("left", d.x + "px"); + if (d.arrow) { + tooltip.selectAll(".d3plus_tooltip_arrow").call(arrowStyle); + } + } + return tooltip; +}; + +arrowStyle = function(arrow) { + return arrow.style("bottom", function(d) { + if (d.anchor.y !== "center" && !d.flip) { + return "-5px"; + } else { + return "auto"; + } + }).style("right", function(d) { + if (d.anchor.y === "center" && !d.flip) { + return "-5px"; + } else { + return "auto"; + } + }).style("top", function(d) { + if (d.anchor.y !== "center" && d.flip) { + return "-5px"; + } else if (d.anchor.y === "center") { + return "50%"; + } else { + return "auto"; + } + }).style("left", function(d) { + if (d.anchor.y === "center" && d.flip) { + return "-5px"; + } else if (d.anchor.y !== "center") { + return "50%"; + } else { + return "auto"; + } + }).style("margin-left", function(d) { + var arrow_x; + if (d.anchor.y === "center") { + return "auto"; + } else { + if (d.anchor.x === "right") { + arrow_x = -d.width / 2 + d.arrow_offset / 2; + } else if (d.anchor.x === "left") { + arrow_x = d.width / 2 - d.arrow_offset * 2 - 5; + } else { + arrow_x = -5; + } + if (d.cx - d.width / 2 - 5 < arrow_x) { + arrow_x = d.cx - d.width / 2 - 5; + if (arrow_x < 2 - d.width / 2) { + arrow_x = 2 - d.width / 2; + } + } else if (-(d.limit[0] - d.cx - d.width / 2 + 5) > arrow_x) { + arrow_x = -(d.limit[0] - d.cx - d.width / 2 + 5); + if (arrow_x > d.width / 2 - 11) { + arrow_x = d.width / 2 - 11; + } + } + return arrow_x + "px"; + } + }).style("margin-top", function(d) { + var arrow_y; + if (d.anchor.y !== "center") { + return "auto"; + } else { + if (d.anchor.y === "bottom") { + arrow_y = -d.height / 2 + d.arrow_offset / 2 - 1; + } else if (d.anchor.y === "top") { + arrow_y = d.height / 2 - d.arrow_offset * 2 - 2; + } else { + arrow_y = -9; + } + if (d.cy - d.height / 2 - d.arrow_offset < arrow_y) { + arrow_y = d.cy - d.height / 2 - d.arrow_offset; + if (arrow_y < 4 - d.height / 2) { + arrow_y = 4 - d.height / 2; + } + } else if (-(d.limit[1] - d.cy - d.height / 2 + d.arrow_offset) > arrow_y) { + arrow_y = -(d.limit[1] - d.cy - d.height / 2 + d.arrow_offset); + if (arrow_y > d.height / 2 - 22) { + arrow_y = d.height / 2 - 22; + } + } + return arrow_y + "px"; + } + }); +}; + + +},{"../client/scroll.js":41}],203:[function(require,module,exports){ +module.exports = function(id) { + if (id) { + d3.selectAll("div#d3plus_tooltip_curtain_" + id).remove(); + return d3.selectAll("div#d3plus_tooltip_id_" + id).remove(); + } else { + d3.selectAll("div.d3plus_tooltip_curtain").remove(); + return d3.selectAll("div.d3plus_tooltip").remove(); + } +}; + + +},{}],204:[function(require,module,exports){ +module.exports = function(arr, n) { + var buckets, step; + buckets = []; + step = 1 / (n - 1) * (arr[1] - arr[0]); + return d3.range(arr[0], arr[1] + step, step); +}; + + +},{}],205:[function(require,module,exports){ +var d3selection; + +d3selection = require("./d3selection.coffee"); + +module.exports = function(parent, child) { + var node; + if (!parent || !child) { + return false; + } + if (d3selection(parent)) { + parent = parent.node(); + } + if (d3selection(parent)) { + child = child.node(); + } + node = child.parentNode; + while (node !== null) { + if (node === parent) { + return true; + } + node = node.parentNode; + } + return false; +}; + + +},{"./d3selection.coffee":208}],206:[function(require,module,exports){ +module.exports = function(arr, value) { + var closest, i; + if (value.constructor === String) { + i = arr.indexOf(value); + if (i > -1) { + return arr[i]; + } else { + return arr[0]; + } + } + closest = arr[0]; + arr.forEach(function(p) { + if (Math.abs(value - p) < Math.abs(value - closest)) { + return closest = p; + } + }); + return closest; +}; + + +},{}],207:[function(require,module,exports){ +var copy, objectMerge, objectValidate; + +objectMerge = require("../object/merge.coffee"); + +objectValidate = require("../object/validate.coffee"); + +copy = function(variable) { + var ret; + if (objectValidate(variable)) { + return objectMerge(variable); + } else if (variable instanceof Array) { + ret = []; + variable.forEach(function(o) { + return ret.push(copy(o)); + }); + return ret; + } else { + return variable; + } +}; + +module.exports = copy; + + +},{"../object/merge.coffee":171,"../object/validate.coffee":172}],208:[function(require,module,exports){ +var ie; + +ie = require("../client/ie.js"); + +module.exports = function(elem) { + if (ie) { + return typeof elem === "object" && elem instanceof Array && "size" in elem && "select" in elem; + } else { + return elem instanceof d3.selection; + } +}; + + +},{"../client/ie.js":37}],209:[function(require,module,exports){ +module.exports = function(url, callback) { + var img; + img = new Image(); + img.src = url; + img.crossOrigin = "Anonymous"; + img.onload = function() { + var canvas, context; + canvas = document.createElement("canvas"); + canvas.width = this.width; + canvas.height = this.height; + context = canvas.getContext("2d"); + context.drawImage(this, 0, 0); + callback.call(this, canvas.toDataURL("image/png")); + canvas = null; + }; +}; + + +},{}],210:[function(require,module,exports){ +var objectValidate, uniques; + +objectValidate = require("../object/validate.coffee"); + +uniques = function(data, value, fetch, vars, depth, sorted) { + var check, d, i, j, k, len, len1, len2, len3, lookups, m, v, val, vals; + if (data === void 0) { + return []; + } + if (vars && depth === void 0) { + depth = vars.id.value; + } + sorted = (true === sorted && sorted === void 0); + if (!(data instanceof Array)) { + data = [data]; + } + lookups = []; + if (value === void 0) { + return data.reduce(function(p, c) { + var lookup; + lookup = JSON.stringify(c); + if (lookups.indexOf(lookup) < 0) { + if (p.indexOf(c) < 0) { + p.push(c); + } + lookups.push(lookup); + } + return p; + }, []); + } + vals = []; + check = function(v) { + var l; + if (v !== void 0 && v !== null) { + l = JSON.stringify(v); + if (lookups.indexOf(l) < 0) { + vals.push(v); + return lookups.push(l); + } + } + }; + if (typeof fetch === "function" && vars) { + for (i = 0, len = data.length; i < len; i++) { + d = data[i]; + val = uniques(fetch(vars, d, value, depth)); + for (j = 0, len1 = val.length; j < len1; j++) { + v = val[j]; + check(v); + } + } + } else if (typeof value === "function") { + for (k = 0, len2 = data.length; k < len2; k++) { + d = data[k]; + val = value(d); + check(val); + } + } else { + for (m = 0, len3 = data.length; m < len3; m++) { + d = data[m]; + if (objectValidate(d)) { + val = d[value]; + check(val); + } + } + } + if (sorted) { + return vals.sort(function(a, b) { + return a - b; + }); + } else { + return vals; + } +}; + +module.exports = uniques; + + +},{"../object/validate.coffee":172}],211:[function(require,module,exports){ +module.exports = function(vars) { + var checkParent, i, len, ref, s; + vars.container.value.style("position", function() { + var current, remain; + current = d3.select(this).style("position"); + remain = ["absolute", "fixed"].indexOf(current) >= 0; + if (remain) { + return current; + } else { + return "relative"; + } + }); + if (vars.container.changed) { + vars.container.value.html(""); + } + ref = ["width", "height"]; + for (i = 0, len = ref.length; i < len; i++) { + s = ref[i]; + if (!vars[s].value) { + checkParent = function(element) { + var elem, val; + if (element.tagName === void 0 || ["BODY", "HTML"].indexOf(element.tagName) >= 0) { + val = window["inner" + s.charAt(0).toUpperCase() + s.slice(1)]; + elem = document !== element ? d3.select(element) : false; + if (elem) { + if (s === "width") { + val -= parseFloat(elem.style("margin-left"), 10); + val -= parseFloat(elem.style("margin-right"), 10); + val -= parseFloat(elem.style("padding-left"), 10); + val -= parseFloat(elem.style("padding-right"), 10); + } else { + val -= parseFloat(elem.style("margin-top"), 10); + val -= parseFloat(elem.style("margin-bottom"), 10); + val -= parseFloat(elem.style("padding-top"), 10); + val -= parseFloat(elem.style("padding-bottom"), 10); + } + } + return vars[s].value = val <= 20 ? vars[s].small : val; + } else { + val = parseFloat(d3.select(element).style(s), 10); + if (typeof val === "number" && val > 0) { + return vars[s].value = val; + } else if (element.tagName !== "BODY") { + return checkParent(element.parentNode); + } + } + }; + checkParent(vars.container.value.node()); + if (d3.selectAll("body > *:not(script)").size() === 1) { + d3.select("body").style("overflow", "hidden"); + } + } + } + vars.container.value.style("width", vars.width.value + "px").style("height", vars.height.value + "px"); +}; + + +},{}],212:[function(require,module,exports){ +var dataFormat = require("../../core/data/format.js"), + dataColor = require("../../core/data/color.js"), + dataKeys = require("../../core/data/keys.coffee"), + dataLoad = require("../../core/data/load.coffee"), + drawDrawer = require("./ui/drawer.js"), + drawLegend = require("./ui/legend.js"), + drawTimeline = require("./ui/timeline.coffee"), + errorCheck = require("./errorCheck.js"), + fetchData = require("../../core/fetch/data.js"), + finish = require("./finish.js"), + focusTooltip = require("./focus/tooltip.coffee"), + history = require("./ui/history.coffee"), + parseEdges = require("../../core/parse/edges.js"), + parseNodes = require("../../core/parse/nodes.js"), + print = require("../../core/console/print.coffee"), + removeTooltip = require("../../tooltip/remove.coffee"), + runType = require("./types/run.coffee"), + shapes = require("./shapes/draw.js"), + stringFormat = require("../../string/format.js"), + svgSetup = require("./svg/enter.js"), + svgUpdate = require("./svg/update.js"), + titles = require("./ui/titles.js"), + validObject = require("../../object/validate.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Calculate steps needed to redraw the visualization +//------------------------------------------------------------------------------ +module.exports = function(vars) { + + var steps = [] + , appType = vars.type.value + , locale = vars.format.locale.value + , uiMessage = locale.message.ui + , drawMessage = locale.message.draw + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check to see if any data needs to be loaded with JSON + //---------------------------------------------------------------------------- + var urlLoads = [ "data" , "attrs" , "coords" , "nodes" , "edges" ] + urlLoads.forEach(function(u){ + + if (!vars.error.value && !vars[u].loaded && vars[u].url) { + + steps.push({ + "function": function( vars , next ){ + dataLoad( vars , u , next ) + }, + "message": locale.message.loading, + "wait": true + }) + + } + + }) + + if (vars.draw.update) { + + var appName = locale.visualization[appType] || appType + , appSetup = vars.types[appType].setup || false + , appReqs = vars.types[appType].requirements || [] + , appMessage = stringFormat(locale.message.initializing,appName) + , dataMessage = locale.message.data + + if (!(appReqs instanceof Array)) appReqs = [appReqs] + appName = appName.toLowerCase() + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If it has one, run the current app's setup function. + //-------------------------------------------------------------------------- + if (!vars.error.value && typeof appSetup === "function") { + + steps.push({ + "function": function( vars ) { + + if ( vars.dev.value ) { + var timerString = "running " + appName + " setup" + print.time( timerString ) + } + + appSetup( vars ) + + if ( vars.dev.value ) print.timeEnd( timerString ) + + }, + "message": appMessage + }) + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create SVG group elements if the container is new or has changed + //-------------------------------------------------------------------------- + if (vars.container.changed) { + + steps.push({ "function" : svgSetup , "message" : appMessage }) + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create group for current app, if it doesn't exist. + //-------------------------------------------------------------------------- + if (!(appType in vars.g.apps)) { + + steps.push({ + "function": function( vars ) { + + if ( vars.dev.value ) { + var timerString = "creating " + appName + " group" + print.time( timerString ) + } + + vars.g.apps[appType] = vars.g.app.append("g") + .attr("id", appType) + .attr("opacity", 0); + + if ( vars.dev.value ) print.timeEnd( timerString ) + + }, + "message": appMessage + }) + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If new data is detected, analyze and reset it. + //-------------------------------------------------------------------------- + if (vars.data.changed) { + + steps.push({ + "function": function(vars) { + vars.data.cache = {} + delete vars.nodes.restricted + delete vars.edges.restricted + dataKeys(vars, "data") + }, + "message": dataMessage + }) + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If new attributes are detected, analyze them. + //-------------------------------------------------------------------------- + if (vars.attrs.changed) { + + steps.push({ + "function": function( vars ) { + dataKeys(vars, "attrs") + }, + "message": dataMessage + }) + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Determine color type + //-------------------------------------------------------------------------- + steps.push({ + "function": function(vars) { + + if (!vars.color.type || vars.color.changed || vars.data.changed || + vars.attrs.changed || vars.id.changed || vars.depth.changed || + vars.id.solo.changed || + (!vars.time.fixed.value && (vars.time.solo.changed || vars.time.mute.changed))) { + + vars.color.valueScale = false; + + if ( vars.dev.value ) { + var timerString = "checking color type"; + print.time(timerString); + } + + vars.color.type = false; + + if (vars.color.value) { + + var colorKey = vars.color.value; + + if ( validObject(colorKey) ) { + if (colorKey[vars.id.value]) { + colorKey = colorKey[vars.id.value]; + } + else { + colorKey = colorKey[d3.keys(colorKey)[0]]; + } + } + + if (vars.data.keys && colorKey in vars.data.keys) { + vars.color.type = vars.data.keys[colorKey]; + } + else if (vars.attrs.keys && colorKey in vars.attrs.keys) { + vars.color.type = vars.attrs.keys[colorKey]; + } + + } + else if (vars.data.keys) { + vars.color.type = vars.data.keys[vars.id.value]; + } + + if (vars.dev.value) print.timeEnd(timerString); + + } + + }, + "message": dataMessage + }) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Format nodes/edges if needed + //-------------------------------------------------------------------------- + if ( appReqs.indexOf("edges") >= 0 && vars.edges.value + && ( !vars.edges.linked || vars.edges.changed ) ) { + steps.push({ "function" : parseEdges, "message" : dataMessage }) + } + + if ( appReqs.indexOf("nodes") >= 0 && vars.edges.value + && ( !vars.nodes.positions || vars.nodes.changed || vars.type.changed ) ) { + steps.push({ "function" : parseNodes , "message" : dataMessage }) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Groups data by time and nesting. + //-------------------------------------------------------------------------- + if (vars.data.changed || vars.time.changed || vars.time.format.changed || vars.type.changed || vars.id.changed || (vars.x.scale.changed && [vars.x.scale.value, vars.x.scale.previous].indexOf("discrete") >= 0) || (vars.y.scale.changed && [vars.y.scale.value, vars.y.scale.previous].indexOf("discrete") >= 0)) { + steps.push({ "function" : dataFormat , "message" : dataMessage }) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Fetches data for app and "pool" + //-------------------------------------------------------------------------- + if (!vars.error.value) { + steps.push({ + "function": function(vars) { + + var year = vars.time.fixed.value ? ["all"] : null + if (vars.dev.value) { + var timerString = year ? "fetching pool data" : "fetching data" + print.time( timerString ) + } + vars.data.pool = fetchData( vars , year ) + if (vars.dev.value) print.timeEnd( timerString ) + if ( !year ) { + vars.data.viz = vars.data.pool + } + else { + if ( vars.dev.value ) print.time("fetching data for current year") + vars.data.viz = fetchData( vars ) + if ( vars.dev.value ) print.timeEnd("fetching data for current year") + } + + vars.draw.timing = vars.data.viz.length < vars.data.large ? + vars.timing.transitions : 0; + + }, + "message": dataMessage + }) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Calculate color scale if type is number + //-------------------------------------------------------------------------- + if (!vars.error.value) { + steps.push({ + "check": function(vars) { + + return vars.color.value && vars.color.type === "number" && + vars.color.valueScale === false + + }, + "function": dataColor, + "message": dataMessage + }) + + } + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Remove any lingering tooltips. + //---------------------------------------------------------------------------- + steps.push({ + "function": function(vars) { + if ( vars.dev.value ) { + var str = vars.format.locale.value.message.tooltipReset + print.time(str) + } + if ( vars.type.previous && appType !== vars.type.previous ) { + removeTooltip(vars.type.previous) + } + removeTooltip(appType) + if ( vars.dev.value ) print.timeEnd(str) + }, + "message": uiMessage + }) + + if (!vars.error.value) { + steps.push({"function": errorCheck, "message": uiMessage}) + } + + steps.push({ + "function": function(vars) { + + vars.margin.process() + titles(vars) + + if (!vars.error.value) { + if (vars.draw.update) { + + drawDrawer(vars) + drawTimeline(vars) + drawLegend(vars) + + } + else { + + if ( vars.dev.value ) print.time("calculating margins") + + var drawer = vars.container.value.select("div#d3plus_drawer").node().offsetHeight + || vars.container.value.select("div#d3plus_drawer").node().getBoundingClientRect().height + + var timeline = vars.g.timeline.node().getBBox() + timeline = vars.timeline.value ? timeline.height+vars.ui.padding : 0 + + var legend = vars.g.legend.node().getBBox() + legend = vars.legend.value ? legend.height+vars.ui.padding : 0 + + vars.margin.bottom += drawer+timeline+legend + + if ( vars.dev.value ) print.timeEnd("calculating margins") + + } + } + + history(vars) + vars.height.viz -= (vars.margin.top+vars.margin.bottom) + vars.width.viz -= (vars.margin.left+vars.margin.right) + + }, + "message": uiMessage + }) + + if (!vars.error.value) { + steps.push({ + "function": focusTooltip, + "message": uiMessage + }) + } + + steps.push({ + "function": svgUpdate, + "message": drawMessage + }) + + if (!vars.error.value && vars.draw.update) { + steps.push({ + "function" : [ runType, shapes ], + "message" : drawMessage + }) + } + + steps.push({ + "function" : finish, + "message" : drawMessage + }) + + return steps + +} + +},{"../../core/console/print.coffee":52,"../../core/data/color.js":54,"../../core/data/format.js":56,"../../core/data/keys.coffee":58,"../../core/data/load.coffee":59,"../../core/fetch/data.js":64,"../../core/parse/edges.js":95,"../../core/parse/nodes.js":98,"../../object/validate.coffee":172,"../../string/format.js":173,"../../tooltip/remove.coffee":203,"./errorCheck.js":213,"./finish.js":214,"./focus/tooltip.coffee":215,"./shapes/draw.js":225,"./svg/enter.js":238,"./svg/update.js":239,"./types/run.coffee":242,"./ui/drawer.js":243,"./ui/history.coffee":244,"./ui/legend.js":245,"./ui/timeline.coffee":247,"./ui/titles.js":248}],213:[function(require,module,exports){ +var fetchText = require("../../core/fetch/text.js"), + print = require("../../core/console/print.coffee"), + rejected = require("../../core/methods/rejected.coffee"), + stringFormat = require("../../string/format.js"), + stringList = require("../../string/list.coffee") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Miscellaneous Error Checks +//------------------------------------------------------------------------------ +module.exports = function(vars) { + + if ( vars.dev.value ) print.time("checking for errors") + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check to see if we have all required variables set + //---------------------------------------------------------------------------- + var reqs = ["id"] + , app_reqs = vars.types[vars.type.value].requirements + if (app_reqs) { + if (!(app_reqs instanceof Array)) reqs.push(app_reqs) + else reqs = reqs.concat(vars.types[vars.type.value].requirements) + } + + var missing = [] + reqs.forEach(function(r){ + if (typeof r === "string") { + if (!vars[r].value) missing.push("\""+r+"\"") + } + else if (typeof r === "function") { + var reqReturn = r(vars) + if (!reqReturn.status && reqReturn.text) { + missing.push("\""+reqReturn.text+"\"") + } + } + }) + + if ( missing.length > 1 ) { + var str = vars.format.locale.value.error.methods + , app = vars.format.locale.value.visualization[vars.type.value] || vars.type.value + , and = vars.format.locale.value.ui.and + missing = stringList(missing,and) + vars.error.internal = stringFormat(str,app,missing) + } + else if ( missing.length === 1 ) { + var str = vars.format.locale.value.error.method + , app = vars.format.locale.value.visualization[vars.type.value] || vars.type.value + vars.error.internal = stringFormat(str,app,missing[0]) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check to see if we have focus connections, if needed + //---------------------------------------------------------------------------- + if (!vars.error.internal && reqs.indexOf("edges") >= 0 && reqs.indexOf("focus") >= 0) { + var connections = vars.edges.connections(vars.focus.value[0],vars.id.value) + if (connections.length == 0) { + var name = fetchText(vars,vars.focus.value[0],vars.depth.value) + , str = vars.format.locale.value.error.connections + vars.error.internal = stringFormat(str,"\""+name+"\"") + } + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check to see if we have all required libraries + //---------------------------------------------------------------------------- + var reqs = ["d3"] + if (vars.types[vars.type.value].libs) { + reqs = reqs.concat(vars.types[vars.type.value].libs) + } + var missing = [] + reqs.forEach(function(r){ + if (!window[r]) missing.push("\""+r+"\"") + }) + + if ( missing.length > 1 ) { + var str = vars.format.locale.value.error.libs + , app = vars.format.locale.value.visualization[vars.type.value] + , and = vars.format.locale.value.ui.and + missing = stringList(missing,and) + vars.error.internal = stringFormat(str,app,missing) + } + else if ( missing.length === 1 ) { + var str = vars.format.locale.value.error.lib + , app = vars.format.locale.value.visualization[vars.type.value] + vars.error.internal = stringFormat(str,app,missing[0]) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check to see if the requested app supports the set shape + //---------------------------------------------------------------------------- + var shapes = vars.shape.accepted(vars); + if (!(shapes instanceof Array)) shapes = [shapes] + var shape = vars.shape.value; + + if (!shape || rejected(vars, shapes, shape, "shape")) { + vars.self.shape(shapes[0]); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check to see if the requested app supports the set "mode" + //---------------------------------------------------------------------------- + if ("modes" in vars.types[vars.type.value]) { + + var modes = vars.types[vars.type.value].modes + if (!(modes instanceof Array)) modes = [modes] + var mode = vars.type.mode.value + + if (!mode || rejected(vars, modes, mode, "mode")) { + vars.self.type({"mode": modes[0]}) + } + + } + + if ( vars.dev.value ) print.timeEnd("checking for errors") + +} + +},{"../../core/console/print.coffee":52,"../../core/fetch/text.js":66,"../../core/methods/rejected.coffee":91,"../../string/format.js":173,"../../string/list.coffee":174}],214:[function(require,module,exports){ +var edges = require("./shapes/edges.js"), + paths = require("./shapes/paths.js"), + flash = require("./ui/message.js"), + focusViz = require("./focus/viz.js"), + methodReset = require("../../core/methods/reset.coffee"), + print = require("../../core/console/print.coffee"), + shapeLabels = require("./shapes/labels.js"), + titleCase = require("../../string/title.coffee") + +var bounds = require("./zoom/bounds.coffee") +var labels = require("./zoom/labels.coffee") +var mouse = require("./zoom/mouse.coffee") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Finalize Visualization +//------------------------------------------------------------------------------ +module.exports = function(vars) { + + // Highlight focus nodes/edges + if (vars.draw.first) { + setTimeout(function(){ + focusViz(vars); + }, vars.draw.timing); + } + else { + focusViz(vars); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Zoom to fit bounds, if applicable + //---------------------------------------------------------------------------- + if (!vars.error.value) { + + var zoom = vars.zoom.viewport || vars.zoom.bounds + if (vars.types[vars.type.value].zoom && vars.zoom.value && zoom) { + + if ( vars.dev.value ) print.time("calculating zoom") + + if (vars.draw.first || vars.zoom.reset) { + bounds(vars, zoom, 0); + } + else if (vars.type.changed || vars.focus.changed || vars.height.changed || vars.width.changed || vars.nodes.changed || vars.legend.changed || vars.timeline.changed || vars.ui.changed) { + bounds(vars, zoom); + } + + if ( vars.dev.value ) print.timeEnd("calculating zoom") + + } + else { + vars.zoom.bounds = [[0,0],[vars.width.viz,vars.height.viz]] + vars.zoom.scale = 1 + bounds(vars) + } + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Resize/Reposition Overlay Rect for Mouse events + //---------------------------------------------------------------------------- + var w = vars.zoom.size ? vars.zoom.size.width : vars.width.viz, + h = vars.zoom.size ? vars.zoom.size.height : vars.height.viz, + x = vars.zoom.bounds ? vars.zoom.bounds[0][0] : 0, + y = vars.zoom.bounds ? vars.zoom.bounds[0][1] : 0 + + vars.g.overlay + .attr("width",w) + .attr("height",h) + .attr("x",x) + .attr("y",y) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create labels + //---------------------------------------------------------------------------- + if (!vars.error.value) { + if (vars.draw.update) { + if (vars.edges.path) { + paths(vars); + } + else { + edges(vars); + } + // if (vars.draw.timing || (!vars.types[vars.type.value].zoom && !vars.draw.timing)) { + shapeLabels(vars, "data"); + if (vars.edges.label && !vars.edges.path) { + setTimeout(function(){ + shapeLabels(vars, "edges"); + }, vars.draw.timing + 200); + } + // } + } + else if ((vars.labels.value || vars.labels.changed) && vars.types[vars.type.value].zoom && vars.zoom.value && vars.draw.timing) { + setTimeout(function(){ + labels(vars) + },vars.draw.timing) + } + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check for Errors + //---------------------------------------------------------------------------- + if (!vars.error.value) { + var reqs = vars.types[vars.type.value].requirements || [] + if (!(reqs instanceof Array)) reqs = [reqs] + var data_req = reqs.indexOf("data") >= 0 + if (!vars.error.internal) { + if ((!vars.data.viz || !vars.returned.nodes.length) && data_req) { + vars.error.internal = vars.format.locale.value.error.data + } + } + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Hide the previous app, if applicable + //---------------------------------------------------------------------------- + var prev = vars.type.previous + if (prev && vars.type.value != prev && vars.g.apps[prev]) { + if ( vars.dev.value ) print.time("hiding \"" + prev + "\"") + if (vars.draw.timing) { + vars.g.apps[prev].transition().duration(vars.draw.timing) + .attr("opacity",0) + } + else { + vars.g.apps[prev].attr("opacity",0) + } + if ( vars.dev.value ) print.timeEnd() + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Show the current app, data, and edges groups + //---------------------------------------------------------------------------- + if (!vars.error.value) { + var new_opacity = (data_req && vars.data.viz.length === 0) || + vars.error.internal || vars.error.value ? 0 : vars.focus.value.length && + vars.types[vars.type.value].zoom && vars.zoom.value ? + 1 - vars.tooltip.curtain.opacity : 1; + + var timing = vars.draw.timing; + + vars.group.transition().duration(timing) + .attr("opacity",new_opacity); + + vars.g.data.transition().duration(timing) + .attr("opacity",new_opacity); + + vars.g.edges.transition().duration(timing) + .attr("opacity",new_opacity); + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Display and reset internal_error, if applicable + //---------------------------------------------------------------------------- + if (vars.error.value) { + flash(vars, vars.error.value); + } + else if (vars.error.internal) { + vars.error.internal = titleCase(vars.error.internal); + print.warning(vars.error.internal); + flash(vars, vars.error.internal); + vars.error.internal = null; + } + else { + flash(vars); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Unfreeze controls and apply zoom behavior, if applicable + //---------------------------------------------------------------------------- + setTimeout(function(){ + + methodReset( vars ) + + if (vars.types[vars.type.value].zoom && vars.zoom.value) { + vars.g.zoom + .datum(vars) + .call(vars.zoom.behavior.on("zoom",mouse)) + if (!vars.zoom.scroll.value) { + vars.g.zoom + .on("mousewheel.zoom",null) + .on("MozMousePixelScroll.zoom",null) + .on("wheel.zoom",null) + } + if (!vars.zoom.click.value) { + vars.g.zoom.on("dblclick.zoom",null) + } + if (!vars.zoom.pan.value) { + vars.g.zoom + .on("mousedown.zoom",null) + .on("mousemove.zoom",null) + } + } + else { + vars.g.zoom + .call(vars.zoom.behavior.on("zoom",null)) + .on("dblclick.zoom",null) + .on("mousedown.zoom",null) + .on("mousemove.zoom",null) + .on("mousewheel.zoom",null) + .on("MozMousePixelScroll.zoom",null) + .on("touchstart.zoom",null) + .on("wheel.zoom",null) + } + + },vars.draw.timing) + +} + +},{"../../core/console/print.coffee":52,"../../core/methods/reset.coffee":93,"../../string/title.coffee":176,"./focus/viz.js":216,"./shapes/edges.js":226,"./shapes/labels.js":228,"./shapes/paths.js":230,"./ui/message.js":246,"./zoom/bounds.coffee":249,"./zoom/labels.coffee":251,"./zoom/mouse.coffee":252}],215:[function(require,module,exports){ +var createTooltip, fetchValue, print, removeTooltip; + +createTooltip = require("../tooltip/create.js"); + +fetchValue = require("../../../core/fetch/value.coffee"); + +print = require("../../../core/console/print.coffee"); + +removeTooltip = require("../../../tooltip/remove.coffee"); + +module.exports = function(vars) { + var data, focus, offset; + focus = vars.focus; + if (!vars.error.internal && focus.value.length === 1 && focus.value.length && !vars.small && focus.tooltip.value) { + if (vars.dev.value) { + print.time("drawing focus tooltip"); + } + data = vars.data.pool.filter(function(d) { + return fetchValue(vars, d, vars.id.value) === focus.value[0]; + }); + if (data.length >= 1) { + data = data[0]; + } else { + data = {}; + data[vars.id.value] = focus.value[0]; + } + offset = vars.labels.padding; + createTooltip({ + anchor: "top left", + arrow: false, + data: data, + fullscreen: false, + id: "visualization_focus", + length: "long", + maxheight: vars.height.viz - offset * 2, + mouseevents: true, + offset: 0, + vars: vars, + width: vars.tooltip.large, + x: vars.width.value - vars.margin.right - offset, + y: vars.margin.top + offset + }); + vars.width.viz -= vars.tooltip.large + offset * 2; + if (vars.dev.value) { + print.timeEnd("drawing focus tooltip"); + } + } else { + removeTooltip("visualization_focus"); + } +}; + + +},{"../../../core/console/print.coffee":52,"../../../core/fetch/value.coffee":67,"../../../tooltip/remove.coffee":203,"../tooltip/create.js":240}],216:[function(require,module,exports){ +var events = require("../../../client/pointer.coffee"), + ie = require("../../../client/ie.js"), + fetchValue = require("../../../core/fetch/value.coffee"), + print = require("../../../core/console/print.coffee"), + uniqueValues = require("../../../util/uniques.coffee") + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates focus elements, if available +//------------------------------------------------------------------------------ +module.exports = function(vars) { + + vars.g.edge_focus + .selectAll("g") + .remove() + + vars.g.data_focus + .selectAll("g") + .remove() + + if (vars.focus.value.length && vars.types[vars.type.value].zoom && vars.zoom.value) { + + if ( vars.dev.value ) print.time("drawing focus elements") + + var edges = vars.g.edges.selectAll("g") + + if (edges.size() > 0) { + + edges.each(function(l){ + + var source = l[vars.edges.source][vars.id.value], + target = l[vars.edges.target][vars.id.value] + + if (source == vars.focus.value[0] || target == vars.focus.value[0]) { + var elem = vars.g.edge_focus.node().appendChild(this.cloneNode(true)) + d3.select(elem).datum(l).attr("opacity",1) + .selectAll("line, path").datum(l) + } + + }) + + + var marker = vars.edges.arrows.value + + vars.g.edge_focus.selectAll("line, path") + .attr("vector-effect","non-scaling-stroke") + .style("stroke",vars.color.focus) + .style("stroke-width",function(){ + if (ie && vars.types[vars.type.value].zoom) return 0; + return vars.edges.size.value ? d3.select(this).style("stroke-width") + : vars.data.stroke.width*2 + }) + .attr("marker-start",function(e){ + + var direction = vars.edges.arrows.direction.value + + if ("bucket" in e.d3plus) { + var d = "_"+e.d3plus.bucket + } + else { + var d = "" + } + + return direction == "source" && marker + ? "url(#d3plus_edge_marker_focus"+d+")" : "none" + + }) + .attr("marker-end",function(e){ + + var direction = vars.edges.arrows.direction.value + + if ("bucket" in e.d3plus) { + var d = "_"+e.d3plus.bucket + } + else { + var d = "" + } + + return direction == "target" && marker + ? "url(#d3plus_edge_marker_focus"+d+")" : "none" + + }) + + vars.g.edge_focus.selectAll("text") + .style("fill",vars.color.focus) + + } + + var focii = uniqueValues(vars.edges.connections(vars.focus.value[0],vars.id.value,true),vars.id.value, fetchValue, vars) + focii.push(vars.focus.value[0]) + + var x_bounds = [], y_bounds = [], x_buffer = [0], y_buffer = [0] + + var groups = vars.g.data.selectAll("g") + .each(function(d){ + if (focii.indexOf(d[vars.id.value]) >= 0) { + var elem = vars.g.data_focus.node().appendChild(this.cloneNode(true)) + var elem = d3.select(elem).datum(d).attr("opacity",1) + + if (vars.shape.value == "coordinates") { + + vars.zoom.viewport = vars.path.bounds(vars.zoom.coords[d.d3plus.id]) + + } + else if ("d3plus" in d) { + if ("x" in d.d3plus) { + x_bounds.push(d.d3plus.x) + } + if ("y" in d.d3plus) { + y_bounds.push(d.d3plus.y) + } + if ("r" in d.d3plus) { + x_buffer.push(d.d3plus.r) + y_buffer.push(d.d3plus.r) + } + else { + if ("width" in d.d3plus) { + x_buffer.push(d.d3plus.width/2) + } + if ("height" in d.d3plus) { + y_buffer.push(d.d3plus.height/2) + } + } + } + + for (e in events) { + var evt = d3.select(this).on(events[e]) + if (evt) { + elem.on(events[e],evt) + } + } + + } + }) + + if (x_bounds.length && y_bounds.length) { + + var xcoords = d3.extent(x_bounds), + ycoords = d3.extent(y_bounds), + xmax = d3.max(x_buffer), + ymax = d3.max(y_buffer) + + vars.zoom.viewport = [ + [xcoords[0]-xmax,ycoords[0]-ymax], + [xcoords[1]+xmax,ycoords[1]+ymax] + ] + + } + + vars.g.data_focus.selectAll("path") + .style("stroke-width", ie && vars.types[vars.type.value].zoom ? + 0 : vars.data.stroke.width * 2); + + if ( vars.dev.value ) print.timeEnd("drawing focus elements") + + } + else { + vars.zoom.viewport = false + } + +} + +},{"../../../client/ie.js":37,"../../../client/pointer.coffee":38,"../../../core/console/print.coffee":52,"../../../core/fetch/value.coffee":67,"../../../util/uniques.coffee":210}],217:[function(require,module,exports){ +var angles, largestRect, path2poly, shapeStyle; + +shapeStyle = require("./style.coffee"); + +largestRect = require("../../../geom/largestRect.coffee"); + +path2poly = require("../../../geom/path2poly.coffee"); + +angles = { + start: {}, + end: {} +}; + +module.exports = function(vars, selection, enter, exit) { + var arc, arcTween, data, newarc; + arc = d3.svg.arc().innerRadius(0).outerRadius(function(d) { + return d.d3plus.r; + }).startAngle(function(d) { + return d.d3plus.startAngle; + }).endAngle(function(d) { + return d.d3plus.endAngle; + }); + data = function(d) { + var poly, rect; + if (vars.labels.value) { + if (d.d3plus.label) { + d.d3plus_label = d.d3plus.label; + } else { + poly = path2poly(arc(d)); + rect = largestRect(poly, { + angle: 0 + }); + if (rect[0]) { + d.d3plus_label = { + w: rect[0].width, + h: rect[0].height, + x: rect[0].cx, + y: rect[0].cy + }; + } else { + delete d.d3plus_label; + } + } + } + return [d]; + }; + if (vars.draw.timing) { + newarc = d3.svg.arc().innerRadius(0).outerRadius(function(d) { + return d.d3plus.r; + }).startAngle(function(d) { + if (angles.start[d.d3plus.id] === void 0) { + angles.start[d.d3plus.id] = 0; + } + if (isNaN(angles.start[d.d3plus.id])) { + angles.start[d.d3plus.id] = d.d3plus.startAngle; + } + return angles.start[d.d3plus.id]; + }).endAngle(function(d) { + if (angles.end[d.d3plus.id] === void 0) { + angles.end[d.d3plus.id] = 0; + } + if (isNaN(angles.end[d.d3plus.id])) { + angles.end[d.d3plus.id] = d.d3plus.endAngle; + } + return angles.end[d.d3plus.id]; + }); + arcTween = function(arcs, newAngle) { + return arcs.attrTween("d", function(d) { + var e, interpolateE, interpolateS, s; + if (newAngle === void 0) { + s = d.d3plus.startAngle; + e = d.d3plus.endAngle; + } else if (newAngle === 0) { + s = 0; + e = 0; + } + interpolateS = d3.interpolate(angles.start[d.d3plus.id], s); + interpolateE = d3.interpolate(angles.end[d.d3plus.id], e); + return function(t) { + angles.start[d.d3plus.id] = interpolateS(t); + angles.end[d.d3plus.id] = interpolateE(t); + return newarc(d); + }; + }); + }; + enter.append("path").attr("class", "d3plus_data").call(shapeStyle, vars).attr("d", newarc); + selection.selectAll("path.d3plus_data").data(data).transition().duration(vars.draw.timing).call(shapeStyle, vars).call(arcTween); + exit.selectAll("path.d3plus_data").transition().duration(vars.draw.timing).call(arcTween, 0); + } else { + enter.append("path").attr("class", "d3plus_data"); + selection.selectAll("path.d3plus_data").data(data).call(shapeStyle, vars).attr("d", arc); + } +}; + + +},{"../../../geom/largestRect.coffee":160,"../../../geom/path2poly.coffee":162,"./style.coffee":234}],218:[function(require,module,exports){ +var fetchText = require("../../../core/fetch/text.js"), + fontSizes = require("../../../font/sizes.coffee"), + largestRect = require("../../../geom/largestRect.coffee"), + shapeStyle = require("./style.coffee"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "square" and "circle" shapes using svg:rect +//------------------------------------------------------------------------------ +module.exports = function(vars, selection, enter, exit) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // D3 area definition + //---------------------------------------------------------------------------- + var area = d3.svg.area() + .x(function(d) { return d.d3plus.x; }) + .y0(function(d) { return d.d3plus.y0; }) + .y1(function(d) { return d.d3plus.y; }) + .interpolate(vars.shape.interpolate.value); + + var startArea = d3.svg.area() + .x(function(d) { return d.d3plus.x; }) + .y0(function(d) { return d.d3plus.y0; }) + .y1(function(d) { return d.d3plus.y0; }) + .interpolate(vars.shape.interpolate.value); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Enter + //---------------------------------------------------------------------------- + enter.append("path").attr("class","d3plus_data") + .attr("d",function(d){ return startArea(d.values); }) + .call(shapeStyle,vars); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Update + //---------------------------------------------------------------------------- + + var style = { + "font-weight": vars.labels.font.weight, + "font-family": vars.labels.font.family.value + }; + + selection.selectAll("path.d3plus_data") + .data(function(d) { + + if (vars.labels.value && d.values.length > 1) { + + var max = d3.max(d.values, function(v){ + return v.d3plus.y0 - v.d3plus.y; + }), lr = false; + + if (max > vars.labels.font.size) { + + var tops = [], bottoms = [], names = fetchText(vars, d); + + d.values.forEach(function(v){ + tops.push([v.d3plus.x,v.d3plus.y]); + bottoms.push([v.d3plus.x,v.d3plus.y0]); + }); + tops = tops.concat(bottoms.reverse()); + + var ratio = null; + if (names.length) { + var size = fontSizes(names[0],style); + ratio = size[0].width/size[0].height; + } + + lr = largestRect(tops,{ + "angle": d3.range(-70, 71, 1), + "aspectRatio": ratio, + "tolerance": 0 + }); + + } + + if (lr && lr[0]) { + + var label = { + "w": ~~(lr[0].width), + "h": ~~(lr[0].height), + "x": ~~(lr[0].cx), + "y": ~~(lr[0].cy), + "angle": lr[0].angle*-1, + "padding": 2, + "names": names + } + + if (lr[0].angle !== 0) { + label.translate = { + "x":label.x, + "y":label.y + } + } + else { + label.translate = false + } + + if (label.w >= 10 && label.h >= 10) { + d.d3plus_label = label + } + + } + + } + + return [d]; + }) + + if (vars.draw.timing) { + selection.selectAll("path.d3plus_data") + .transition().duration(vars.draw.timing) + .attr("d",function(d){ return area(d.values) }) + .call(shapeStyle,vars) + } + else { + selection.selectAll("path.d3plus_data") + .attr("d",function(d){ return area(d.values) }) + .call(shapeStyle,vars) + } + +} + +},{"../../../core/fetch/text.js":66,"../../../font/sizes.coffee":102,"../../../geom/largestRect.coffee":160,"./style.coffee":234}],219:[function(require,module,exports){ +var fetchText = require("../../../core/fetch/text.js"), + largestRect = require("../../../geom/largestRect.coffee"), + shapeStyle = require("./style.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "square" and "circle" shapes using svg:rect +//------------------------------------------------------------------------------ +module.exports = function(vars,selection,enter,exit) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialize check scale on enter and exit. + //---------------------------------------------------------------------------- + function init(paths){ + paths.attr("transform", "scale(1)") + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Change scale of check on update. + //--------------------------------------------------------------------------- + function update(paths){ + paths.attr("transform", function(d){ + var smaller_dim = Math.min(d.d3plus.width, d.d3plus.height); + var scale = Math.floor(smaller_dim / 16); + return "scale("+scale+")"; + }) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Enter + //---------------------------------------------------------------------------- + enter.append("path").attr("class","d3plus_data") + .attr("d", "M5-6.844L3.594-5.407L-2,0.188l-1.594-1.594L-5-2.844L-7.844,0l1.438,1.406l3,3L-2,5.843l1.406-1.438l7-7L7.844-4L5-6.844z") + .call(init) + .call(shapeStyle,vars) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Update + //---------------------------------------------------------------------------- + selection.selectAll("path.d3plus_data") + .data(function(d) { + return [d]; + }) + + if (vars.draw.timing) { + selection.selectAll("path.d3plus_data") + .transition().duration(vars.draw.timing) + .call(update) + .call(shapeStyle,vars) + } + else { + selection.selectAll("path.d3plus_data") + .call(update) + .call(shapeStyle,vars) + } + +} + +},{"../../../core/fetch/text.js":66,"../../../geom/largestRect.coffee":160,"./style.coffee":234}],220:[function(require,module,exports){ +var fetchColor, fetchValue, lighter, segments; + +fetchValue = require("../../../core/fetch/value.coffee"); + +fetchColor = require("../../../core/fetch/color.coffee"); + +lighter = require("../../../color/lighter.coffee"); + +segments = require("./segments.coffee"); + +module.exports = function(d, vars, stroke) { + var active, shape, temp, total; + shape = d.d3plus.shape || vars.shape.value; + if (vars.shape.value === "line" && shape !== "circle") { + return "none"; + } else if (vars.shape.value === "area" || shape === "active" || vars.shape.value === "line") { + return fetchColor(vars, d); + } else if (shape === "temp") { + if (stroke) { + return fetchColor(vars, d); + } else { + return "url(#d3plus_hatch_" + d.d3plus.id + ")"; + } + } else if (d.d3plus["static"]) { + return lighter(fetchColor(vars, d), .75); + } + active = segments(vars, d, "active"); + temp = segments(vars, d, "temp"); + total = segments(vars, d, "total"); + if ((!vars.active.value && !vars.temp.value) || active === true || (active && total && active >= total && !temp) || (active && !total)) { + return fetchColor(vars, d); + } else if (vars.active.spotlight.value) { + return vars.color.missing; + } else { + return lighter(fetchColor(vars, d), .75); + } +}; + + +},{"../../../color/lighter.coffee":45,"../../../core/fetch/color.coffee":63,"../../../core/fetch/value.coffee":67,"./segments.coffee":233}],221:[function(require,module,exports){ +var copy, distance, fetchText, fontSizes, labels, largestRect, path2poly, shapeStyle; + +copy = require("../../../util/copy.coffee"); + +distance = require("../../../network/distance.coffee"); + +fetchText = require("../../../core/fetch/text.js"); + +fontSizes = require("../../../font/sizes.coffee"); + +largestRect = require("../../../geom/largestRect.coffee"); + +path2poly = require("../../../geom/path2poly.coffee"); + +shapeStyle = require("./style.coffee"); + +labels = {}; + +module.exports = function(vars, selection, enter, exit) { + var projection, size_change; + projection = d3.geo[vars.coords.projection.value](); + if (projection.center) { + projection.center(vars.coords.center); + } + if (!vars.zoom.scale) { + vars.zoom.scale = 1; + } + vars.zoom.area = 1 / vars.zoom.scale / vars.zoom.scale; + vars.path = d3.geo.path().projection(projection); + if (vars.draw.timing) { + selection.selectAll("path.d3plus_data").attr("d", vars.path).transition().duration(vars.draw.timing).call(shapeStyle, vars); + } else { + selection.selectAll("path.d3plus_data").attr("d", vars.path).call(shapeStyle, vars); + } + enter.append("path").attr("id", function(d) { + return d.id; + }).attr("class", "d3plus_data").attr("d", vars.path).call(shapeStyle, vars); + size_change = vars.old_height !== vars.height.viz || vars.height.changed || vars.old_width !== vars.width.viz || vars.width.changed; + vars.old_height = vars.height.viz; + vars.old_width = vars.width.viz; + if (vars.coords.changed || size_change || vars.coords.mute.changed || vars.coords.solo.changed || vars.type.changed || vars.text.changed || vars.coords.projection.changed || vars.labels.changed) { + vars.zoom.bounds = null; + vars.zoom.reset = true; + vars.zoom.coords = {}; + return selection.each(function(d) { + var areaM, areas, b, c, center, coords, dist_cutoff, dist_values, distances, i, j, largest, len, names, path, ratio, rect, reduced, ref, size, style; + if (vars.coords.simplify.value && d.geometry.coordinates.length > 1) { + distances = []; + areas = []; + areaM = 0; + largest = copy(d); + reduced = copy(d); + d.geometry.coordinates = d.geometry.coordinates.filter(function(c, i) { + var a; + reduced.geometry.coordinates = [c]; + a = vars.path.area(reduced); + if (a > 0) { + areas.push(a); + if (a > areaM) { + largest.geometry.coordinates = [c]; + areaM = a; + } + return true; + } else { + return false; + } + }); + center = vars.path.centroid(largest); + ref = d.geometry.coordinates; + for (i = j = 0, len = ref.length; j < len; i = ++j) { + c = ref[i]; + reduced.geometry.coordinates = [c]; + distances.push(distance(vars.path.centroid(reduced), center)); + } + dist_values = distances.reduce(function(arr, dist, i) { + if (dist) { + arr.push(areas[i] / dist); + } + return arr; + }, []); + dist_cutoff = d3.quantile(dist_values, vars.coords.threshold.value); + reduced.geometry.coordinates = d.geometry.coordinates.filter(function(c, i) { + var a, dist; + dist = distances[i]; + a = areas[i]; + return dist === 0 || a / dist >= dist_cutoff; + }); + coords = largest.geometry.coordinates[0]; + if (coords && largest.geometry.type === "MultiPolygon") { + coords = coords[0]; + largest.geometry.coordinates[0] = coords; + largest.geometry.type = "Polygon"; + } + } else { + reduced = d; + largest = d; + coords = d.geometry.coordinates[0]; + } + vars.zoom.coords[d.d3plus.id] = reduced; + delete d.d3plus_label; + if (vars.labels.value) { + names = fetchText(vars, d); + if (coords && names.length) { + path = path2poly(vars.path(largest)); + style = { + "font-weight": vars.labels.font.weight, + "font-family": vars.labels.font.family.value + }; + ratio = null; + if (names[0].split(" ").length === 1) { + size = fontSizes(names[0], style)[0]; + ratio = size.width / size.height; + } + rect = largestRect(path, { + angle: 0, + aspectRatio: ratio + }); + if (rect) { + rect = rect[0]; + d.d3plus_label = { + anchor: "middle", + valign: "center", + h: rect.height, + w: rect.width, + x: rect.cx, + y: rect.cy, + names: names + }; + } + } + } + labels[d.id] = d.d3plus_label; + b = vars.path.bounds(reduced); + if (!vars.zoom.bounds) { + return vars.zoom.bounds = b; + } else { + if (vars.zoom.bounds[0][0] > b[0][0]) { + vars.zoom.bounds[0][0] = b[0][0]; + } + if (vars.zoom.bounds[0][1] > b[0][1]) { + vars.zoom.bounds[0][1] = b[0][1]; + } + if (vars.zoom.bounds[1][0] < b[1][0]) { + vars.zoom.bounds[1][0] = b[1][0]; + } + if (vars.zoom.bounds[1][1] < b[1][1]) { + return vars.zoom.bounds[1][1] = b[1][1]; + } + } + }); + } else if (!vars.focus.value.length) { + vars.zoom.viewport = false; + return selection.each(function(d) { + return d.d3plus_label = labels[d.id]; + }); + } +}; + + +},{"../../../core/fetch/text.js":66,"../../../font/sizes.coffee":102,"../../../geom/largestRect.coffee":160,"../../../geom/path2poly.coffee":162,"../../../network/distance.coffee":165,"../../../util/copy.coffee":207,"./style.coffee":234}],222:[function(require,module,exports){ +var shapeStyle = require("./style.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "square" and "circle" shapes using svg:rect +//------------------------------------------------------------------------------ +module.exports = function(vars,selection,enter,exit) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialize check scale on enter and exit. + //---------------------------------------------------------------------------- + function init(paths){ + paths.attr("d", d3.svg.symbol().type("cross").size(10)) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Change scale of check on update. + //--------------------------------------------------------------------------- + function update(paths){ + paths.attr("d", d3.svg.symbol().type("cross").size(function(d){ + var smaller_dim = Math.min(d.d3plus.width, d.d3plus.height); + return d3.scale.pow().exponent(2)(smaller_dim/2); + })) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Enter + //---------------------------------------------------------------------------- + enter.append("path").attr("class","d3plus_data") + .call(init) + .call(shapeStyle,vars) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Update + //---------------------------------------------------------------------------- + selection.selectAll("path.d3plus_data") + .data(function(d) { + return [d]; + }) + + if (vars.draw.timing) { + selection.selectAll("path.d3plus_data") + .transition().duration(vars.draw.timing) + .call(update) + .call(shapeStyle,vars) + } + else { + selection.selectAll("path.d3plus_data") + .call(update) + .call(shapeStyle,vars) + } + +} + +},{"./style.coffee":234}],223:[function(require,module,exports){ +var shapeStyle = require("./style.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "square" and "circle" shapes using svg:rect +//------------------------------------------------------------------------------ +module.exports = function(vars,selection,enter,exit) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialize check scale on enter and exit. + //---------------------------------------------------------------------------- + function init(paths){ + paths.attr("d", d3.svg.symbol().type("diamond").size(10)) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Change scale of check on update. + //--------------------------------------------------------------------------- + function update(paths){ + paths.attr("d", d3.svg.symbol().type("diamond").size(function(d){ + var smaller_dim = Math.min(d.d3plus.width, d.d3plus.height); + return d3.scale.pow().exponent(2)(smaller_dim/2); + })) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Enter + //---------------------------------------------------------------------------- + enter.append("path").attr("class","d3plus_data") + .call(init) + .call(shapeStyle,vars) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Update + //---------------------------------------------------------------------------- + selection.selectAll("path.d3plus_data") + .data(function(d) { + return [d]; + }) + + if (vars.draw.timing) { + selection.selectAll("path.d3plus_data") + .transition().duration(vars.draw.timing) + .call(update) + .call(shapeStyle,vars) + } + else { + selection.selectAll("path.d3plus_data") + .call(update) + .call(shapeStyle,vars) + } + +} + +},{"./style.coffee":234}],224:[function(require,module,exports){ +var shapeStyle = require("./style.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "donut" shapes using svg:path with arcs +//------------------------------------------------------------------------------ +module.exports = function(vars,selection,enter,exit) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // In order to correctly animate each donut's size and arcs, we need to store + // it's previous values in a lookup object that does not get destroyed when + // redrawing the visualization. + //---------------------------------------------------------------------------- + if (!vars.arcs) { + vars.arcs = { + "donut": {}, + "active": {}, + "temp": {} + } + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // This is the main arc function that determines what values to use for each + // arc angle and radius. + //---------------------------------------------------------------------------- + var arc = d3.svg.arc() + .startAngle(0) + .endAngle(function(d){ + var a = vars.arcs[d.d3plus.shape][d.d3plus.id].a; + return a > Math.PI*2 ? Math.PI*2 : a; + }) + .innerRadius(function(d){ + if (d.d3plus.static) return 0; + var r = vars.arcs[d.d3plus.shape][d.d3plus.id].r; + return r * vars.data.donut.size; + }) + .outerRadius(function(d){ + return vars.arcs[d.d3plus.shape][d.d3plus.id].r; + }) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // This is the main "arcTween" function where all of the animation happens + // for each arc. + //---------------------------------------------------------------------------- + function size(path,mod,rad,ang) { + if (!mod) var mod = 0 + if (typeof rad != "number") var rad = undefined + if (typeof ang != "number") var ang = undefined + path.attrTween("d", function(d){ + if (rad == undefined) var r = d.d3plus.r ? d.d3plus.r : d3.max([d.d3plus.width,d.d3plus.height]) + else var r = rad + if (ang == undefined) var a = d.d3plus.segments[d.d3plus.shape] + else var a = ang + if (!vars.arcs[d.d3plus.shape][d.d3plus.id]) { + vars.arcs[d.d3plus.shape][d.d3plus.id] = {"r": 0} + vars.arcs[d.d3plus.shape][d.d3plus.id].a = Math.PI * 2 + } + var radius = d3.interpolate(vars.arcs[d.d3plus.shape][d.d3plus.id].r,r+mod), + angle = d3.interpolate(vars.arcs[d.d3plus.shape][d.d3plus.id].a,a) + return function(t) { + vars.arcs[d.d3plus.shape][d.d3plus.id].r = radius(t) + vars.arcs[d.d3plus.shape][d.d3plus.id].a = angle(t) + return arc(d) + } + }) + } + + function data(d) { + + if (d.d3plus.label) { + d.d3plus_label = d.d3plus.label; + } + else { + delete d.d3plus_label; + } + + return [d]; + } + + if (vars.draw.timing) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Exit + //---------------------------------------------------------------------------- + exit.selectAll("path.d3plus_data").transition().duration(vars.draw.timing) + .call(size,0,0) + .each("end",function(d){ + delete vars.arcs[d.d3plus.shape][d.d3plus.id]; + }); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Update + //---------------------------------------------------------------------------- + selection.selectAll("path.d3plus_data") + .data(data) + .transition().duration(vars.draw.timing) + .call(size) + .call(shapeStyle,vars); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Enter + //---------------------------------------------------------------------------- + enter.append("path") + .attr("class","d3plus_data") + .transition().duration(0) + .call(size,0,0) + .call(shapeStyle,vars) + .transition().duration(vars.draw.timing) + .call(size) + .call(shapeStyle,vars); + + } + else { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Exit + //---------------------------------------------------------------------------- + exit.selectAll("path.d3plus_data") + .each(function(d){ + delete vars.arcs[d.d3plus.shape][d.d3plus.id]; + }); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Enter + //---------------------------------------------------------------------------- + enter.append("path") + .attr("class","d3plus_data"); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Update + //---------------------------------------------------------------------------- + selection.selectAll("path.d3plus_data") + .data(data) + .call(size) + .call(shapeStyle,vars); + } + +}; + +},{"./style.coffee":234}],225:[function(require,module,exports){ +var child = require("../../../util/child.coffee"), + closest = require("../../../util/closest.coffee"), + createTooltip = require("../tooltip/create.js"), + events = require("../../../client/pointer.coffee"), + fetchValue = require("../../../core/fetch/value.coffee"), + fetchColor = require("../../../core/fetch/color.coffee"), + fetchText = require("../../../core/fetch/text.js"), + legible = require("../../../color/legible.coffee"), + print = require("../../../core/console/print.coffee"), + removeTooltip = require("../../../tooltip/remove.coffee"), + segments = require("./segments.coffee"), + shapeFill = require("./fill.js"), + stringStrip = require("../../../string/strip.js"), + touch = require("../../../client/touch.coffee"), + touchEvent = require("../zoom/propagation.coffee"), + uniqueValues = require("../../../util/uniques.coffee"), + validObject = require("../../../object/validate.coffee"), + zoomDirection = require("../zoom/direction.coffee"); + +var drawShape = { + "arc": require("./arc.coffee"), + "area": require("./area.js"), + "check": require("./check.js"), + "coordinates": require("./coordinates.coffee"), + "cross": require("./cross.js"), + "diamond": require("./diamond.js"), + "donut": require("./donut.js"), + "line": require("./line.js"), + "radial": require("./radial.coffee"), + "rect": require("./rect.coffee"), + "triangle_down": require("./triangle_down.js"), + "triangle_up": require("./triangle_up.js"), + "whisker": require("./whisker.coffee") +}; + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws the appropriate shape based on the data +//------------------------------------------------------------------------------ +module.exports = function(vars) { + + var data = vars.returned.nodes || [], + edges = vars.returned.edges || []; + + vars.draw.timing = data.length < vars.data.large && + edges.length < vars.edges.large ? + vars.timing.transitions : 0; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Match vars.shape types to their respective d3plus.shape functions. For + // example, both "square", and "circle" shapes use "rect" as their drawing + // class. + //---------------------------------------------------------------------------- + var shapeLookup = { + "arc": "arc", + "area": "area", + "check": "check", + "circle": "rect", + "coordinates": "coordinates", + "cross": "cross", + "donut": "donut", + "diamond": "diamond", + "line": "line", + "plus": "cross", + "radial": "radial", + "rect": "rect", + "square": "rect", + "triangle_down": "triangle_down", + "triangle": "triangle_up", + "triangle_up": "triangle_up", + "whisker": "whisker" + }; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Split the data by each shape type in the data. + //---------------------------------------------------------------------------- + var shapes = {}; + data.forEach(function(d){ + var s = d.d3plus && d.d3plus.shape ? d.d3plus.shape : vars.shape.value; + if (s in shapeLookup) { + if (d.d3plus) d.d3plus.shape = s + s = shapeLookup[s] + if (!shapes[s]) shapes[s] = [] + shapes[s].push(d) + } + }) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Resets the "id" of each data point to use with matching. + //---------------------------------------------------------------------------- + function id(d) { + + if (!d.d3plus.id) { + d.d3plus.id = ""; + for (var i = 0; i <= vars.depth.value; i++) { + d.d3plus.id += fetchValue(vars,d,vars.id.nesting[i])+"_" + } + + d.d3plus.id += shape; + + ["x", "y", "x2", "y2"].forEach(function(axis){ + if (vars[axis].scale.value == "discrete") { + var val = fetchValue(vars, d, vars[axis].value) + if (val.constructor === Date) val = val.getTime() + d.d3plus.id += "_"+val + } + }) + + if (d.d3plus.suffix) { + d.d3plus.id += "_" + d.d3plus.suffix; + } + + d.d3plus.id = stringStrip(d.d3plus.id) + } + + return d + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Transforms the positions and scale of each group. + //---------------------------------------------------------------------------- + function transform(g,grow) { + + var scales = vars.types[vars.type.value].scale, + scale = 1; + if (scales) { + if (validObject[scales] && vars.shape.value in scales) { + scale = scales[vars.shape.value]; + } + else if (typeof scales == "function") { + scale = scales(vars, vars.shape.value); + } + else if (typeof scales == "number") { + scale = scales; + } + } + + scale = grow ? scale : 1; + g.attr("transform", function(d){ + + if (["line", "area", "coordinates"].indexOf(shape) < 0) { + var x = d.d3plus.x || 0, y = d.d3plus.y || 0; + return "translate("+x+","+y+")scale("+scale+")"; + } + else { + return "scale("+scale+")"; + } + + }); + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Sets the class name for a group + //---------------------------------------------------------------------------- + function className(g) { + g + .attr("id", function(d){ + return "d3plus_group_" + d.d3plus.id; + }) + .attr("class", function(d){ + var c = vars.class.value ? " " + fetchValue(vars, d, vars.class.value) : ""; + return "d3plus_" + shape + c; + }); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Remove old groups + //---------------------------------------------------------------------------- + for (var s in shapeLookup) { + if (!(shapeLookup[s] in shapes) || d3.keys(shapes).length === 0) { + var oldShapes = vars.g.data.selectAll("g.d3plus_"+shapeLookup[s]); + if (vars.draw.timing) { + oldShapes + .transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove(); + } + else { + oldShapes + .remove(); + } + } + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialize arrays for labels and sizes + //---------------------------------------------------------------------------- + var labels = [], shares = []; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create groups by shape, apply data, and call specific shape drawing class. + //---------------------------------------------------------------------------- + for (var shape in shapes) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Bind Data to Groups + //-------------------------------------------------------------------------- + var selection = vars.g.data.selectAll("g.d3plus_"+shape) + .data(shapes[shape],function(d){ + + if (!d.d3plus) d.d3plus = {} + + if ( shape === "coordinates" ) { + d.d3plus.id = d.id + return d.id + } + + if ( !d.d3plus.id ) { + + if (d.values) { + + d.values.forEach(function(v){ + v = id(v) + v.d3plus.shape = "circle" + }) + d.d3plus.id = d.key + + } + else { + + d = id(d) + + if (!d.d3plus.segments) { + + d.d3plus.segments = {"donut": Math.PI*2} + var active = segments(vars, d, "active"), + temp = segments(vars, d, "temp"), + total = segments(vars, d, "total"); + + if (total) { + if (active) { + d.d3plus.segments.active = (active/total) * (Math.PI * 2) + } + else { + d.d3plus.segments.active = 0 + } + if (temp) { + d.d3plus.segments.temp = ((temp/total) * (Math.PI * 2)) + d.d3plus.segments.active + } + else { + d.d3plus.segments.temp = 0 + } + } + + } + + } + + } + + return d.d3plus ? d.d3plus.id : false; + + }) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Groups Exit + //-------------------------------------------------------------------------- + if (vars.draw.timing) { + var exit = selection.exit() + .transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove() + } + else { + var exit = selection.exit() + .remove() + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Existing Groups Update + //-------------------------------------------------------------------------- + if (vars.draw.timing) { + selection + .transition().duration(vars.draw.timing) + .call(transform) + .call(className); + } + else { + selection.call(transform).call(className); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Groups Enter + //-------------------------------------------------------------------------- + var opacity = vars.draw.timing ? 0 : 1 + var enter = selection.enter().append("g") + .attr("opacity",opacity) + .call(transform) + .call(className); + + if (vars.draw.timing) { + enter.transition().duration(vars.draw.timing) + .attr("opacity",1) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // All Groups Sort Order + //-------------------------------------------------------------------------- + selection.order() + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Draw appropriate graphics inside of each group + //-------------------------------------------------------------------------- + if ( vars.dev.value ) print.time("drawing \"" + shape + "\" shapes") + drawShape[shape]( vars , selection , enter , exit , transform ) + if ( vars.dev.value ) print.timeEnd("drawing \"" + shape + "\" shapes") + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check for active and temp fills for rects and donuts + //-------------------------------------------------------------------------- + if (["rect","donut"].indexOf(shape) >= 0 && vars.types[vars.type.value].fill) { + if ( vars.dev.value ) print.time("filling \"" + shape + "\" shapes") + shapeFill( vars , selection , enter , exit , transform ) + if ( vars.dev.value ) print.timeEnd("filling \"" + shape + "\" shapes") + } + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Function to Update Edges + //---------------------------------------------------------------------------- + function edge_update(d) { + + if (d && vars.g.edges.selectAll("g").size() > 0) { + + vars.g.edge_hover + .selectAll("*") + .remove() + + vars.g.edges.selectAll("g") + .each(function(l){ + + var id = d[vars.id.value], + source = l[vars.edges.source][vars.id.value], + target = l[vars.edges.target][vars.id.value]; + + if (source == id || source == "left_" + id || source == "right_" + id || + target == id || target == "left_" + id || target == "right_" + id) { + var elem = vars.g.edge_hover.node().appendChild(this.cloneNode(true)) + d3.select(elem).datum(l).attr("opacity",1) + .selectAll("line, path").datum(l) + } + + }) + + + var marker = vars.edges.arrows.value + + vars.g.edge_hover + .attr("opacity",0) + .selectAll("line, path") + .style("stroke",vars.color.primary) + .style("stroke-width",function(d){ + if (vars.edges.path && d.dy) { + return Math.max(1, d.dy); + } + return vars.edges.size.value ? d3.select(this).style("stroke-width") + : vars.data.stroke.width*2 + }) + .attr("marker-start",function(e){ + + var direction = vars.edges.arrows.direction.value + + if ("bucket" in e.d3plus) { + var d = "_"+e.d3plus.bucket + } + else { + var d = "" + } + + return direction == "source" && marker + ? "url(#d3plus_edge_marker_highlight"+d+")" : "none" + + }) + .attr("marker-end",function(e){ + + var direction = vars.edges.arrows.direction.value + + if ("bucket" in e.d3plus) { + var d = "_"+e.d3plus.bucket + } + else { + var d = "" + } + + return direction == "target" && marker + ? "url(#d3plus_edge_marker_highlight"+d+")" : "none" + + }) + + + vars.g.edge_hover.selectAll("text") + .style("fill",vars.color.primary) + + if (vars.draw.timing) { + + vars.g.edge_hover + .transition().duration(vars.timing.mouseevents) + .attr("opacity",1) + + vars.g.edges + .transition().duration(vars.timing.mouseevents) + .attr("opacity",0.5) + + } + else { + + vars.g.edge_hover + .attr("opacity",1) + + } + + } + else { + + if (vars.draw.timing) { + + vars.g.edge_hover + .transition().duration(vars.timing.mouseevents) + .attr("opacity",0) + .transition() + .selectAll("*") + .remove() + + vars.g.edges + .transition().duration(vars.timing.mouseevents) + .attr("opacity",1) + + } + else { + + vars.g.edge_hover + .selectAll("*") + .remove() + + } + + } + + } + + edge_update() + + if (vars.tooltip.value) { + + vars.g.data.selectAll("g") + .on(events.over,function(d){ + + if (touch) touchEvent(vars, d3.event); + + if (!d3.event.buttons && vars.mouse.value && vars.mouse.over.value && !vars.draw.frozen && (!d.d3plus || !d.d3plus.static)) { + + var defaultClick = typeof vars.mouse.over.value !== "function"; + if (typeof vars.mouse.over.value === "function") { + defaultClick = vars.mouse.over.value(d, vars.self); + } + if (defaultClick) { + + var zoomDir = zoomDirection(d.d3plus_data || d, vars) + var pointer = typeof vars.mouse.viz === "function" || + typeof vars.mouse.viz[events.click] === "function" || + (vars.zoom.value && (vars.types[vars.type.value].zoom || + (d.d3plus.threshold && d.d3plus.merged) || + zoomDir === 1 || + (zoomDir === -1 && vars.history.states.length && !vars.tooltip.value.long))); + + d3.select(this) + .style("cursor", pointer ? "pointer" : "auto") + .transition().duration(vars.timing.mouseevents) + .call(transform,true) + + d3.select(this).selectAll(".d3plus_data") + .transition().duration(vars.timing.mouseevents) + .attr("opacity",1) + + vars.covered = false + + if (d.values && vars.axes.discrete) { + + var index = vars.axes.discrete === "x" ? 0 : 1 + , mouse = d3.mouse(vars.container.value.node())[index] + , positions = uniqueValues(d.values,function(x){return x.d3plus[vars.axes.discrete]}) + , match = closest(positions,mouse) + + d.d3plus_data = d.values[positions.indexOf(match)] + d.d3plus = d.values[positions.indexOf(match)].d3plus + + } + + var tooltip_data = d.d3plus_data ? d.d3plus_data : d + + createTooltip({ + "vars": vars, + "data": tooltip_data + }) + + if (typeof vars.mouse.viz == "function") { + vars.mouse.viz(d.d3plus_data || d, vars) + } + else if (vars.mouse.viz[events.over]) { + vars.mouse.viz[events.over](d.d3plus_data || d, vars) + } + + edge_update(d) + + } + + } + else { + removeTooltip(vars.type.value); + } + + }) + .on(events.move,function(d){ + + if (touch) touchEvent(vars, d3.event); + + if (!d3.event.buttons && vars.mouse.value && vars.mouse.move.value && !vars.draw.frozen && (!d.d3plus || !d.d3plus.static)) { + + var defaultClick = typeof vars.mouse.move.value !== "function"; + if (typeof vars.mouse.move.value === "function") { + defaultClick = vars.mouse.move.value(d, vars.self); + } + if (defaultClick) { + + var zoomDir = zoomDirection(d.d3plus_data || d, vars) + var pointer = typeof vars.mouse.viz === "function" || + typeof vars.mouse.viz[events.click] === "function" || + (vars.zoom.value && (vars.types[vars.type.value].zoom || + (d.d3plus.threshold && d.d3plus.merged) || + zoomDir === 1 || + (zoomDir === -1 && vars.history.states.length && !vars.tooltip.value.long))); + + + d3.select(this).style("cursor", pointer ? "pointer" : "auto"); + + // vars.covered = false + var tooltipType = vars.types[vars.type.value].tooltip || "follow" + + if (d.values && vars.axes.discrete) { + + var index = vars.axes.discrete === "x" ? 0 : 1 + , mouse = d3.mouse(vars.container.value.node())[index] + , positions = uniqueValues(d.values,function(x){return x.d3plus[vars.axes.discrete]}) + , match = closest(positions,mouse) + + d.d3plus_data = d.values[positions.indexOf(match)] + d.d3plus = d.values[positions.indexOf(match)].d3plus + + } + + var tooltip_data = d.d3plus_data ? d.d3plus_data : d + createTooltip({ + "vars": vars, + "data": tooltip_data + }) + + if (typeof vars.mouse.viz == "function") { + vars.mouse.viz(d.d3plus_data || d, vars) + } + else if (vars.mouse.viz[events.move]) { + vars.mouse.viz[events.move](d.d3plus_data || d, vars) + } + + } + + } + else { + removeTooltip(vars.type.value); + } + + }) + .on(events.out,function(d){ + + if (touch) touchEvent(vars, d3.event); + + if (!d3.event.buttons && vars.mouse.value && vars.mouse.out.value) { + + var defaultClick = typeof vars.mouse.out.value !== "function"; + if (typeof vars.mouse.out.value === "function") { + defaultClick = vars.mouse.out.value(d, vars.self); + } + if (defaultClick) { + + var childElement = child(this,d3.event.toElement) + + if (!childElement && !vars.draw.frozen && (!d.d3plus || !d.d3plus.static)) { + + d3.select(this) + .transition().duration(vars.timing.mouseevents) + .call(transform) + + d3.select(this).selectAll(".d3plus_data") + .transition().duration(vars.timing.mouseevents) + .attr("opacity",vars.data.opacity) + + if (!vars.covered) { + removeTooltip(vars.type.value) + } + + if (typeof vars.mouse.viz == "function") { + vars.mouse.viz(d.d3plus_data || d, vars) + } + else if (vars.mouse.viz[events.out]) { + vars.mouse.viz[events.out](d.d3plus_data || d, vars) + } + + edge_update() + + } + + } + + } + else { + removeTooltip(vars.type.value); + } + + }) + + } + else { + + var mouseEvent = function() { + touchEvent(vars, d3.event) + } + + vars.g.data.selectAll("g") + .on(events.over, mouseEvent) + .on(events.move, mouseEvent) + .on(events.out , mouseEvent) + + } + + d3.select(window).on("scroll.d3plus", function(){ + removeTooltip(vars.type.value); + }); + + vars.g.data.selectAll("g") + .on(events.click,function(d){ + + if (!(vars.mouse.viz && vars.mouse.viz.click === false) && vars.mouse.value && vars.mouse.click.value && !d3.event.defaultPrevented && !vars.draw.frozen && (!d.d3plus || !d.d3plus.static)) { + + var defaultClick = typeof vars.mouse.click.value !== "function"; + if (typeof vars.mouse.click.value === "function") { + defaultClick = vars.mouse.click.value(d, vars.self); + } + if (defaultClick) { + + if (d.values && vars.axes.discrete) { + + var index = vars.axes.discrete === "x" ? 0 : 1 + , mouse = d3.mouse(vars.container.value.node())[index] + , positions = uniqueValues(d.values,function(x){return x.d3plus[vars.axes.discrete]}) + , match = closest(positions,mouse) + + d.d3plus_data = d.values[positions.indexOf(match)] + d.d3plus = d.values[positions.indexOf(match)].d3plus + + } + + if (typeof vars.mouse.viz == "function") { + vars.mouse.viz(d.d3plus_data || d, vars) + } + else if (vars.mouse.viz[events.out]) { + vars.mouse.viz[events.out](d.d3plus_data || d, vars) + } + else if (vars.mouse.viz[events.click]) { + vars.mouse.viz[events.click](d.d3plus_data || d, vars) + } + + var depth_delta = zoomDirection(d.d3plus_data || d, vars) + , previous = vars.id.solo.value + , title = fetchText(vars,d)[0] + , color = legible(fetchColor(vars,d)) + , prev_sub = vars.title.sub.value || false + , prev_color = vars.title.sub.font.color + , prev_total = vars.title.total.font.color + + if (d.d3plus.threshold && d.d3plus.merged && vars.zoom.value) { + + vars.history.states.push(function(){ + + vars.self + .id({"solo": previous}) + .title({ + "sub": { + "font": { + "color": prev_color + }, + "value": prev_sub + }, + "total": { + "font": { + "color": prev_total + } + } + }) + .draw() + + }) + + vars.self + .id({"solo": previous.concat(uniqueValues(d.d3plus.merged, vars.id.value, fetchValue, vars))}) + .title({ + "sub": { + "font": { + "color": color + }, + "value": title + }, + "total": { + "font": { + "color": color + } + } + }) + .draw() + + } + else if (depth_delta === 1 && vars.zoom.value) { + + var id = fetchValue(vars, d.d3plus_data || d, vars.id.value) + + vars.history.states.push(function(){ + + vars.self + .depth(vars.depth.value-1) + .id({"solo": previous}) + .title({ + "sub": { + "font": { + "color": prev_color + }, + "value": prev_sub + }, + "total": { + "font": { + "color": prev_total + } + } + }) + .draw() + + }) + + vars.self + .depth(vars.depth.value+1) + .id({"solo": previous.concat(id)}) + .title({ + "sub": { + "font": { + "color": color + }, + "value": title + }, + "total": { + "font": { + "color": color + } + } + }) + .draw() + + } + else if (depth_delta === -1 && vars.zoom.value && + vars.history.states.length && !vars.tooltip.value.long) { + + vars.history.back() + + } + else if (vars.types[vars.type.value].zoom && vars.zoom.value) { + + edge_update() + + d3.select(this) + .transition().duration(vars.timing.mouseevents) + .call(transform) + + d3.select(this).selectAll(".d3plus_data") + .transition().duration(vars.timing.mouseevents) + .attr("opacity",vars.data.opacity) + + removeTooltip(vars.type.value) + vars.draw.update = false + + if (!d || d[vars.id.value] == vars.focus.value[0]) { + vars.self.focus(false).draw() + } + else { + vars.self.focus(d[vars.id.value]).draw() + } + + } + else if (vars.types[vars.type.value].requirements.indexOf("focus") < 0) { + + edge_update() + + var tooltip_data = d.d3plus_data ? d.d3plus_data : d + + createTooltip({ + "vars": vars, + "data": tooltip_data + }) + + } + + } + + } + + }) + +} + +},{"../../../client/pointer.coffee":38,"../../../client/touch.coffee":43,"../../../color/legible.coffee":44,"../../../core/console/print.coffee":52,"../../../core/fetch/color.coffee":63,"../../../core/fetch/text.js":66,"../../../core/fetch/value.coffee":67,"../../../object/validate.coffee":172,"../../../string/strip.js":175,"../../../tooltip/remove.coffee":203,"../../../util/child.coffee":205,"../../../util/closest.coffee":206,"../../../util/uniques.coffee":210,"../tooltip/create.js":240,"../zoom/direction.coffee":250,"../zoom/propagation.coffee":253,"./arc.coffee":217,"./area.js":218,"./check.js":219,"./coordinates.coffee":221,"./cross.js":222,"./diamond.js":223,"./donut.js":224,"./fill.js":227,"./line.js":229,"./radial.coffee":231,"./rect.coffee":232,"./segments.coffee":233,"./triangle_down.js":235,"./triangle_up.js":236,"./whisker.coffee":237}],226:[function(require,module,exports){ +var buckets = require("../../../util/buckets.coffee"), + offset = require("../../../geom/offset.coffee"); + +module.exports = function(vars) { + + var edges = vars.returned.edges || [], + scale = vars.zoom.behavior.scaleExtent()[0]; + + if (typeof vars.edges.size.value === "string") { + + var strokeDomain = d3.extent(edges, function(e){ + return e[vars.edges.size.value]; + }), + maxSize = d3.min(vars.returned.nodes || [], function(n){ + return n.d3plus.r; + }) * (vars.edges.size.scale * 2); + + vars.edges.scale = d3.scale.sqrt() + .domain(strokeDomain) + .range([vars.edges.size.min,maxSize*scale]); + + } + else { + + var defaultWidth = typeof vars.edges.size.value == "number" ? + vars.edges.size.value : vars.edges.size.min; + + vars.edges.scale = function(){ + return defaultWidth; + }; + + } + + var o = vars.edges.opacity.value; + var o_type = typeof o; + + if (vars.edges.opacity.changed && o_type === "string") { + vars.edges.opacity.scale.value + .domain(d3.extent(edges, function(d){ + return d[o]; + })) + .range([vars.edges.opacity.min.value,1]); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialization of Lines + //---------------------------------------------------------------------------- + function init(l) { + + l + .attr("opacity", 0) + .style("stroke-width",0) + .style("stroke",vars.background.value) + .style("fill","none"); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Styling of Lines + //---------------------------------------------------------------------------- + function style(edges) { + + var marker = vars.edges.arrows.value; + + edges + .attr("opacity", function(d){ + return o_type === "number" ? o : + o_type === "function" ? o(d, vars) : + vars.edges.opacity.scale.value(d[o]); + }) + .style("stroke-width",function(e){ + return vars.edges.scale(e[vars.edges.size.value]); + }) + .style("stroke",vars.edges.color) + .attr("marker-start",function(e){ + + var direction = vars.edges.arrows.direction.value; + + if ("bucket" in e.d3plus) { + var d = "_"+e.d3plus.bucket; + } + else { + var d = ""; + } + + return direction == "source" && marker + ? "url(#d3plus_edge_marker_default"+d+")" : "none" + + }) + .attr("marker-end",function(e){ + + var direction = vars.edges.arrows.direction.value + + if ("bucket" in e.d3plus) { + var d = "_"+e.d3plus.bucket + } + else { + var d = "" + } + + return direction == "target" && marker + ? "url(#d3plus_edge_marker_default"+d+")" : "none" + + }) + .attr("vector-effect","non-scaling-stroke") + .attr("pointer-events","none") + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Positioning of Lines + //---------------------------------------------------------------------------- + function line(l) { + l + .attr("x1",function(d){ + return d[vars.edges.source].d3plus.edges[d[vars.edges.target][vars.id.value]].x; + }) + .attr("y1",function(d){ + return d[vars.edges.source].d3plus.edges[d[vars.edges.target][vars.id.value]].y; + }) + .attr("x2",function(d){ + return d[vars.edges.target].d3plus.edges[d[vars.edges.source][vars.id.value]].x; + }) + .attr("y2",function(d){ + return d[vars.edges.target].d3plus.edges[d[vars.edges.source][vars.id.value]].y; + }); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Positioning of Splines + //---------------------------------------------------------------------------- + var curve = d3.svg.line().interpolate(vars.edges.interpolate.value); + + function spline(l) { + l + .attr("d", function(d) { + + return curve(d.d3plus.spline); + + }); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Calculates and Draws Label for edge + //---------------------------------------------------------------------------- + function label(d) { + + delete d.d3plus_label + + if (vars.g.edges.selectAll("line, path").size() < vars.edges.large && vars.edges.label && d[vars.edges.label]) { + + if ("spline" in d.d3plus) { + + var length = this.getTotalLength(), + center = this.getPointAtLength(length/2), + prev = this.getPointAtLength((length/2)-(length*.1)), + next = this.getPointAtLength((length/2)+(length*.1)), + radians = Math.atan2(next.y-prev.y,next.x-prev.x), + angle = radians*(180/Math.PI), + bounding = this.parentNode.getBBox(), + width = length*.8, + x = center.x, + y = center.y + + } + else { + + var bounds = this.getBBox(), + source = d[vars.edges.source], + target = d[vars.edges.target], + start = {"x": source.d3plus.edges[target[vars.id.value]].x, "y": source.d3plus.edges[target[vars.id.value]].y}, + end = {"x": target.d3plus.edges[source[vars.id.value]].x, "y": target.d3plus.edges[source[vars.id.value]].y}, + xdiff = end.x-start.x, + ydiff = end.y-start.y, + center = {"x": end.x-(xdiff)/2, "y": end.y-(ydiff)/2}, + radians = Math.atan2(ydiff,xdiff), + angle = radians*(180/Math.PI), + length = Math.sqrt((xdiff*xdiff)+(ydiff*ydiff)), + width = length, + x = center.x, + y = center.y + + } + + width += vars.labels.padding*2 + + var m = 0 + if (vars.edges.arrows.value) { + m = typeof vars.edges.arrows.value === "number" + ? vars.edges.arrows.value : 8 + m = m/vars.zoom.behavior.scaleExtent()[1] + width -= m*2 + } + + if (angle < -90 || angle > 90) { + angle -= 180 + } + + if (width*vars.zoom.behavior.scaleExtent()[0] > 20) { + + d.d3plus_label = { + "x": x, + "y": y, + "translate": {"x": x, "y": y}, + "w": width, + "h": 15+vars.labels.padding*2, + "angle": angle, + "anchor": "middle", + "valign": "center", + "color": vars.edges.color, + "resize": false, + "names": [vars.format.value(d[vars.edges.label])], + "background": 1 + } + + } + + } + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Enter/update/exit the Arrow Marker + //---------------------------------------------------------------------------- + var markerData = vars.edges.arrows.value ? typeof vars.edges.size.value == "string" + ? [ "default_0", "default_1", "default_2", + "highlight_0", "highlight_1", "highlight_2", + "focus_0", "focus_1", "focus_2" ] + : [ "default", "highlight", "focus" ] : [] + + if (typeof vars.edges.size.value == "string") { + var b = buckets(vars.edges.scale.range(),4) + , markerSize = [] + for (var i = 0; i < 3; i++) { + markerSize.push(b[i+1]+(b[1]-b[0])*(i+2)*2) + } + } + else { + var m = typeof vars.edges.arrows.value === "number" + ? vars.edges.arrows.value : 8 + + var markerSize = typeof vars.edges.size.value === "number" + ? vars.edges.size.value/m : m + } + + var marker = vars.defs.selectAll(".d3plus_edge_marker") + .data(markerData, String) + + var marker_style = function(path) { + path + .attr("d",function(id){ + + var depth = id.split("_") + + if (depth.length == 2 && vars.edges.scale) { + depth = parseInt(depth[1]) + var m = markerSize[depth] + } + else { + var m = markerSize + } + + if (vars.edges.arrows.direction.value == "target") { + return "M 0,-"+m/2+" L "+m*.85+",0 L 0,"+m/2+" L 0,-"+m/2 + } + else { + return "M 0,-"+m/2+" L -"+m*.85+",0 L 0,"+m/2+" L 0,-"+m/2 + } + }) + .attr("fill",function(d){ + + var type = d.split("_")[0] + + if (type == "default") { + return vars.edges.color + } + else if (type == "focus") { + return vars.color.focus + } + else { + return vars.color.primary + } + }) + .attr("transform","scale("+1/scale+")") + } + + if (vars.draw.timing) { + marker.exit().transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove() + + marker.select("path").transition().duration(vars.draw.timing) + .attr("opacity",1) + .call(marker_style) + } + else { + marker.exit().remove() + + marker.select("path") + .attr("opacity",1) + .call(marker_style) + } + + var opacity = vars.draw.timing ? 0 : 1 + var enter = marker.enter().append("marker") + .attr("id",function(d){ + return "d3plus_edge_marker_"+d + }) + .attr("class","d3plus_edge_marker") + .attr("orient","auto") + .attr("markerUnits","userSpaceOnUse") + .style("overflow","visible") + .append("path") + .attr("opacity",opacity) + .attr("vector-effect","non-scaling-stroke") + .call(marker_style) + + if (vars.draw.timing) { + enter.transition().duration(vars.draw.timing) + .attr("opacity",1) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Bind "edges" data to lines in the "edges" group + //---------------------------------------------------------------------------- + var strokeBuckets = typeof vars.edges.size.value == "string" + ? buckets(vars.edges.scale.domain(),4) + : null + , direction = vars.edges.arrows.direction.value + + var line_data = edges.filter(function(l){ + + if (!l.d3plus) l.d3plus = {} + + l.d3plus.id = "edge_"+l[vars.edges.source][vars.id.value]+"_"+l[vars.edges.target][vars.id.value] + + if ( l.d3plus.spline !== true ) { + + if (strokeBuckets) { + var size = l[vars.edges.size.value] + l.d3plus.bucket = size < strokeBuckets[1] ? 0 + : size < strokeBuckets[2] ? 1 : 2 + var marker = markerSize[l.d3plus.bucket]*.85/scale + } + else { + delete l.d3plus.bucket + var marker = markerSize*.85/scale + } + + var source = l[vars.edges.source] + , target = l[vars.edges.target] + + if (!source.d3plus || !target.d3plus) return false + + var sourceAngle = Math.atan2( source.d3plus.y - target.d3plus.y + , source.d3plus.x - target.d3plus.x ) + , targetAngle = Math.atan2( target.d3plus.y - source.d3plus.y + , target.d3plus.x - source.d3plus.x ) + , sourceRadius = direction == "source" && vars.edges.arrows.value + ? source.d3plus.r + marker + : source.d3plus.r + , targetRadius = direction == "target" && vars.edges.arrows.value + ? target.d3plus.r + marker + : target.d3plus.r + , sourceOffset = offset( sourceAngle + , sourceRadius + , vars.shape.value ) + , targetOffset = offset( targetAngle + , targetRadius + , vars.shape.value ) + + if (!("edges" in source.d3plus)) source.d3plus.edges = {} + source.d3plus.edges[target[vars.id.value]] = { + "x": source.d3plus.x - sourceOffset.x, + "y": source.d3plus.y - sourceOffset.y + } + + if (!("edges" in target.d3plus)) target.d3plus.edges = {} + target.d3plus.edges[source[vars.id.value]] = { + "x": target.d3plus.x - targetOffset.x, + "y": target.d3plus.y - targetOffset.y + } + + return true + } + + return false + + }) + + var lines = vars.g.edges.selectAll("g.d3plus_edge_line") + .data(line_data,function(d){ + + return d.d3plus.id + + }) + + var spline_data = edges.filter(function(l){ + + if (l.d3plus.spline) { + + if (strokeBuckets) { + var size = l[vars.edges.size.value] + l.d3plus.bucket = size < strokeBuckets[1] ? 0 + : size < strokeBuckets[2] ? 1 : 2 + var marker = markerSize[l.d3plus.bucket]*.85/scale + } + else { + delete l.d3plus.bucket + var marker = markerSize*.85/scale + } + + var source = l[vars.edges.source] + , target = l[vars.edges.target] + , sourceEdge = source.d3plus.edges ? source.d3plus.edges[target[vars.id.value]] || {} : {} + , targetEdge = target.d3plus.edges ? target.d3plus.edges[source[vars.id.value]] || {} : {} + , sourceMod = vars.edges.arrows.value && direction == "source" ? marker : 0 + , targetMod = vars.edges.arrows.value && direction == "target" ? marker : 0 + , angleTweak = 0.1 + , sourceTweak = source.d3plus.x > target.d3plus.x ? 1-angleTweak : 1+angleTweak + , targetTweak = source.d3plus.x > target.d3plus.x ? 1+angleTweak : 1-angleTweak + , sourceAngle = typeof sourceEdge.angle === "number" ? sourceEdge.angle + : Math.atan2( source.d3plus.y - target.d3plus.y + , source.d3plus.x - target.d3plus.x ) * sourceTweak + , sourceOffset = offset(sourceAngle, source.d3plus.r + sourceMod, vars.shape.value ) + , targetAngle = typeof targetEdge.angle === "number" ? targetEdge.angle + : Math.atan2( target.d3plus.y - source.d3plus.y + , target.d3plus.x - source.d3plus.x ) * targetTweak + , targetOffset = offset(targetAngle, target.d3plus.r + targetMod, vars.shape.value ) + , start = [source.d3plus.x-sourceOffset.x, source.d3plus.y-sourceOffset.y] + , startOffset = sourceEdge.offset ? offset(sourceAngle,sourceEdge.offset) : false + , startPoint = startOffset ? [start[0]-startOffset.x,start[1]-startOffset.y] : start + , end = [target.d3plus.x-targetOffset.x, target.d3plus.y-targetOffset.y] + , endOffset = targetEdge.offset ? offset(targetAngle,targetEdge.offset) : false + , endPoint = endOffset ? [end[0]-endOffset.x,end[1]-endOffset.y] : end + , xd = endPoint[0] - startPoint[0] + , yd = endPoint[1] - startPoint[1] + , sourceDistance = typeof sourceEdge.radius === "number" ? sourceEdge.radius : Math.sqrt(xd*xd+yd*yd)/4 + , targetDistance = typeof targetEdge.radius === "number" ? targetEdge.radius : Math.sqrt(xd*xd+yd*yd)/4 + , startAnchor = offset(sourceAngle,sourceDistance-source.d3plus.r-sourceMod*2) + , endAnchor = offset(targetAngle,targetDistance-target.d3plus.r-targetMod*2) + + l.d3plus.spline = [ start, end ] + var testAngle = Math.abs(Math.atan2( source.d3plus.y - target.d3plus.y + , source.d3plus.x - target.d3plus.x )).toFixed(5) + , testStart = Math.abs(sourceAngle).toFixed(5) + , testEnd = Math.abs(targetAngle - Math.PI).toFixed(5) + + if (testStart !== testEnd || [testStart,testEnd].indexOf(testAngle) < 0) { + + l.d3plus.spline.splice(1,0,[startPoint[0]-startAnchor.x,startPoint[1]-startAnchor.y], + [endPoint[0]-endAnchor.x,endPoint[1]-endAnchor.y]) + + if (startOffset) l.d3plus.spline.splice(1,0,startPoint) + if (endOffset) l.d3plus.spline.splice(l.d3plus.spline.length-1,0,endPoint) + + } + + return true + + } + + return false + + }) + + var splines = vars.g.edges.selectAll("g.d3plus_edge_path") + .data(spline_data,function(d){ + + return d.d3plus.id + + }) + + if (vars.draw.timing) { + + lines.exit().transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove() + + splines.exit().transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove() + + lines.selectAll("text.d3plus_label, rect.d3plus_label_bg") + .transition().duration(vars.draw.timing/2) + .attr("opacity",0) + .remove() + + splines.selectAll("text.d3plus_label, rect.d3plus_label_bg") + .transition().duration(vars.draw.timing/2) + .attr("opacity",0) + .remove() + + lines.selectAll("line") + .data(function(d){ return [d] }) + .transition().duration(vars.draw.timing) + .call(line) + .call(style) + .each("end",label) + + splines.selectAll("path") + .data(function(d){ return [d] }) + .transition().duration(vars.draw.timing) + .call(spline) + .call(style) + .each("end",label) + + lines.enter().append("g") + .attr("class","d3plus_edge_line") + .append("line") + .call(line) + .call(init) + .transition().duration(vars.draw.timing) + .call(style) + .each("end",label) + + splines.enter().append("g") + .attr("class","d3plus_edge_path") + .append("path") + .call(spline) + .call(init) + .transition().duration(vars.draw.timing) + .call(style) + .each("end",label) + + } + else { + + lines.exit().remove() + + splines.exit().remove() + + lines.selectAll("text.d3plus_label, rect.d3plus_label_bg") + .remove() + + splines.selectAll("text.d3plus_label, rect.d3plus_label_bg") + .remove() + + lines.selectAll("line") + .data(function(d){ return [d] }) + .call(line) + .call(style) + .call(label) + + splines.selectAll("path") + .data(function(d){ return [d] }) + .call(spline) + .call(style) + .call(label) + + lines.enter().append("g") + .attr("class","d3plus_edge_line") + .append("line") + .call(line) + .call(init) + .call(style) + .call(label) + + splines.enter().append("g") + .attr("class","d3plus_edge_path") + .append("path") + .call(spline) + .call(init) + .call(style) + .call(label) + + } + +} + +},{"../../../geom/offset.coffee":161,"../../../util/buckets.coffee":204}],227:[function(require,module,exports){ +var copy = require("../../../util/copy.coffee"), + fetchColor = require("../../../core/fetch/color.coffee"), + fetchValue = require("../../../core/fetch/value.coffee"), + segments = require("./segments.coffee"), + shapeStyle = require("./style.coffee"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "square" and "circle" shapes using svg:rect +//------------------------------------------------------------------------------ +module.exports = function(vars,selection,enter,exit) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // The position and size of each rectangle on enter and exit. + //---------------------------------------------------------------------------- + function init(nodes) { + + nodes + .attr("x",0) + .attr("y",0) + .attr("width",0) + .attr("height",0); + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // The position and size of each rectangle on update. + //---------------------------------------------------------------------------- + function update(nodes,mod) { + if (!mod) mod = 0; + nodes + .attr("x",function(d){ + var w = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.width; + return (-w/2)-(mod/2); + }) + .attr("y",function(d){ + var h = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.height; + return (-h/2)-(mod/2); + }) + .attr("width",function(d){ + var w = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.width; + return w+mod; + }) + .attr("height",function(d){ + var h = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.height; + return h+mod; + }) + .attr("rx",function(d){ + var w = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.width; + var rounded = ["circle","donut"].indexOf(vars.shape.value) >= 0; + return rounded ? (w+mod)/2 : 0; + }) + .attr("ry",function(d){ + var h = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.height; + var rounded = ["circle","donut"].indexOf(vars.shape.value) >= 0; + return rounded ? (h+mod)/2 : 0; + }) + .attr("shape-rendering",function(d){ + if (["square"].indexOf(vars.shape.value) >= 0) { + return vars.shape.rendering.value; + } + else { + return "auto"; + } + }); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // In order to correctly animate each donut's size and arcs, we need to store + // it's previous values in a lookup object that does not get destroyed when + // redrawing the visualization. + //---------------------------------------------------------------------------- + if (!vars.arcs) { + vars.arcs = { + "donut": {}, + "active": {}, + "temp": {} + }; + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // This is the main arc function that determines what values to use for each + // arc angle and radius. + //---------------------------------------------------------------------------- + var arc = d3.svg.arc() + .startAngle(0) + .endAngle(function(d){ + var a = vars.arcs[d.d3plus.shape][d.d3plus.id].a; + return a > Math.PI*2 ? Math.PI*2 : a; + }) + .innerRadius(function(d){ + if (!d.d3plus.static && vars.shape.value === "donut") { + var r = vars.arcs[d.d3plus.shape][d.d3plus.id].r; + return r * vars.data.donut.size; + } + else { + return 0; + } + }) + .outerRadius(function(d){ + var r = vars.arcs[d.d3plus.shape][d.d3plus.id].r; + return vars.shape.value === "donut" ? r : r*2; + }); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // This is the main "arcTween" function where all of the animation happens + // for each arc. + //---------------------------------------------------------------------------- + function size(path,mod,rad,ang) { + if (!mod) mod = 0; + if (typeof rad != "number") rad = undefined; + if (typeof ang != "number") ang = undefined; + path.attrTween("d", function(d){ + if (rad === undefined) var r = d.d3plus.r ? d.d3plus.r : d3.max([d.d3plus.width,d.d3plus.height]); + else var r = rad; + if (ang === undefined) var a = d.d3plus.segments[d.d3plus.shape]; + else var a = ang; + if (!vars.arcs[d.d3plus.shape][d.d3plus.id]) { + vars.arcs[d.d3plus.shape][d.d3plus.id] = {"r": 0}; + vars.arcs[d.d3plus.shape][d.d3plus.id].a = d.d3plus.shape === "donut" ? Math.PI * 2 : 0; + } + var radius = d3.interpolate(vars.arcs[d.d3plus.shape][d.d3plus.id].r,r+mod), + angle = d3.interpolate(vars.arcs[d.d3plus.shape][d.d3plus.id].a,a); + + return function(t) { + vars.arcs[d.d3plus.shape][d.d3plus.id].r = radius(t); + vars.arcs[d.d3plus.shape][d.d3plus.id].a = angle(t); + return arc(d); + }; + }); + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check each data point for active and temp data + //---------------------------------------------------------------------------- + selection.each(function(d){ + + var active = segments(vars, d, "active"), + temp = segments(vars, d, "temp"), + total = segments(vars, d, "total"), + group = d3.select(this), + color = fetchColor(vars,d); + + var fill_data = [], hatch_data = []; + + if (total && vars.types[vars.type.value].fill) { + + if (temp) { + var c = copy(d); + c.d3plus.shape = "temp"; + fill_data.push(c); + hatch_data = ["temp"]; + } + + if (active && (active < total || temp)) { + var c = copy(d); + c.d3plus.shape = "active"; + fill_data.push(c); + } + + } + + function hatch_lines(l) { + l + .attr("stroke",color) + .attr("stroke-width",1) + .attr("shape-rendering",vars.shape.rendering.value); + } + + var pattern = vars.defs.selectAll("pattern#d3plus_hatch_"+d.d3plus.id) + .data(hatch_data); + + if (vars.draw.timing) { + + pattern.selectAll("rect") + .transition().duration(vars.draw.timing) + .style("fill",color); + + pattern.selectAll("line") + .transition().duration(vars.draw.timing) + .style("stroke",color); + + } + else { + + pattern.selectAll("rect").style("fill",color); + + pattern.selectAll("line").style("stroke",color); + + } + + var pattern_enter = pattern.enter().append("pattern") + .attr("id","d3plus_hatch_"+d.d3plus.id) + .attr("patternUnits","userSpaceOnUse") + .attr("x","0") + .attr("y","0") + .attr("width","10") + .attr("height","10") + .append("g"); + + pattern_enter.append("rect") + .attr("x","0") + .attr("y","0") + .attr("width","10") + .attr("height","10") + .attr("fill",color) + .attr("fill-opacity",0.25); + + pattern_enter.append("line") + .attr("x1","0") + .attr("x2","10") + .attr("y1","0") + .attr("y2","10") + .call(hatch_lines); + + pattern_enter.append("line") + .attr("x1","-1") + .attr("x2","1") + .attr("y1","9") + .attr("y2","11") + .call(hatch_lines); + + pattern_enter.append("line") + .attr("x1","9") + .attr("x2","11") + .attr("y1","-1") + .attr("y2","1") + .call(hatch_lines); + + var clip_data = fill_data.length ? [d] : []; + + var clip = group.selectAll("#d3plus_clip_"+d.d3plus.id) + .data(clip_data); + + clip.enter().insert("clipPath",".d3plus_mouse") + .attr("id","d3plus_clip_"+d.d3plus.id) + .append("rect") + .attr("class","d3plus_clipping") + .call(init); + + if (vars.draw.timing) { + + clip.selectAll("rect").transition().duration(vars.draw.timing) + .call(update); + + clip.exit().transition().delay(vars.draw.timing) + .remove(); + + } + else { + + clip.selectAll("rect").call(update); + + clip.exit().remove(); + + } + + var fills = group.selectAll("path.d3plus_fill") + .data(fill_data); + + fills.transition().duration(vars.draw.timing) + .call(shapeStyle,vars) + .call(size); + + fills.enter().insert("path","rect.d3plus_mouse") + .attr("class","d3plus_fill") + .attr("clip-path","url(#d3plus_clip_"+d.d3plus.id+")") + .transition().duration(0) + .call(shapeStyle,vars) + .call(size,0,undefined,0) + .transition().duration(vars.draw.timing) + .call(size) + .call(shapeStyle,vars); + + fills.exit().transition().duration(vars.draw.timing) + .call(size,0,undefined,0) + .remove(); + + }); + +}; + +},{"../../../core/fetch/color.coffee":63,"../../../core/fetch/value.coffee":67,"../../../util/copy.coffee":207,"./segments.coffee":233,"./style.coffee":234}],228:[function(require,module,exports){ +var copy = require("../../../util/copy.coffee"), + fetchText = require("../../../core/fetch/text.js"), + fetchValue = require("../../../core/fetch/value.coffee"), + mix = require("../../../color/mix.coffee"), + print = require("../../../core/console/print.coffee"), + rtl = require("../../../client/rtl.coffee"), + segments = require("./segments.coffee"), + shapeColor = require("./color.coffee"), + stringList = require("../../../string/list.coffee"), + textColor = require("../../../color/text.coffee"), + textWrap = require("../../../textwrap/textwrap.coffee"); + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "labels" using svg:text and d3plus.textwrap +//------------------------------------------------------------------------------ +module.exports = function( vars , group ) { + + var scale = vars.types[vars.type.value].zoom ? vars.zoom.behavior.scaleExtent() : [1,1], + selection = vars.g[ group ].selectAll("g"); + + var opacity = function(elem) { + + elem + .attr("opacity",function(d){ + // if (vars.draw.timing) return 1; + var size = parseFloat(d3.select(this).attr("font-size"),10); + d.visible = size * (vars.zoom.scale/scale[1]) >= 2; + return d.visible ? 1 : 0; + }); + + }; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Label Exiting + //---------------------------------------------------------------------------- + var remove = function(text) { + + if (vars.draw.timing) { + text + .transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove(); + } + else { + text.remove(); + } + + }; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Label Styling + //---------------------------------------------------------------------------- + var style = function(text) { + + var salign = vars.labels.valign.value === "bottom" ? "top" : "bottom"; + + text + .attr("font-weight",vars.labels.font.weight) + .attr("font-family",vars.labels.font.family.value) + .attr("stroke", "none") + .attr("pointer-events",function(t){ + return t.mouse ? "auto": "none"; + }) + .attr("fill", function(t){ + + if ( t.color ) return t.color; + + var color = shapeColor(t.parent,vars), + legible = textColor(color), + opacity = t.text ? 0.15 : 1; + + return mix( color , legible , 0.2 , opacity ); + + }) + .each(function(t){ + + if (t.resize instanceof Array) { + var min = t.resize[0], max = t.resize[1]; + } + + var size = t.resize, resize = true; + + if (t.text) { + + if ( !(size instanceof Array) ) { + size = [9, 50]; + resize = t.resize; + } + + var y = t.y - t.h*scale[1]/2 + t.padding/2; + if (salign === "bottom") y += (t.h * scale[1])/2; + + textWrap() + .align("center") + .container(d3.select(this)) + .height((t.h * scale[1])/2) + .padding(t.padding/2) + .resize(resize) + .size(size) + .text(vars.format.value(t.text*100,{"key": "share", "vars": vars})) + .width(t.w * scale[1]) + .valign(salign) + .x(t.x - t.w*scale[1]/2 + t.padding/2) + .y(y) + .draw(); + + } + else { + + if ( !(t.resize instanceof Array) ) { + size = [7, 40*(scale[1]/scale[0])]; + resize = t.resize; + } + + var yOffset = vars.labels.valign.value === "bottom" ? t.share : 0; + + textWrap() + .align(t.anchor || vars.labels.align.value) + .container( d3.select(this) ) + .height(t.h * scale[1] - t.share) + .padding(t.padding/2) + .resize( resize ) + .size( size ) + .shape(t.shape || "square") + .text( t.names ) + .valign(vars.labels.valign.value) + .width(t.w * scale[1]) + .x(t.x - t.w*scale[1]/2 + t.padding/2) + .y(t.y - t.h*scale[1]/2 + t.padding/2 + yOffset) + .draw(); + + } + + }) + .attr("transform",function(t){ + var translate = d3.select(this).attr("transform") || ""; + var a = t.angle || 0, + x = t.translate && t.translate.x ? t.translate.x : 0, + y = t.translate && t.translate.y ? t.translate.y : 0; + + if (translate.length) { + translate = translate.split(")").slice(-3).join(")"); + } + return "rotate("+a+","+x+","+y+")scale("+1/scale[1]+")translate("+(t.x*scale[1]-t.x)+","+(t.y*scale[1]-t.y)+")" + translate; + + }); + + }; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Loop through each selection and analyze the labels + //---------------------------------------------------------------------------- + if (group === "edges" || vars.labels.value) { + + if ( vars.dev.value ) { + var timerString = "drawing " + group + " labels"; + print.time( timerString ); + } + + selection.each(function(d){ + + var disabled = d.d3plus && "label" in d.d3plus && !d.d3plus.label, + label = d.d3plus_label || null, + share = d.d3plus_share, + names = d.d3plus.text ? d.d3plus.text : + label && label.names ? label.names : + vars.labels.text.value ? + fetchValue(vars, d, vars.labels.text.value) : + fetchText(vars,d), + group = label && "group" in label ? label.group : d3.select(this), + share_size = 0, + fill = vars.types[vars.type.value].fill; + + if (!(names instanceof Array)) names = [names]; + + if (label) { + + if (["line","area"].indexOf(vars.shape.value) >= 0) { + var background = true; + } + else if (d && "d3plus" in d) { + var active = segments(vars, d, "active"), + temp = segments(vars, d, "temp"), + total = segments(vars, d, "total"), + background = (!temp && !active) || (active >= total) || (!active && temp >= total); + } + + } + + if (!disabled && ((label && label.force) || background || !fill)) { + + if (share && d.d3plus.share && share.w-vars.labels.padding*2 >= 10 && share.h-vars.labels.padding*2 >= 10 && vars.labels.valign.value != "middle") { + + share.resize = vars.labels.resize.value === false ? false : + share && "resize" in share ? share.resize : true; + + share.padding = vars.labels.padding; + + share.text = d.d3plus.share; + share.parent = d; + + var text = group.selectAll("text#d3plus_share_"+d.d3plus.id) + .data([share],function(t){ + return t.w+""+t.h+""+t.text; + }); + + if (vars.draw.timing && vars.zoom.scale === 1) { + + text + .transition().duration(vars.draw.timing/2) + .call(style); + + text.enter().append("text") + .attr("id","d3plus_share_"+d.d3plus.id) + .attr("class","d3plus_share") + .attr("opacity",0) + .call(style) + .transition().duration(vars.draw.timing/2) + .delay(vars.draw.timing/2) + .attr("opacity",1); + + } + else { + + text + .attr("opacity",1) + .call(style); + + text.enter().append("text") + .attr("id","d3plus_share_"+d.d3plus.id) + .attr("class","d3plus_share") + .attr("opacity",1) + .call(style); + + } + + share_size = text.node().getBBox().height + vars.labels.padding; + + text.exit().call(remove); + + } + else { + group.selectAll("text.d3plus_share") + .call(remove); + } + + if (label) { + + label.resize = vars.labels.resize.value === false ? false : + label && "resize" in label ? label.resize : true; + + label.padding = typeof label.padding === "number" ? label.padding : vars.labels.padding; + + } + + if (label && label.w*scale[1]-label.padding >= 20 && label.h*scale[1]-label.padding >= 10 && names.length) { + + var and = vars.format.locale.value.ui.and, + more = vars.format.locale.value.ui.more; + + for (var i = 0; i < names.length; i++) { + if (names[i] instanceof Array) { + names[i] = stringList(names[i],and,3,more); + } + } + + label.names = names; + + label.share = share_size; + label.parent = d; + + var text = group.selectAll("text#d3plus_label_"+d.d3plus.id) + .data([label],function(t){ + if (!t) return false; + return t.w+"_"+t.h+"_"+t.x+"_"+t.y+"_"+t.names.join("_"); + }), fontSize = label.resize ? undefined : + (vars.labels.font.size * scale[0]) + "px"; + + if (vars.draw.timing && vars.zoom.scale === 1) { + + text + .transition().duration(vars.draw.timing/2) + .call(style) + .call(opacity); + + text.enter().append("text") + .attr("font-size",fontSize) + .attr("id","d3plus_label_"+d.d3plus.id) + .attr("class","d3plus_label") + .attr("opacity",0) + .call(style) + .transition().duration(vars.draw.timing/2) + .delay(vars.draw.timing/2) + .call(opacity); + + } + else { + + text + .attr("opacity",1) + .call(style) + .call(opacity); + + text.enter().append("text") + .attr("font-size",fontSize) + .attr("id","d3plus_label_"+d.d3plus.id) + .attr("class","d3plus_label") + .call(style) + .call(opacity); + + } + + text.exit().call(remove); + + if (text.size() === 0 || text.selectAll("tspan").size() === 0) { + delete d.d3plus_label; + d3.select(this).selectAll("text#d3plus_label_"+d.d3plus.id+", rect#d3plus_label_bg_"+d.d3plus.id) + .call(remove); + vars.g.labels.selectAll("text#d3plus_label_"+d.d3plus.id+", rect#d3plus_label_bg_"+d.d3plus.id) + .call(remove); + } + else { + + if (label.background) { + + var background_data = ["background"]; + + var box = text.node().getBBox(); + var bounds = { + "height": box.height, + "width": box.width, + "x": box.x, + "y": box.y > 0 ? box.y : -box.height/2 + }; + bounds.width += vars.labels.padding*scale[0]; + bounds.height += vars.labels.padding*scale[0]; + bounds.x -= (vars.labels.padding*scale[0])/2; + bounds.y -= (vars.labels.padding*scale[0])/2; + var y = text.attr("transform").match(/translate\(([^a-z]+)\)/gi)[0]; + y = y.replace(/([^a-z])\s([^a-z])/gi, "$1,$2"); + y = y.split(","); + if (y.length > 1) { + y = y[y.length - 1]; + y = y.substring(0, y.length - 1); + bounds.y += parseFloat(y); + } + + } + else { + var background_data = [], + bounds = {}; + } + + var bg = group.selectAll("rect#d3plus_label_bg_"+d.d3plus.id) + .data(background_data), + bg_opacity = typeof label.background === "number" ? + label.background : + typeof label.background === "string" ? 1 : 0.6; + + function bg_style(elem) { + + var color = typeof label.background === "string" ? label.background : vars.background.value === "none" + ? "#ffffff" : vars.background.value + , fill = typeof label.background === "string" + ? label.background : color + , transform = text.attr("transform").split(")"); + transform.pop(); + transform.pop(); + transform.push(""); + transform = transform.join(")"); + + elem + .attr("fill",fill) + .attr(bounds) + .attr("transform",transform); + + } + + if (vars.draw.timing) { + + bg.exit().transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove(); + + bg.transition().duration(vars.draw.timing) + .attr("opacity",bg_opacity) + .call(bg_style); + + bg.enter().insert("rect",".d3plus_label") + .attr("id","d3plus_label_bg_"+d.d3plus.id) + .attr("class","d3plus_label_bg") + .attr("opacity",0) + .call(bg_style) + .transition().duration(vars.draw.timing) + .attr("opacity",bg_opacity); + + } + else { + + bg.exit().remove(); + + bg.enter().insert("rect",".d3plus_label") + .attr("id","d3plus_label_bg_"+d.d3plus.id) + .attr("class","d3plus_label_bg"); + + bg.attr("opacity",bg_opacity) + .call(bg_style); + + } + + } + + } + else { + delete d.d3plus_label; + d3.select(this).selectAll("text#d3plus_label_"+d.d3plus.id+", rect#d3plus_label_bg_"+d.d3plus.id) + .call(remove); + vars.g.labels.selectAll("text#d3plus_label_"+d.d3plus.id+", rect#d3plus_label_bg_"+d.d3plus.id) + .call(remove); + } + + } + else { + delete d.d3plus_label; + d3.select(this).selectAll("text#d3plus_label_"+d.d3plus.id+", rect#d3plus_label_bg_"+d.d3plus.id) + .call(remove); + vars.g.labels.selectAll("text#d3plus_label_"+d.d3plus.id+", rect#d3plus_label_bg_"+d.d3plus.id) + .call(remove); + } + }); + + if ( vars.dev.value ) print.timeEnd( timerString ); + + } + else { + + if ( vars.dev.value ) { + var timerString = "removing " + group + " labels"; + print.time( timerString ); + } + + selection.selectAll("text.d3plus_label, rect.d3plus_label_bg") + .call(remove); + + vars.g.labels.selectAll("text.d3plus_label, rect.d3plus_label_bg") + .call(remove); + + if ( vars.dev.value ) print.timeEnd( timerString ); + + } +} + +},{"../../../client/rtl.coffee":40,"../../../color/mix.coffee":46,"../../../color/text.coffee":50,"../../../core/console/print.coffee":52,"../../../core/fetch/text.js":66,"../../../core/fetch/value.coffee":67,"../../../string/list.coffee":174,"../../../textwrap/textwrap.coffee":200,"../../../util/copy.coffee":207,"./color.coffee":220,"./segments.coffee":233}],229:[function(require,module,exports){ +var copy = require("../../../util/copy.coffee"), + closest = require("../../../util/closest.coffee"), + events = require("../../../client/pointer.coffee"), + shapeStyle = require("./style.coffee"), + fetchValue = require("../../../core/fetch/value.coffee"); + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "line" shapes using svg:line +//------------------------------------------------------------------------------ +module.exports = function(vars,selection,enter,exit) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // The D3 line function that determines what variables to use for x and y + // positioning, as well as line interpolation defined by the user. + //---------------------------------------------------------------------------- + var line = d3.svg.line() + .x(function(d){ return d.d3plus.x; }) + .y(function(d){ return d.d3plus.y; }) + .interpolate(vars.shape.interpolate.value); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Divide each line into it's segments. We do this so that there can be gaps + // in the line and mouseover. + // + // Then, create new data group from values to become small nodes at each + // point on the line. + //---------------------------------------------------------------------------- + + var stroke = vars.size.value || vars.data.stroke.width, + discrete = vars[vars.axes.discrete], + hitarea = function(l){ + var s = stroke; + if (s.constructor !== Number) { + var v = fetchValue(vars, l, stroke); + if (v && v.length) s = d3.max(v); + else s = vars.data.stroke.width; + } + return s < 15 ? 15 : s; + }; + + var ticks = discrete.ticks.values.map(function(d){ + if (d.constructor === Date) return d.getTime(); + else return d; + }); + + selection.each(function(d){ + + var lastIndex = false, + segments = [], + nodes = [], + temp = copy(d), + group = d3.select(this); + + temp.values = []; + temp.segment_key = temp.key; + d.values.forEach(function(v,i,arr){ + + var k = fetchValue(vars, v, discrete.value); + + if (k.constructor === Date) k = k.getTime(); + + var index = ticks.indexOf(closest(ticks,k)); + + if (lastIndex === false || lastIndex === index - 1) { + temp.values.push(v); + temp.segment_key += "_" + index; + } + else { + if (temp.values.length > 1) { + segments.push(temp); + } + else { + nodes.push(temp.values[0]); + } + temp = copy(d); + temp.values = [v]; + } + + if ( i === arr.length - 1 ) { + if (temp.values.length > 1) { + segments.push(temp); + } + else { + nodes.push(temp.values[0]); + } + } + + lastIndex = index; + + }); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Bind segment data to "paths" + //-------------------------------------------------------------------------- + var paths = group.selectAll("path.d3plus_line") + .data(segments, function(d){ + if (!d.d3plus) d.d3plus = {}; + d.d3plus.shape = "line"; + return d.segment_key; + }); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Bind node data to "rects" + //-------------------------------------------------------------------------- + var rects = group.selectAll("rect.d3plus_anchor") + .data(nodes, function(d){ + if (!d.d3plus) d.d3plus = {}; + d.d3plus.r = stroke; + return d.d3plus.id; + }); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" and "rects" Enter/Update + //-------------------------------------------------------------------------- + if (vars.draw.timing) { + + paths.exit().transition().duration(vars.draw.timing) + .attr("opacity", 0) + .remove(); + + paths.transition().duration(vars.draw.timing) + .attr("d",function(d){ return line(d.values); }) + .call(shapeStyle,vars); + + paths.enter().append("path") + .attr("class","d3plus_line") + .style("stroke-linecap","round") + .attr("d", function(d){ return line(d.values); }) + .call(shapeStyle,vars) + .attr("opacity", 0) + .transition().duration(vars.draw.timing) + .attr("opacity", 1); + + rects.enter().append("rect") + .attr("class","d3plus_anchor") + .attr("id",function(d){ return d.d3plus.id; }) + .call(init) + .call(shapeStyle,vars); + + rects.transition().duration(vars.draw.timing) + .call(update) + .call(shapeStyle,vars); + + rects.exit().transition().duration(vars.draw.timing) + .call(init) + .remove(); + + } + else { + + paths.exit().remove(); + + paths.enter().append("path") + .attr("class","d3plus_line") + .style("stroke-linecap","round"); + + paths + .attr("d",function(d){ return line(d.values); }) + .call(shapeStyle,vars); + + rects.enter().append("rect") + .attr("class","d3plus_anchor") + .attr("id",function(d){ + return d.d3plus.id; + }); + + rects.exit().remove(); + + rects.call(update) + .call(shapeStyle,vars); + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Create mouse event lines + //-------------------------------------------------------------------------- + var mouse = group.selectAll("path.d3plus_mouse") + .data(segments, function(d){ + return d.segment_key; + }); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Mouse "paths" Enter + //-------------------------------------------------------------------------- + mouse.enter().append("path") + .attr("class","d3plus_mouse") + .attr("d", function(l){ return line(l.values); }) + .style("stroke","black") + .style("stroke-width",hitarea) + .style("fill","none") + .style("stroke-linecap","round") + .attr("opacity",0); + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Mouse "paths" Update + //-------------------------------------------------------------------------- + mouse + .on(events.over,function(m){ + if (!vars.draw.frozen && vars.mouse.value && vars.mouse.over.value) mouseStyle(vars, this, stroke, 2); + }) + .on(events.out,function(d){ + if (!vars.draw.frozen && vars.mouse.value && vars.mouse.out.value) mouseStyle(vars, this, stroke, 0); + }); + + if (vars.draw.timing) { + + mouse.transition().duration(vars.draw.timing) + .attr("d",function(l){ return line(l.values); }) + .style("stroke-width",hitarea); + + } + else { + + mouse.attr("d",function(l){ return line(l.values); }) + .style("stroke-width",hitarea); + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Mouse "paths" Exit + //-------------------------------------------------------------------------- + mouse.exit().remove(); + + }); + +}; + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// The position and size of each anchor point on enter and exit. +//---------------------------------------------------------------------------- +function init(n) { + + n + .attr("x",function(d){ + return d.d3plus.x; + }) + .attr("y",function(d){ + return d.d3plus.y; + }) + .attr("width",0) + .attr("height",0); + +} + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// The position and size of each anchor point on update. +//---------------------------------------------------------------------------- +function update(n,mod) { + + if (mod === undefined) mod = 0; + + n + .attr("x",function(d){ + var w = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.width; + return d.d3plus.x - ((w/2)+(mod/2)); + }) + .attr("y",function(d){ + var h = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.height; + return d.d3plus.y - ((h/2)+(mod/2)); + }) + .attr("width",function(d){ + var w = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.width; + return w+mod; + }) + .attr("height",function(d){ + var h = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.height; + return h+mod; + }) + .attr("rx",function(d){ + var w = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.width; + return (w+mod)/2; + }) + .attr("ry",function(d){ + var h = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.height; + return (h+mod)/2; + }); + +} + +function mouseStyle(vars, elem, stroke, mod) { + + var timing = vars.draw.timing ? vars.timing.mouseevents : 0; + if (mod === undefined) mod = 0; + + if (timing) { + + d3.select(elem.parentNode).selectAll("path.d3plus_line") + .transition().duration(timing) + .style("stroke-width",function(l){ + var s = stroke; + if (s.constructor !== Number) { + var v = fetchValue(vars, l, stroke); + if (v && v.length) s = d3.max(v); + else s = vars.data.stroke.width; + } + return s + mod; + }); + + d3.select(elem.parentNode).selectAll("rect") + .transition().duration(timing) + .style("stroke-width",function(l){ + var s = stroke; + if (s.constructor !== Number) { + var v = fetchValue(vars, l, stroke); + if (v && v.length) s = d3.max(v); + else s = vars.data.stroke.width; + } + return s; + }) + .call(update, mod); + + } + else { + + d3.select(elem.parentNode).selectAll("path.d3plus_line") + .style("stroke-width",function(l){ + var s = stroke; + if (s.constructor !== Number) { + var v = fetchValue(vars, l, stroke); + if (v && v.length) s = d3.max(v); + else s = vars.data.stroke.width; + } + return s + mod; + }); + + d3.select(elem.parentNode).selectAll("rect") + .style("stroke-width",function(l){ + var s = stroke; + if (s.constructor !== Number) { + var v = fetchValue(vars, l, stroke); + if (v && v.length) s = d3.max(v); + else s = vars.data.stroke.width; + } + return s; + }) + .call(update, mod); + } + +} + +},{"../../../client/pointer.coffee":38,"../../../core/fetch/value.coffee":67,"../../../util/closest.coffee":206,"../../../util/copy.coffee":207,"./style.coffee":234}],230:[function(require,module,exports){ +module.exports = function(vars) { + + var edges = vars.returned.edges || []; + + var paths = vars.g.edges.selectAll("g.d3plus_edge_path") + .data(edges, function(d){ + d.d3plus.id = "path_" + d[vars.edges.source][vars.id.value] + "_" + d[vars.edges.target][vars.id.value]; + return d.d3plus.id; + }); + + function pathStyles(p) { + p + .attr("d", vars.edges.path) + .style("stroke-width", function(d) { + return Math.max(1, d.dy); + }) + .style("stroke", "#ddd") + .style("fill", "none") + .attr("transform", function(d){ + return "translate(" + d.d3plus.x + "," + d.d3plus.y + ")"; + }); + } + + if (vars.draw.timing) { + + paths.exit().transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove(); + + paths.selectAll("text.d3plus_label, rect.d3plus_label_bg") + .transition().duration(vars.draw.timing/2) + .attr("opacity",0) + .remove(); + + paths.selectAll("path") + .data(function(d){ return [d] }) + .transition().duration(vars.draw.timing) + .call(pathStyles); + + paths.enter().append("g") + .attr("class","d3plus_edge_path") + .append("path") + .style("stroke-width", 0) + .transition().duration(vars.draw.timing) + .call(pathStyles); + + } + else { + + paths.exit().remove(); + + paths.selectAll("text.d3plus_label, rect.d3plus_label_bg") + .remove(); + + paths.selectAll("path") + .data(function(d){ return [d] }) + .call(pathStyles); + + paths.enter().append("g") + .attr("class","d3plus_edge_path") + .append("path") + .call(pathStyles); + + } + +} + +},{}],231:[function(require,module,exports){ +var angles, interpolates, radii, shapeStyle; + +shapeStyle = require("./style.coffee"); + +radii = {}; + +angles = {}; + +interpolates = { + r: {}, + a: {} +}; + +module.exports = function(vars, selection, enter, exit) { + var data, newRadial, nextLevel, radial, radialTween; + nextLevel = vars.id.nesting[vars.depth.value + 1]; + radial = d3.svg.line.radial().interpolate("linear-closed").radius(function(d) { + return d.d3plus.r; + }).angle(function(d) { + return d.d3plus.a; + }); + data = function(d) { + if (vars.labels.value) { + if (d.d3plus.label) { + d.d3plus_label = d.d3plus.label; + } else { + delete d.d3plus_label; + } + } + return [d]; + }; + if (vars.draw.timing) { + selection.each(function(d) { + var c, j, len, ref, results; + ref = d[nextLevel]; + results = []; + for (j = 0, len = ref.length; j < len; j++) { + c = ref[j]; + results.push(c.d3plus.id = c[vars.id.value] + "_" + c[nextLevel]); + } + return results; + }); + newRadial = d3.svg.line.radial().interpolate("linear-closed").radius(function(d, i) { + if (radii[d.d3plus.id] === void 0) { + radii[d.d3plus.id] = 0; + } + if (isNaN(radii[d.d3plus.id])) { + radii[d.d3plus.id] = d.d3plus.r; + } + return radii[d.d3plus.id]; + }).angle(function(d, i) { + if (angles[d.d3plus.id] === void 0) { + angles[d.d3plus.id] = d.d3plus.a; + } + if (isNaN(angles[d.d3plus.id])) { + angles[d.d3plus.id] = d.d3plus.a; + } + return angles[d.d3plus.id]; + }); + radialTween = function(arcs, newRadius) { + return arcs.attrTween("d", function(d) { + var a, c, i, j, len, r, ref; + ref = d[nextLevel]; + for (i = j = 0, len = ref.length; j < len; i = ++j) { + c = ref[i]; + a = c.d3plus.a; + if (newRadius === void 0) { + r = c.d3plus.r; + } else if (newRadius === 0) { + r = 0; + } + interpolates.a[c.d3plus.id] = d3.interpolate(angles[c.d3plus.id], a); + interpolates.r[c.d3plus.id] = d3.interpolate(radii[c.d3plus.id], r); + } + return function(t) { + var k, len1, ref1; + ref1 = d[nextLevel]; + for (i = k = 0, len1 = ref1.length; k < len1; i = ++k) { + c = ref1[i]; + angles[c.d3plus.id] = interpolates.a[c.d3plus.id](t); + radii[c.d3plus.id] = interpolates.r[c.d3plus.id](t); + } + return newRadial(d[nextLevel]); + }; + }); + }; + enter.append("path").attr("class", "d3plus_data").call(shapeStyle, vars).attr("d", function(d) { + return newRadial(d[nextLevel]); + }); + selection.selectAll("path.d3plus_data").data(data).transition().duration(vars.draw.timing).call(shapeStyle, vars).call(radialTween); + exit.selectAll("path.d3plus_data").transition().duration(vars.draw.timing).call(radialTween, 0); + } else { + enter.append("path").attr("class", "d3plus_data"); + selection.selectAll("path.d3plus_data").data(data).call(shapeStyle, vars).attr("d", function(d) { + return radial(d[nextLevel]); + }); + } +}; + + +},{"./style.coffee":234}],232:[function(require,module,exports){ +var shapeStyle; + +shapeStyle = require("./style.coffee"); + +module.exports = function(vars, selection, enter, exit) { + var data, init, update; + data = function(d) { + var h, w; + if (vars.labels.value && !d.d3plus.label) { + w = (d.d3plus.r ? d.d3plus.r * 2 : d.d3plus.width); + h = (d.d3plus.r ? d.d3plus.r * 2 : d.d3plus.height); + d.d3plus_label = { + w: w, + h: h, + x: 0, + y: 0 + }; + d.d3plus_share = { + w: w, + h: h, + x: 0, + y: 0 + }; + d.d3plus_label.shape = (d.d3plus.shape === "circle" ? "circle" : "square"); + } else if (d.d3plus.label) { + d.d3plus_label = d.d3plus.label; + } else { + delete d.d3plus_label; + } + return [d]; + }; + init = function(nodes) { + return nodes.attr("x", function(d) { + if (d.d3plus.init && "x" in d.d3plus.init) { + return d.d3plus.init.x; + } else { + if (d.d3plus.init && "width" in d.d3plus.init) { + return -d.d3plus.width / 2; + } else { + return 0; + } + } + }).attr("y", function(d) { + if (d.d3plus.init && "y" in d.d3plus.init) { + return d.d3plus.init.y; + } else { + if (d.d3plus.init && "height" in d.d3plus.init) { + return -d.d3plus.height / 2; + } else { + return 0; + } + } + }).attr("width", function(d) { + if (d.d3plus.init && "width" in d.d3plus.init) { + return d.d3plus.init.width; + } else { + return 0; + } + }).attr("height", function(d) { + if (d.d3plus.init && "height" in d.d3plus.init) { + return d.d3plus.init.height; + } else { + return 0; + } + }); + }; + update = function(nodes) { + return nodes.attr("x", function(d) { + var w; + w = d.d3plus.r ? d.d3plus.r * 2 : d.d3plus.width; + return -w / 2; + }).attr("y", function(d) { + var h; + h = d.d3plus.r ? d.d3plus.r * 2 : d.d3plus.height; + return -h / 2; + }).attr("width", function(d) { + if (d.d3plus.r) { + return d.d3plus.r * 2; + } else { + return d.d3plus.width; + } + }).attr("height", function(d) { + if (d.d3plus.r) { + return d.d3plus.r * 2; + } else { + return d.d3plus.height; + } + }).attr("rx", function(d) { + var rounded, w; + rounded = d.d3plus.shape === "circle"; + w = d.d3plus.r ? d.d3plus.r * 2 : d.d3plus.width; + if (rounded) { + return (w + 2) / 2; + } else { + return 0; + } + }).attr("ry", function(d) { + var h, rounded; + rounded = d.d3plus.shape === "circle"; + h = d.d3plus.r ? d.d3plus.r * 2 : d.d3plus.height; + if (rounded) { + return (h + 2) / 2; + } else { + return 0; + } + }).attr("transform", function(d) { + if ("rotate" in d.d3plus) { + return "rotate(" + d.d3plus.rotate + ")"; + } else { + return ""; + } + }).attr("shape-rendering", function(d) { + if (d.d3plus.shape === "square" && (!("rotate" in d.d3plus))) { + return vars.shape.rendering.value; + } else { + return "auto"; + } + }); + }; + if (vars.draw.timing) { + enter.append("rect").attr("class", "d3plus_data").call(init).call(shapeStyle, vars); + selection.selectAll("rect.d3plus_data").data(data).transition().duration(vars.draw.timing).call(update).call(shapeStyle, vars); + return exit.selectAll("rect.d3plus_data").transition().duration(vars.draw.timing).call(init); + } else { + enter.append("rect").attr("class", "d3plus_data"); + return selection.selectAll("rect.d3plus_data").data(data).call(update).call(shapeStyle, vars); + } +}; + + +},{"./style.coffee":234}],233:[function(require,module,exports){ +var fetchValue; + +fetchValue = require("../../../core/fetch/value.coffee"); + +module.exports = function(vars, d, segment) { + var ret; + ret = vars[segment].value; + if (ret) { + if (segment in d.d3plus) { + return d.d3plus[segment]; + } else { + return fetchValue(vars, d, ret); + } + } else { + return d.d3plus[segment]; + } +}; + + +},{"../../../core/fetch/value.coffee":67}],234:[function(require,module,exports){ +var color, ie, value; + +color = require("./color.coffee"); + +ie = require("../../../client/ie.js"); + +value = require("../../../core/fetch/value.coffee"); + +module.exports = function(nodes, vars) { + return nodes.attr("fill", function(d) { + if (d.d3plus && d.d3plus.spline) { + return "none"; + } else { + return color(d, vars); + } + }).style("stroke", function(d) { + var c; + if (d.d3plus && d.d3plus.stroke) { + return d.d3plus.stroke; + } else { + c = d.values ? color(d.values[0], vars) : color(d, vars, true); + return d3.rgb(c).darker(0.6); + } + }).style("stroke-width", function(d) { + var v; + if (ie && vars.types[vars.type.value].zoom) { + return 0; + } + if (d.d3plus.shape === "line" && vars.size.value) { + if (vars.size.value.constructor === Number) { + return vars.size.value; + } + v = value(vars, d, vars.size.value); + if (v && v.length) { + return d3.max(v); + } + } + return vars.data.stroke.width; + }).attr("opacity", vars.data.opacity).attr("vector-effect", "non-scaling-stroke"); +}; + + +},{"../../../client/ie.js":37,"../../../core/fetch/value.coffee":67,"./color.coffee":220}],235:[function(require,module,exports){ +var shapeStyle = require("./style.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "square" and "circle" shapes using svg:rect +//------------------------------------------------------------------------------ +module.exports = function(vars,selection,enter,exit) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialize check scale on enter and exit. + //---------------------------------------------------------------------------- + function init(paths){ + paths.attr("d", d3.svg.symbol().type("triangle-down").size(10)) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Change scale of check on update. + //--------------------------------------------------------------------------- + function update(paths){ + paths.attr("d", d3.svg.symbol().type("triangle-down").size(function(d){ + var smaller_dim = Math.min(d.d3plus.width, d.d3plus.height); + return d3.scale.pow().exponent(2)(smaller_dim/2); + })) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Enter + //---------------------------------------------------------------------------- + enter.append("path").attr("class","d3plus_data") + .call(init) + .call(shapeStyle,vars) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Update + //---------------------------------------------------------------------------- + selection.selectAll("path.d3plus_data") + .data(function(d) { + return [d]; + }) + + if (vars.draw.timing) { + selection.selectAll("path.d3plus_data") + .transition().duration(vars.draw.timing) + .call(update) + .call(shapeStyle,vars) + } + else { + selection.selectAll("path.d3plus_data") + .call(update) + .call(shapeStyle,vars) + } + +} + +},{"./style.coffee":234}],236:[function(require,module,exports){ +var shapeStyle = require("./style.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws "square" and "circle" shapes using svg:rect +//------------------------------------------------------------------------------ +module.exports = function(vars,selection,enter,exit) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialize check scale on enter and exit. + //---------------------------------------------------------------------------- + function init(paths){ + paths.attr("d", d3.svg.symbol().type("triangle-up").size(10)) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Change scale of check on update. + //--------------------------------------------------------------------------- + function update(paths){ + paths.attr("d", d3.svg.symbol().type("triangle-up").size(function(d){ + var smaller_dim = Math.min(d.d3plus.width, d.d3plus.height); + return d3.scale.pow().exponent(2)(smaller_dim/2); + })) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Enter + //---------------------------------------------------------------------------- + enter.append("path").attr("class","d3plus_data") + .call(init) + .call(shapeStyle,vars) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // "paths" Update + //---------------------------------------------------------------------------- + selection.selectAll("path.d3plus_data") + .data(function(d) { + return [d]; + }) + + if (vars.draw.timing) { + selection.selectAll("path.d3plus_data") + .transition().duration(vars.draw.timing) + .call(update) + .call(shapeStyle,vars) + } + else { + selection.selectAll("path.d3plus_data") + .call(update) + .call(shapeStyle,vars) + } + +} + +},{"./style.coffee":234}],237:[function(require,module,exports){ +module.exports = function(vars, selection, enter, exit) { + var d, data, init, marker, orient, pos, position, size, style; + data = function(d) { + if (d.d3plus.text) { + d.d3plus_label = { + w: size, + h: size, + x: 0, + y: 0, + background: "#fff", + resize: false, + angle: ["left", "right"].indexOf(d.d3plus.position) >= 0 ? 90 : 0 + }; + } else if (d.d3plus.label) { + d.d3plus_label = d.d3plus.label; + } else { + delete d.d3plus_label; + } + return [d]; + }; + style = function(line) { + return line.style("stroke-width", vars.data.stroke.width).style("stroke", "#444").attr("fill", "none").attr("shape-rendering", vars.shape.rendering.value); + }; + init = function(line) { + return line.attr("x1", 0).attr("x2", 0).attr("y1", 0).attr("y2", 0); + }; + position = function(line) { + return line.attr("x1", function(d) { + var offset, w, x; + if (["top", "bottom"].indexOf(d.d3plus.position) >= 0) { + return 0; + } else { + offset = d.d3plus.offset || 0; + w = d.d3plus.width || 0; + x = offset < 0 ? -w : w; + return x + offset; + } + }).attr("x2", function(d) { + if (["top", "bottom"].indexOf(d.d3plus.position) >= 0) { + return 0; + } else { + return d.d3plus.offset || 0; + } + }).attr("y1", function(d) { + var h, offset, y; + if (["left", "right"].indexOf(d.d3plus.position) >= 0) { + return 0; + } else { + offset = d.d3plus.offset || 0; + h = d.d3plus.height || 0; + y = offset < 0 ? -h : h; + return y + offset; + } + }).attr("y2", function(d) { + if (["left", "right"].indexOf(d.d3plus.position) >= 0) { + return 0; + } else { + return d.d3plus.offset || 0; + } + }).attr("marker-start", "url(#d3plus_whisker_marker)"); + }; + marker = vars.defs.selectAll("#d3plus_whisker_marker").data([0]); + marker.enter().append("marker").attr("id", "d3plus_whisker_marker").attr("markerUnits", "userSpaceOnUse").style("overflow", "visible").append("line"); + d = selection.datum(); + if (d) { + pos = d.d3plus.position; + orient = ["top", "bottom"].indexOf(pos) >= 0 ? "horizontal" : "vertical"; + size = orient === "horizontal" ? d.d3plus.width : d.d3plus.height; + } else { + orient = "horizontal"; + size = 0; + } + marker.select("line").attr("x1", orient === "horizontal" ? -size / 2 : 0).attr("x2", orient === "horizontal" ? size / 2 : 0).attr("y1", orient === "vertical" ? -size / 2 : 0).attr("y2", orient === "vertical" ? size / 2 : 0).call(style).style("stroke-width", vars.data.stroke.width * 2); + if (vars.draw.timing) { + enter.append("line").attr("class", "d3plus_data").call(style).call(init); + selection.selectAll("line.d3plus_data").data(data).transition().duration(vars.draw.timing).call(style).call(position); + exit.selectAll("line.d3plus_data").transition().duration(vars.draw.timing).call(init); + } else { + enter.append("line").attr("class", "d3plus_data"); + selection.selectAll("line.d3plus_data").data(data).call(style).call(position); + } +}; + + +},{}],238:[function(require,module,exports){ +var events = require("../../../client/pointer.coffee"), + prefix = require("../../../client/prefix.coffee"), + print = require("../../../core/console/print.coffee"), + touch = require("../../../client/touch.coffee"), + touchEvent = require("../zoom/propagation.coffee"); + +// Enter SVG Elements +module.exports = function(vars) { + + if ( vars.dev.value ) print.time("creating SVG elements"); + + // Enter SVG + vars.svg = vars.container.value.selectAll("svg#d3plus").data([0]); + vars.svg.enter().insert("svg","#d3plus_message") + .attr("id","d3plus") + .attr("width",vars.width.value) + .attr("height",vars.height.value) + .attr("xmlns","http://www.w3.org/2000/svg") + .attr("xmlns:xlink","http://www.w3.org/1999/xlink"); + + // Enter BG Rectangle + vars.g.bg = vars.svg.selectAll("rect#bg").data(["bg"]); + vars.g.bg.enter().append("rect") + .attr("id","bg") + .attr("fill",vars.background.value) + .attr("stroke", "none") + .attr("width",vars.width.value) + .attr("height",vars.height.value); + + // Enter Timeline Group + vars.g.timeline = vars.svg.selectAll("g#timeline").data(["timeline"]); + vars.g.timeline.enter().append("g") + .attr("id","timeline") + .attr("transform","translate(0,"+vars.height.value+")"); + + // Enter Key Group + vars.g.legend = vars.svg.selectAll("g#key").data(["key"]); + vars.g.legend.enter().append("g") + .attr("id","key") + .attr("transform","translate(0,"+vars.height.value+")"); + + // Enter Footer Group + vars.g.footer = vars.svg.selectAll("g#footer").data(["footer"]); + vars.g.footer.enter().append("g") + .attr("id","footer") + .attr("transform","translate(0,"+vars.height.value+")"); + + // Enter App Clipping Mask + var clipID = "clipping_" + vars.container.id; + vars.g.clipping = vars.svg.selectAll("#clipping").data(["clipping"]); + vars.g.clipping.enter().append("clipPath") + .attr("id", clipID) + .append("rect") + .attr("width",vars.width.viz) + .attr("height",vars.height.viz); + + // Enter Container Group + vars.g.container = vars.svg.selectAll("g#container").data(["container"]); + vars.g.container.enter().append("g") + .attr("id","container") + .attr("clip-path","url(#" + clipID + ")") + .attr("transform","translate("+vars.margin.left+","+vars.margin.top+")"); + + // Enter Zoom Group + vars.g.zoom = vars.g.container.selectAll("g#zoom").data(["zoom"]); + vars.g.zoom.enter().append("g") + .attr("id","zoom"); + + // Enter App Background Group + vars.g.viz = vars.g.zoom.selectAll("g#d3plus_viz").data(["d3plus_viz"]); + vars.g.viz.enter().append("g") + .attr("id","d3plus_viz"); + + // Enter App Overlay Rect + vars.g.overlay = vars.g.viz.selectAll("rect#d3plus_overlay").data([{"id":"d3plus_overlay"}]); + vars.g.overlay.enter().append("rect") + .attr("id","d3plus_overlay") + .attr("width",vars.width.value) + .attr("height",vars.height.value) + .attr("opacity",0); + + vars.g.overlay + .on(events.move,function(d){ + + if (touch) touchEvent(vars, d3.event); + + if (vars.types[vars.type.value].zoom && vars.zoom.pan.value && + vars.zoom.behavior.scaleExtent()[0] < vars.zoom.scale) { + d3.select(this).style("cursor",prefix()+"grab"); + } + else { + d3.select(this).style("cursor","auto"); + } + + }) + .on(events.up,function(d){ + + if (touch) touchEvent(vars, d3.event); + + if (vars.types[vars.type.value].zoom && vars.zoom.pan.value && + vars.zoom.behavior.scaleExtent()[0] < vars.zoom.scale) { + d3.select(this).style("cursor",prefix()+"grab"); + } + else { + d3.select(this).style("cursor","auto"); + } + + }) + .on(events.down,function(d){ + + if (touch) touchEvent(vars, d3.event); + + if (vars.types[vars.type.value].zoom && vars.zoom.pan.value && + vars.zoom.behavior.scaleExtent()[0] < vars.zoom.scale) { + d3.select(this).style("cursor",prefix()+"grabbing"); + } + else { + d3.select(this).style("cursor","auto"); + } + + }); + + // Enter App Background Group + vars.g.app = vars.g.viz.selectAll("g#app").data(["app"]); + vars.g.app.enter().append("g") + .attr("id","app"); + + // Enter Edges Group + vars.g.edges = vars.g.viz.selectAll("g#edges").data(["edges"]); + vars.g.edges.enter().append("g") + .attr("id","edges") + .attr("opacity",0); + + // Enter Edge Focus Group + vars.g.edge_focus = vars.g.viz.selectAll("g#focus").data(["focus"]); + vars.g.edge_focus.enter().append("g") + .attr("id","focus"); + + // Enter Edge Hover Group + vars.g.edge_hover = vars.g.viz.selectAll("g#edge_hover").data(["edge_hover"]); + vars.g.edge_hover.enter().append("g") + .attr("id","edge_hover") + .attr("opacity",0); + + // Enter App Data Group + vars.g.data = vars.g.viz.selectAll("g#data").data(["data"]); + vars.g.data.enter().append("g") + .attr("id","data") + .attr("opacity",0); + + // Enter Data Focus Group + vars.g.data_focus = vars.g.viz.selectAll("g#data_focus").data(["data_focus"]); + vars.g.data_focus.enter().append("g") + .attr("id","data_focus"); + + // Enter Top Label Group + vars.g.labels = vars.g.viz.selectAll("g#d3plus_labels").data(["d3plus_labels"]); + vars.g.labels.enter().append("g") + .attr("id","d3plus_labels"); + + vars.defs = vars.svg.selectAll("defs").data(["defs"]); + vars.defs.enter().append("defs"); + + if ( vars.dev.value ) print.timeEnd("creating SVG elements"); + +}; + +},{"../../../client/pointer.coffee":38,"../../../client/prefix.coffee":39,"../../../client/touch.coffee":43,"../../../core/console/print.coffee":52,"../zoom/propagation.coffee":253}],239:[function(require,module,exports){ +var print = require("../../../core/console/print.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Updating Elements +//------------------------------------------------------------------------------ +module.exports = function(vars) { + + if ( vars.dev.value ) print.time("updating SVG elements") + + if ( vars.draw.timing ) { + + // Update Parent Element + vars.container.value.transition().duration(vars.draw.timing) + .style("width",vars.width.value+"px") + .style("height",vars.height.value+"px") + + // Update SVG + vars.svg.transition().duration(vars.draw.timing) + .attr("width",vars.width.value) + .attr("height",vars.height.value) + + // Update Background Rectangle + vars.g.bg.transition().duration(vars.draw.timing) + .attr("width",vars.width.value) + .attr("height",vars.height.value) + .attr("fill",vars.background.value); + + // Update App Clipping Rectangle + vars.g.clipping.select("rect").transition().duration(vars.draw.timing) + .attr("width",vars.width.viz) + .attr("height",vars.height.viz) + + // Update Container Groups + vars.g.container.transition().duration(vars.draw.timing) + .attr("transform","translate("+vars.margin.left+","+vars.margin.top+")") + + } + else { + + // Update Parent Element + vars.container.value + .style("width",vars.width.value+"px") + .style("height",vars.height.value+"px") + + // Update SVG + vars.svg + .attr("width",vars.width.value) + .attr("height",vars.height.value) + + // Update Background Rectangle + vars.g.bg + .attr("width",vars.width.value) + .attr("height",vars.height.value) + .attr("fill",vars.background.value); + + // Update App Clipping Rectangle + vars.g.clipping.select("rect") + .attr("width",vars.width.viz) + .attr("height",vars.height.viz) + + // Update Container Groups + vars.g.container + .attr("transform","translate("+vars.margin.left+","+vars.margin.top+")") + + } + + if ( vars.dev.value ) print.timeEnd("updating SVG elements") + +} + +},{"../../../core/console/print.coffee":52}],240:[function(require,module,exports){ +var arraySort = require("../../../array/sort.coffee"), + createTooltip = require("../../../tooltip/create.js"), + dataNest = require("../../../core/data/nest.js"), + fetchData = require("./data.js"), + fetchColor = require("../../../core/fetch/color.coffee"), + fetchText = require("../../../core/fetch/text.js"), + fetchValue = require("../../../core/fetch/value.coffee"), + mergeObject = require("../../../object/merge.coffee"), + removeTooltip = require("../../../tooltip/remove.coffee"), + segments = require("../shapes/segments.coffee"), + scroll = require("../../../client/scroll.js"), + uniques = require("../../../util/uniques.coffee"), + validObject = require("../../../object/validate.coffee"), + zoomDirection = require("../zoom/direction.coffee"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates correctly formatted tooltip for Apps +//------------------------------------------------------------------- +module.exports = function(params) { + + if ( !( "d3plus" in params.data ) ) { + params.data.d3plus = {} + } + + var vars = params.vars, + d = params.data, + dataDepth = "d3plus" in d && "depth" in d.d3plus ? d.d3plus.depth : vars.depth.value, + ex = params.ex, + mouse = params.mouseevents ? params.mouseevents : false, + arrow = "arrow" in params ? params.arrow : true, + id = fetchValue(vars,d,vars.id.value), + tooltip_id = params.id || vars.type.value + + if ((d3.event && d3.event.type == "click") && (vars.tooltip.html.value || vars.tooltip.value.long) && !("fullscreen" in params)) { + var fullscreen = true, + arrow = false, + mouse = true, + length = "long", + footer = vars.footer.value + + vars.covered = true + } + else { + var fullscreen = false, + align = params.anchor || vars.tooltip.anchor, + length = params.length || "short", + zoom = zoomDirection(d, vars) + + if (zoom === -1) { + var key = vars.id.nesting[dataDepth-1], + parent = fetchValue(vars,id,key) + } + + var text = ""; + if (!(!vars.mouse.click.value || (vars.mouse.viz && vars.mouse.viz.click === false))) { + if (zoom === 1 && vars.zoom.value) { + var text = vars.format.value(vars.format.locale.value.ui.expand) + } + else if (zoom === -1 && vars.zoom.value && vars.history.states.length && !vars.tooltip.value.long) { + var text = vars.format.value(vars.format.locale.value.ui.collapse) + } + else if (!vars.small && length == "short" && (vars.tooltip.html.value || vars.tooltip.value.long) && (vars.focus.value.length !== 1 || vars.focus.value[0] != id)) { + var text = vars.format.locale.value.ui.moreInfo + } + else if (length == "long") { + var text = vars.footer.value || "" + } + } + + var footer = text.length ? vars.format.value(text,{"key": "footer", "vars": vars}) : false + + } + + if ("x" in params) { + var x = params.x; + } + else if (vars.types[vars.type.value].tooltip === "static") { + var x = d.d3plus.x; + if (vars.zoom.translate && vars.zoom.scale) { + x = vars.zoom.translate[0]+x*vars.zoom.scale; + } + x += vars.margin.left; + if (params.length !== "long") { + y += scroll.x(); + x += vars.container.value.node().getBoundingClientRect().left; + x += parseFloat(vars.container.value.style("padding-left"), 10); + } + } + else { + var x = d3.mouse(d3.select("html").node())[0]; + } + + if ("y" in params) { + var y = params.y; + } + else if (vars.types[vars.type.value].tooltip == "static") { + var y = d.d3plus.y; + if (vars.zoom.translate && vars.zoom.scale) { + y = vars.zoom.translate[1]+y*vars.zoom.scale; + } + y += vars.margin.top; + if (params.length !== "long") { + y += scroll.y(); + y += vars.container.value.node().getBoundingClientRect().top; + y += parseFloat(vars.container.value.style("padding-top"), 10); + } + } + else { + var y = d3.mouse(d3.select("html").node())[1]; + } + + if ("offset" in params) { + var offset = params.offset; + } + else if (vars.types[vars.type.value].tooltip == "static") { + var offset = d.d3plus.r ? d.d3plus.r : d.d3plus.height/2; + if (vars.zoom.scale) { + offset = offset * vars.zoom.scale; + } + } + else { + var offset = 3; + } + + function make_tooltip(html) { + + var titleDepth = "depth" in params ? params.depth : dataDepth; + + var ex = {}, + children, + depth = vars.id.nesting[titleDepth+1] in d ? titleDepth + 1 : titleDepth, + nestKey = vars.id.nesting[depth], + nameList = "merged" in d.d3plus ? d.d3plus.merged : d[nestKey]; + + if (!(nameList instanceof Array)) nameList = [nameList]; + + var dataValue = fetchValue( vars , d , vars.size.value ); + + if (vars.tooltip.children.value) { + + nameList = nameList.slice(0); + if (nameList.length > 1 && validObject(nameList[0])) nameList = dataNest(vars, nameList, [nestKey]); + + if (vars.size.value && validObject(nameList[0])) { + + var namesNoValues = []; + var namesWithValues = nameList.filter(function(n){ + var val = fetchValue(vars, n, vars.size.value); + if (val !== null && (!("d3plus" in n) || !n.d3plus.merged)) { + return true; + } + else { + namesNoValues.push(n); + } + }); + + arraySort(namesWithValues, vars.size.value, "desc", [], vars); + + nameList = namesWithValues.concat(namesNoValues); + + } + + var maxChildrenShownInShortMode = vars.tooltip.children.value === true ? 3 : vars.tooltip.children.value; + var limit = length === "short" ? maxChildrenShownInShortMode : vars.data.large, + listLength = nameList.length, + max = d3.min([listLength , limit]), + objs = []; + + children = {"values": []}; + for (var i = 0; i < max; i++) { + + if (!nameList.length) break; + + var obj = nameList.shift(), + name = fetchText(vars, obj, depth)[0], + id = validObject(obj) ? fetchValue(vars, obj, nestKey, depth) : obj; + + if (id !== d[vars.id.nesting[titleDepth]] && name && !children[name]) { + + var value = validObject(obj) ? fetchValue(vars, obj, vars.size.value, nestKey) : null, + color = fetchColor(vars, obj, nestKey); + + children[name] = value && !(value instanceof Array) ? vars.format.value(value, {"key": vars.size.value, "vars": vars, "data": obj}) : ""; + var child = {}; + child[name] = children[name]; + children.values.push(child); + + if (color) { + if ( !children.d3plus_colors ) children.d3plus_colors = {}; + children.d3plus_colors[name] = color; + } + + } + else { + i--; + } + + } + + if ( listLength > max ) { + children.d3plusMore = listLength - max; + } + + } + + if (d.d3plus.tooltip) { + ex = mergeObject(ex, d.d3plus.tooltip); + } + + function getLabel(method) { + return typeof vars[method].value === "string" ? vars[method].value : + vars.format.locale.value.method[method]; + } + + if ( vars.tooltip.size.value ) { + if (dataValue && typeof vars.size.value !== "number") { + ex[getLabel("size")] = dataValue; + } + if (vars.axes.opposite && vars[vars.axes.opposite].value !== vars.size.value) { + ex[getLabel(vars.axes.opposite)] = fetchValue(vars, d, vars[vars.axes.opposite].value); + } + if (vars.axes.opposite && vars[vars.axes.opposite + "2"].value !== vars.size.value) { + ex[getLabel(vars.axes.opposite + "2")] = fetchValue(vars, d, vars[vars.axes.opposite + "2"].value); + } + if (vars.color.valueScale) { + ex[getLabel("color")] = fetchValue(vars, d, vars.color.value); + } + } + + var active = segments(vars, d, "active"), + temp = segments(vars, d, "temp"), + total = segments(vars, d, "total"); + + if (typeof active == "number" && active > 0 && total) { + ex[getLabel("active")] = active+"/"+total+" ("+vars.format.value((active/total)*100, {"key": "share", "vars": vars, "data": d})+")"; + } + + if (typeof temp == "number" && temp > 0 && total) { + ex[getLabel("temp")] = temp+"/"+total+" ("+vars.format.value((temp/total)*100, {"key": "share", "vars": vars, "data": d})+")"; + } + + if ( vars.tooltip.share.value && d.d3plus.share ) { + ex.share = vars.format.value(d.d3plus.share*100, {"key": "share", "vars": vars, "data": d}); + } + + var depth = "depth" in params ? params.depth : dataDepth, + title = params.title || fetchText(vars,d,depth)[0], + icon = uniques(d, vars.icon.value, fetchValue, vars, vars.id.nesting[depth]), + tooltip_data = params.titleOnly ? [] : fetchData(vars,d,length,ex,children,depth); + + if (icon.length === 1 && typeof icon[0] === "string") { + icon = icon[0]; + } + else { + icon = false; + } + + if ((tooltip_data.length > 0 || footer) || ((!d.d3plus_label && length == "short" && title) || (d.d3plus_label && (!("visible" in d.d3plus_label) || ("visible" in d.d3plus_label && d.d3plus_label.visible === false))))) { + + if (!title) { + title = vars.format.value(id, {"key": vars.id.value, "vars": vars}); + } + + var depth = "d3plus" in d && "merged" in d.d3plus ? dataDepth - 1 : "depth" in params ? params.depth : dataDepth; + + if (depth < 0) depth = 0 + + depth = vars.id.nesting[depth] + + if (typeof vars.icon.style.value == "string") { + var icon_style = vars.icon.style.value + } + else if (typeof vars.icon.style.value == "object" && vars.icon.style.value[depth]) { + var icon_style = vars.icon.style.value[depth] + } + else { + var icon_style = "default" + } + + var width = vars.tooltip.small; + if (params.width) { + width = params.width; + } + else if (fullscreen) { + width = vars.tooltip.large; + } + + var parent = (!fullscreen && params.length !== "long") || (fullscreen && vars.tooltip.fullscreen.value) ? d3.select("body") : vars.container.value; + + if (!params.description && d && vars.tooltip.sub.value) { + params.description = fetchValue(vars, d, vars.tooltip.sub.value); + } + + createTooltip({ + "align": align, + "arrow": arrow, + "locale": vars.format.locale.value, + "background": vars.tooltip.background, + "curtain": vars.tooltip.curtain.color, + "curtainopacity": vars.tooltip.curtain.opacity, + "fontcolor": vars.tooltip.font.color, + "fontfamily": vars.tooltip.font.family.value, + "fontsize": vars.tooltip.font.size, + "fontweight": vars.tooltip.font.weight, + "data": tooltip_data, + "color": fetchColor(vars, d), + "allColors": true, + "footer": params.footer === false ? params.footer : footer, + "fullscreen": fullscreen, + "html": html, + "js": params.js, + "icon": icon, + "id": tooltip_id, + "max_height": params.maxheight, + "max_width": width, + "mouseevents": mouse, + "offset": offset, + "parent": parent, + "stacked": vars.tooltip.stacked.value, + "style": icon_style, + "title": title, + "description": params.description, + "width": !params.width && !fullscreen && tooltip_data.length == 0 ? "auto" : width, + "x": x, + "y": y + }) + + } + else { + removeTooltip(tooltip_id) + } + + } + + if (fullscreen || params.length === "long") { + + if (typeof vars.tooltip.html.value == "string") { + make_tooltip(vars.tooltip.html.value) + } + else if (typeof vars.tooltip.html.value == "function") { + make_tooltip(vars.tooltip.html.value(id)) + } + else if (vars.tooltip.html.value && typeof vars.tooltip.html.value == "object" && vars.tooltip.html.value.url) { + var tooltip_url = vars.tooltip.html.value.url; + if (typeof tooltip_url === "function") tooltip_url = tooltip_url(id); + d3.json(tooltip_url,function(data){ + var html = vars.tooltip.html.value.callback ? vars.tooltip.html.value.callback(data) : data + make_tooltip(html) + }) + } + else { + make_tooltip(params.html) + } + + } + else { + make_tooltip(params.html) + } + +} + +},{"../../../array/sort.coffee":34,"../../../client/scroll.js":41,"../../../core/data/nest.js":60,"../../../core/fetch/color.coffee":63,"../../../core/fetch/text.js":66,"../../../core/fetch/value.coffee":67,"../../../object/merge.coffee":171,"../../../object/validate.coffee":172,"../../../tooltip/create.js":201,"../../../tooltip/remove.coffee":203,"../../../util/uniques.coffee":210,"../shapes/segments.coffee":233,"../zoom/direction.coffee":250,"./data.js":241}],241:[function(require,module,exports){ +var copy = require("../../../util/copy.coffee"), + fetchValue = require("../../../core/fetch/value.coffee"), + fetchColor = require("../../../core/fetch/color.coffee"), + fetchText = require("../../../core/fetch/text.js"), + legible = require("../../../color/legible.coffee"), + mergeObject = require("../../../object/merge.coffee"), + prefix = require("../../../client/prefix.coffee"), + stringFormat = require("../../../string/format.js"), + validObject = require("../../../object/validate.coffee"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates a data object for the Tooltip +//------------------------------------------------------------------------------ +module.exports = function(vars, id, length, extras, children, depth) { + + if (vars.small) { + return [] + } + + if (!length) var length = "long" + if (length == "long") { + var other_length = "short" + } + else { + var other_length = "long" + } + + var extra_data = {} + if (extras && typeof extras == "string") extras = [extras] + else if (extras && typeof extras == "object") { + extra_data = mergeObject(extra_data,extras) + var extras = [] + for ( var k in extra_data ) { + extras.push(k) + } + } + else if (!extras) var extras = [] + + var tooltip_highlights = [] + + if (vars.tooltip.value instanceof Array) { + var a = vars.tooltip.value + } + else if (typeof vars.tooltip.value == "string") { + var a = [vars.tooltip.value] + } + else { + + if (vars.tooltip.value[vars.id.nesting[depth]]) { + var a = vars.tooltip.value[vars.id.nesting[depth]] + } + else { + var a = vars.tooltip.value + } + + if (!(a instanceof Array)) { + + if (a[length]) { + a = a[length] + } + else if (a[other_length]) { + a = [] + } + else { + a = mergeObject({"":[]},a) + } + + } + + if (typeof a == "string") { + a = [a] + } + else if (!(a instanceof Array)) { + a = mergeObject({"":[]},a) + } + + } + + function format_key(key,group) { + + if (vars.attrs.value[group]) var id_var = group + else var id_var = null + + if (group) group = vars.format.value(group) + + var value = extra_data[key] || fetchValue(vars,id,key,id_var) + + if (validObject(value)) { + tooltip_data.push({ + "name": vars.format.value(key), + "value": vars.format.value(value.value, {"key": value.key, "vars": vars}), + "group": group + }) + } + else if (value != null && value != "undefined" && !(value instanceof Array) && ((typeof value === "string" && value.indexOf("d3plus_other") < 0) || !(typeof value === "string"))) { + var name = vars.format.locale.value.ui[key] + ? vars.format.value(vars.format.locale.value.ui[key]) + : vars.format.value(key), + h = tooltip_highlights.indexOf(key) >= 0 + + if ( value instanceof Array ) { + value.forEach(function(v){ + v = vars.format.value(v, {"key": key, "vars": vars, "data": id}) + }) + } + else { + value = vars.format.value(value, {"key": key, "vars": vars, "data": id}) + } + + var obj = {"name": name, "value": value, "highlight": h, "group": group} + + if ( vars.descs.value ) { + + if ( typeof vars.descs.value === "function" ) { + var descReturn = vars.descs.value( key ) + if ( typeof descReturn === "string" ) { + obj.desc = descReturn + } + } + else if ( key in vars.descs.value ) { + obj.desc = vars.descs.value[key] + } + + } + + tooltip_data.push(obj) + + } + + } + + var tooltip_data = [] + if (a.constructor === Array) a = {"": a}; + + if (vars.id.nesting.length && depth < vars.id.nesting.length-1) { + var a = copy(a) + vars.id.nesting.forEach(function(n,i){ + if (i > depth && a[n]) delete a[n] + }) + } + + for (var group in a) { + if (a[group].constructor !== Array) a[group] = [a[group]] + for (var i = extras.length; i > 0; i--) { + if (a[group].indexOf(extras[i-1]) >= 0) { + extras.splice(i-1, 1); + } + } + } + + if (vars.tooltip.value.long && typeof vars.tooltip.value.long == "object") { + var placed = [] + + for (var group in vars.tooltip.value.long) { + + for (var i = extras.length; i > 0; i--) { + var e = extras[i-1]; + if (vars.tooltip.value.long[group].indexOf(e) >= 0) { + if (!a[group]) a[group] = []; + a[group].push(e); + extras.splice(i-1, 1); + } + } + + } + + } + + if (extras.length) { + if (!a[""]) a[""] = [] + a[""] = a[""].concat(extras); + } + + for (var group in a) { + a[group].forEach(function(t){ + format_key(t, group); + }); + } + + if ( children ) { + + var title = vars.format.locale.value.ui.including + , colors = children.d3plus_colors + + children.values.forEach(function(child) { + var name = d3.keys(child)[0]; + tooltip_data.push({ + "group": vars.format.value(title), + "highlight": colors && colors[name] ? colors[name] : false, + "name": name, + "value": child[name] + }) + }); + + if (children.d3plusMore) { + + tooltip_data.push({ + "group": vars.format.value(title), + "highlight": true, + "name": stringFormat(vars.format.locale.value.ui.more, children.d3plusMore), + "value": "" + }) + + } + + } + + if ( vars.tooltip.connections.value && length === "long" ) { + + var connections = vars.edges.connections( id[vars.id.value] , vars.id.value , true ) + + if ( connections.length ) { + connections.forEach(function(conn){ + + var c = vars.data.viz.filter(function(d){ + return d[vars.id.value] === conn[vars.id.value] + }) + + var c = c.length ? c[0] : conn + + var name = fetchText(vars,c)[0], + color = fetchColor(vars,c), + size = vars.tooltip.font.size, + radius = vars.shape.value == "square" ? 0 : size + styles = [ + "background-color: "+color, + "border-color: "+legible(color), + "border-style: solid", + "border-width: "+vars.data.stroke.width+"px", + "display: inline-block", + "height: "+size+"px", + "left: 0px", + "position: absolute", + "width: "+size+"px", + "top: 0px", + prefix()+"border-radius: "+radius+"px", + ] + node = "
" + + var nodeClick = function() { + vars.self.focus([c[vars.id.value]]).draw() + } + + tooltip_data.push({ + "group": vars.format.value(vars.format.locale.value.ui.primary), + "highlight": false, + "link": nodeClick, + "name": "" + }) + + }) + } + + } + + return tooltip_data + +} + +},{"../../../client/prefix.coffee":39,"../../../color/legible.coffee":44,"../../../core/fetch/color.coffee":63,"../../../core/fetch/text.js":66,"../../../core/fetch/value.coffee":67,"../../../object/merge.coffee":171,"../../../object/validate.coffee":172,"../../../string/format.js":173,"../../../util/copy.coffee":207}],242:[function(require,module,exports){ +var print; + +print = require("../../../core/console/print.coffee"); + +module.exports = function(vars) { + var app, d, dataRequired, drawable, i, len, ref, requirements, returned, visualization; + vars.group = vars.g.apps[vars.type.value]; + vars.mouse.viz = false; + vars.edges.path = false; + visualization = vars.types[vars.type.value]; + requirements = visualization.requirements || []; + dataRequired = requirements.indexOf("data") >= 0; + drawable = !dataRequired || (dataRequired && vars.data.viz.length); + if (!vars.error.internal && drawable) { + app = vars.format.locale.value.visualization[vars.type.value]; + if (vars.dev.value) { + print.time("running " + app); + } + ref = vars.data.viz; + for (i = 0, len = ref.length; i < len; i++) { + d = ref[i]; + if (d.d3plus) { + delete d.d3plus.shape; + delete d.d3plus.label; + delete d.d3plus.rotate; + delete d.d3plus.share; + } + } + returned = visualization(vars); + if (vars.dev.value) { + print.timeEnd("running " + app); + } + } else { + returned = null; + } + vars.returned = { + nodes: [], + edges: null + }; + if (returned instanceof Array) { + vars.returned.nodes = returned; + } else if (returned) { + if (returned.nodes) { + vars.returned.nodes = returned.nodes; + } + if (returned.edges) { + vars.returned.edges = returned.edges; + } + } +}; + + +},{"../../../core/console/print.coffee":52}],243:[function(require,module,exports){ +var copy = require("../../../util/copy.coffee"), + form = require("../../../form/form.js"), + print = require("../../../core/console/print.coffee"), + validObject = require("../../../object/validate.coffee"); + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws a UI drawer, if defined. +//------------------------------------------------------------------------------ +module.exports = function( vars ) { + + var enabled = vars.ui.value && vars.ui.value.length, + position = vars.ui.position.value; + + if ( vars.dev.value && enabled ) print.time("drawing custom UI elements"); + + var drawer = vars.container.value.selectAll("div#d3plus_drawer") + .data(["d3plus_drawer"]); + + drawer.enter().append("div") + .attr("id","d3plus_drawer"); + + var positionStyles = {}; + vars.ui.position.accepted.forEach(function(p){ + positionStyles[p] = p == position ? vars.margin.bottom+"px" : "auto"; + }); + + drawer + .style("text-align",vars.ui.align.value) + .style("position","absolute") + .style("width",vars.width.value-(vars.ui.padding*2)+"px") + .style("height","auto") + .style(positionStyles); + + var ui = drawer.selectAll("div.d3plus_drawer_ui") + .data(enabled ? vars.ui.value : [], function(d){ + return d.method || false; + }); + + ui.exit().remove(); + + ui.enter().append("div") + .attr("class","d3plus_drawer_ui") + .style("display","inline-block"); + + ui.style("padding",vars.ui.padding+"px") + .each(function(d){ + + if (!d.form) { + + d.form = form() + .container(d3.select(this)) + .data({"sort": false}) + .id("id") + .text("text"); + + } + + var focus, callback; + + if (typeof d.method === "string" && d.method in vars) { + focus = vars[d.method].value; + callback = function(value) { + if ( value !== vars[d.method].value ) { + vars.self[d.method](value).draw(); + } + }; + } + else { + focus = d.focus || d.value[0]; + if (validObject(focus)) focus = focus[d3.keys(focus)[0]]; + if (typeof d.method === "function") { + callback = function(value) { + if (value !== focus) { + focus = value; + d.focus = value; + d.method(value, vars.self); + } + }; + } + } + + var data = [], title; + + if (d.label) { + title = d.label; + } + else if (typeof d.method === "string" && d.method in vars) { + title = vars.format.locale.value.method[d.method] || d.method; + } + + d.value.forEach(function(o){ + + var obj = {}; + + if (validObject(o)) { + obj.id = o[d3.keys(o)[0]]; + obj.text = vars.format.value(d3.keys(o)[0]); + } + else { + obj.id = o; + obj.text = vars.format.value(o); + } + + data.push(obj); + + }); + + var font = copy(vars.ui.font); + font.align = copy(vars.font.align); + font.secondary = copy(font); + + d.form + .data(data) + .font(font) + .focus(d.value.length > 1 ? focus : false) + .focus({"callback": callback}) + .format(vars.format.locale.language) + .format({ + "number": vars.format.number.value, + "text": vars.format.text.value + }) + .title(vars.format.value(title)) + .type(d.type || "auto") + .ui({ + "align": vars.ui.align.value, + "border": vars.ui.border, + "color": { + "primary": vars.ui.color.primary.value, + "secondary": vars.ui.color.secondary.value + }, + "padding": vars.ui.padding, + "margin": 0 + }) + .width(d.width || false) + .draw(); + + }); + + var drawerHeight = drawer.node().offsetHeight || drawer.node().getBoundingClientRect().height; + + if ( drawerHeight ) { + vars.margin[position] += drawerHeight; + } + + if ( vars.dev.value && enabled ) print.timeEnd("drawing custom UI elements"); + +}; + +},{"../../../core/console/print.coffee":52,"../../../form/form.js":104,"../../../object/validate.coffee":172,"../../../util/copy.coffee":207}],244:[function(require,module,exports){ +var events, lighter, print, stylesheet; + +events = require("../../../client/pointer.coffee"); + +lighter = require("../../../color/lighter.coffee"); + +print = require("../../../core/console/print.coffee"); + +stylesheet = require("../../../client/css.coffee"); + +module.exports = function(vars) { + var button, color, containerPadding, enter, family, left, min_height, padding, size, stripY, style, titleClass, titleGroup, top, weight; + if (!vars.small && vars.history.states.length > 0) { + if (vars.dev.value) { + print.time("drawing back button"); + } + button = vars.container.value.selectAll("div#d3plus_back_button").data(["d3plus_back_button"]).style("position", "relative").style("z-index", 1900); + size = vars.title.sub.font.size; + color = vars.title.sub.font.color; + family = vars.title.sub.font.family.value; + weight = vars.title.sub.font.weight; + padding = vars.title.sub.padding; + titleClass = false; + if (vars.title.sub.value && ["start", "left"].indexOf(vars.title.sub.font.align) < 0) { + titleClass = "sub"; + } else if (vars.title.total.value && ["start", "left"].indexOf(vars.title.total.font.align) < 0) { + titleClass = "total"; + } else if (vars.title.value && ["start", "left"].indexOf(vars.title.font.align) < 0) { + titleClass = "title"; + } + if (titleClass) { + stripY = function(elem) { + var y; + y = elem.attr("transform").match(/translate\(([^a-z]+)\)/gi)[0]; + y = y.replace(/([^a-z])\s([^a-z])/gi, "$1,$2"); + y = y.split(","); + y = y[y.length - 1]; + return parseFloat(y.substring(0, y.length - 1)); + }; + titleGroup = vars.svg.select(".d3plus_title." + titleClass); + top = stripY(titleGroup) + stripY(titleGroup.select("text")); + } else { + top = vars.margin.top - vars.title.padding; + min_height = size + padding * 2; + vars.margin.top += min_height; + } + containerPadding = parseFloat(vars.container.value.style("padding-top"), 10); + top += containerPadding; + containerPadding = parseFloat(vars.container.value.style("padding-left"), 10); + left = vars.margin.left + size / 2 + containerPadding; + style = function(elem) { + return elem.style("position", "absolute").style("left", left + "px").style("top", top + "px").style("color", color).style("font-family", family).style("font-weight", weight).style("font-size", size + "px"); + }; + enter = button.enter().append("div").attr("id", "d3plus_back_button").style("opacity", 0).call(style).html(function() { + var arrow; + if (stylesheet("font-awesome") && vars.icon.back.value.indexOf("fa-") === 0) { + arrow = ""; + } else { + arrow = vars.icon.back.value + " "; + } + return arrow + vars.format.value(vars.format.locale.value.ui.back); + }); + button.on(events.over, function() { + if (!vars.small && vars.history.states.length > 0) { + return d3.select(this).style("cursor", "pointer").transition().duration(vars.timing.mouseevents).style("color", lighter(color, .25)); + } + }).on(events.out, function() { + if (!vars.small && vars.history.states.length > 0) { + return d3.select(this).style("cursor", "auto").transition().duration(vars.timing.mouseevents).style("color", color); + } + }).on(events.click, function() { + return vars.history.back(); + }).transition().duration(vars.draw.timing).style("opacity", 1).call(style); + if (vars.dev.value) { + return print.timeEnd("drawing back button"); + } + } else { + return vars.container.value.selectAll("div#d3plus_back_button").transition().duration(vars.draw.timing).style("opacity", 0).remove(); + } +}; + + +},{"../../../client/css.coffee":36,"../../../client/pointer.coffee":38,"../../../color/lighter.coffee":45,"../../../core/console/print.coffee":52}],245:[function(require,module,exports){ +var arraySort = require("../../../array/sort.coffee"), + buckets = require("../../../util/buckets.coffee"), + copy = require("../../../util/copy.coffee"), + createTooltip = require("../tooltip/create.js"), + dataNest = require("../../../core/data/nest.js"), + dataURL = require("../../../util/dataURL.coffee"), + events = require("../../../client/pointer.coffee"), + fetchValue = require("../../../core/fetch/value.coffee"), + fetchColor = require("../../../core/fetch/color.coffee"), + fetchText = require("../../../core/fetch/text.js"), + print = require("../../../core/console/print.coffee"), + removeTooltip = require("../../../tooltip/remove.coffee"), + textColor = require("../../../color/text.coffee"), + uniqueValues = require("../../../util/uniques.coffee"), + scroll = require("../../../client/scroll.js"), + stringStrip = require("../../../string/strip.js"), + textWrap = require("../../../textwrap/textwrap.coffee"), + touch = require("../../../client/touch.coffee"), + validObject = require("../../../object/validate.coffee"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates color key +//------------------------------------------------------------------------------ +module.exports = function(vars) { + + var key_display = true, + square_size = 0; + + if (!vars.error.internal && vars.color.value && !vars.small && vars.legend.value) { + + if (!vars.color.valueScale) { + + if ( vars.dev.value ) print.time("grouping data by colors"); + + var data; + if ( vars.nodes.value && vars.types[vars.type.value].requirements.indexOf("nodes") >= 0 ) { + data = copy(vars.nodes.restriced || vars.nodes.value); + if ( vars.data.viz.length ) { + for (var i = 0 ; i < data.length ; i++) { + var appData = vars.data.viz.filter(function(a){ + return a[vars.id.value] === data[i][vars.id.value]; + }); + if (appData.length) { + data[i] = appData[0]; + } + } + } + } + else { + data = vars.data.viz; + } + + if (data.length && "key" in data[0] && "values" in data[0]) { + data = d3.merge(data.map(function(d){ + return d.values; + })); + } + + var colorFunction = function(d){ + return fetchColor(vars, d, colorDepth); + }, + colorDepth = 0, + colorKey = vars.id.value; + + var colorIndex = vars.id.nesting.indexOf(vars.color.value); + if (colorIndex >= 0) { + colorDepth = colorIndex; + colorKey = vars.id.nesting[colorIndex]; + } + else { + + for (var n = 0; n <= vars.depth.value; n++) { + + colorDepth = n; + colorKey = vars.id.nesting[n]; + + var uniqueIDs = uniqueValues(data , function(d){ + return fetchValue(vars, d, colorKey); + }), + uniqueColors = uniqueValues(data, colorFunction); + + if (uniqueIDs.length >= uniqueColors.length && uniqueColors.length > 1) { + break; + } + + } + + } + + var legendNesting = [vars.color.value]; + // if (vars.icon.value && vars.legend.icons.value) legendNesting.push(vars.icon.value); + var colors = dataNest(vars, data, legendNesting, false); + + if ( vars.dev.value ) print.timeEnd("grouping data by color") + + var available_width = vars.width.value; + + square_size = vars.legend.size; + + var key_width = square_size*colors.length+vars.ui.padding*(colors.length+1) + + if (square_size instanceof Array) { + + if ( vars.dev.value ) print.time("calculating legend size") + + for (var i = square_size[1]; i >= square_size[0]; i--) { + key_width = i*colors.length+vars.ui.padding*(colors.length+1) + if (available_width >= key_width) { + square_size = i; + break; + } + } + + if ( vars.dev.value ) print.timeEnd("calculating legend size"); + + } + else if (typeof square_size != "number" && square_size !== false) { + square_size = 30; + } + + if (available_width < key_width || colors.length == 1) { + key_display = false; + } + else { + + key_width -= vars.ui.padding*2; + + if ( vars.dev.value ) print.time("sorting legend"); + + if(typeof vars.legend.order.value === "function") { + colors = vars.legend.order.value(colors) + } else { + var order = vars[vars.legend.order.value].value; + + var sort_color = vars.color.value; + if (!order) { + order = vars[vars.color.value].value; + } + else if (vars.legend.order.value !== "color") { + sort_color = []; + } + + arraySort(colors, order, vars.legend.order.sort.value, sort_color, vars, colorDepth); + } + + if ( vars.dev.value ) print.timeEnd("sorting legend"); + + if ( vars.dev.value ) print.time("drawing legend"); + + var start_x; + + if (vars.legend.align == "start") { + start_x = vars.ui.padding; + } + else if (vars.legend.align == "end") { + start_x = available_width - vars.ui.padding - key_width; + } + else { + start_x = available_width/2 - key_width/2; + } + + vars.g.legend.selectAll("g.d3plus_scale") + .transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove(); + + function position(group) { + + group + .attr("transform",function(g,i){ + var x = start_x + (i*(vars.ui.padding+square_size)) + return "translate("+x+","+vars.ui.padding+")" + }) + + } + + function style(rect) { + + rect + .attr("width", square_size) + .attr("height", square_size) + .attr("fill",function(g){ + + d3.select(this.parentNode).select("text").remove(); + + var icon = uniqueValues(g, vars.icon.value, fetchValue, vars, colorKey), + color = fetchColor(vars, g, colorKey); + + if (vars.legend.icons.value && icon.length === 1 && + typeof icon[0] === "string") { + icon = icon[0]; + var short_url = stringStrip(icon+"_"+color), + iconStyle = vars.icon.style.value, + icon_style, + pattern = vars.defs.selectAll("pattern#"+short_url) + .data([short_url]); + + if (typeof iconStyle === "string") { + icon_style = vars.icon.style.value; + } + else if (validObject(iconStyle) && iconStyle[colorKey]) { + icon_style = iconStyle[colorKey]; + } + else { + icon_style = "default"; + } + + color = icon_style == "knockout" ? color : "none"; + + pattern.select("rect").transition().duration(vars.draw.timing) + .attr("fill",color) + .attr("width",square_size) + .attr("height",square_size); + + pattern.select("image").transition().duration(vars.draw.timing) + .attr("width",square_size) + .attr("height",square_size); + + var pattern_enter = pattern.enter().append("pattern") + .attr("id",short_url) + .attr("width",square_size) + .attr("height",square_size); + + pattern_enter.append("rect") + .attr("fill",color) + .attr("stroke", "none") + .attr("width",square_size) + .attr("height",square_size); + + pattern_enter.append("image") + .attr("xlink:href",icon) + .attr("width",square_size) + .attr("height",square_size) + .each(function(d){ + + if (icon.indexOf("/") === 0 || icon.indexOf(window.location.hostname) >= 0) { + dataURL(icon,function(base64){ + pattern.select("image").attr("xlink:href",base64); + }); + } + else { + pattern.select("image").attr("xlink:href",icon); + } + + }); + + return "url(#"+short_url+")"; + } + else { + + if (vars.legend.labels.value) { + + var names; + if (vars.legend.text.value) { + names = [fetchValue(vars, g, vars.legend.text.value, colorDepth)]; + } + else { + names = fetchText(vars, g, colorDepth); + } + + if (names.length === 1 && !(names[0] instanceof Array) && names[0].length) { + + var text = d3.select(this.parentNode).append("text"), + size = vars.legend.font.size; + + if (!(size instanceof Array)) { + size = [size] + } + + text + .attr("font-size", size[size.length-1]+"px") + .attr("font-weight", vars.legend.font.weight) + .attr("font-family", vars.legend.font.family.value) + .attr("stroke", "none") + .attr("fill", textColor(color)) + .attr("x", 0) + .attr("y", 0) + .each(function(t){ + + textWrap() + .align("middle") + .container( d3.select(this) ) + .height(square_size) + .padding(vars.ui.padding) + .resize(size.length > 1) + .size(size) + .text( names[0] ) + .width(square_size) + .valign("middle") + .draw(); + + }) + + if (text.select("tspan").empty()) { + text.remove(); + } + + } + + } + + return color; + } + + }); + + } + + var colorInt = {}; + var keys = vars.g.legend.selectAll("g.d3plus_color") + .data(colors,function(d){ + var c = fetchColor(vars, d, colorKey); + if (!(c in colorInt)) colorInt[c] = -1; + colorInt[c]++; + return colorInt[c]+"_"+c; + }); + + keys.enter().append("g") + .attr("class","d3plus_color") + .attr("opacity",0) + .call(position) + .append("rect") + .attr("class","d3plus_color") + .attr("stroke", "none") + .call(style); + + keys.order() + .transition().duration(vars.draw.timing) + .call(position) + .attr("opacity", 1) + .selectAll("rect.d3plus_color") + .call(style); + + keys.exit() + .transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove(); + + if (vars.legend.tooltip.value) { + + keys + .on(events.over,function(d,i){ + + d3.select(this).style("cursor","pointer"); + + var bounds = this.getBoundingClientRect(), + x = bounds.left + square_size/2 + scroll.x(), + y = bounds.top + square_size/2 + scroll.y() + 5; + + var id = fetchValue(vars, d, colorKey), + idIndex = vars.id.nesting.indexOf(colorKey); + + var title; + if (vars.legend.title.value) { + title = fetchValue(vars, d, vars.legend.title.value, colorDepth); + } + else { + title = idIndex >= 0 ? fetchText(vars,d,idIndex)[0] : + vars.format.value(fetchValue(vars,d,vars.color.value,colorKey), {"key": vars.color.value, "vars": vars, "data": d}); + } + + var html, js; + if (vars.legend.filters.value && !(id instanceof Array)) { + html = "
"; + var loc = vars.format.locale.value; + html += "
"+vars.format.value(loc.method.mute)+"
"; + html += "
"+vars.format.value(loc.method.solo)+"
"; + html += "
" + js = function(tooltip) { + var style = { + "border": "1px solid #ccc", + "display": "inline-block", + "margin": "1px 2px", + "padding": "3px 5px" + } + tooltip.select(".mute") + .style(style) + .on(events.over, function(){ + d3.select(this).style("cursor", "pointer"); + }) + .on(events.click, function(){ + var mute = vars.id.mute.value; + vars.history.states.push(function(){ + vars.self.id({"mute": mute}).draw(); + }) + vars.self.id({"mute": id}).draw(); + }); + tooltip.select(".solo") + .style(style) + .on(events.over, function(){ + d3.select(this).style("cursor", "pointer"); + }) + .on(events.click, function(){ + var solo = vars.id.solo.value; + vars.history.states.push(function(){ + vars.self.id({"solo": solo}).draw(); + }) + vars.self.id({"solo": id}).draw(); + }); + } + } + + createTooltip({ + "data": d, + "html": html, + "js": js, + "depth": colorDepth, + "footer": false, + "vars": vars, + "x": x, + "y": y, + "mouseevents": this, + "title": title, + "titleOnly": !vars.legend.data.value, + "offset": square_size*0.4 + }); + + }) + .on(events.out,function(d){ + removeTooltip(vars.type.value); + }); + + } + + if ( vars.dev.value ) print.timeEnd("drawing legend"); + + } + + } + else if (vars.color.valueScale) { + + if ( vars.dev.value ) print.time("drawing color scale"); + + vars.g.legend.selectAll("g.d3plus_color") + .transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove(); + + var values = vars.color.valueScale.domain(), + colors = vars.color.valueScale.range(); + + if (values.length <= 2) { + values = buckets(values,6); + } + + var scale = vars.g.legend.selectAll("g.d3plus_scale") + .data(["scale"]); + + scale.enter().append("g") + .attr("class","d3plus_scale") + .attr("opacity",0); + + var heatmapId = vars.container.id + "_legend_heatmap"; + + var heatmap = scale.selectAll("#" + heatmapId) + .data(["heatmap"]); + + heatmap.enter().append("linearGradient") + .attr("id", heatmapId) + .attr("x1", "0%") + .attr("y1", "0%") + .attr("x2", "100%") + .attr("y2", "0%") + .attr("spreadMethod", "pad"); + + var stops = heatmap.selectAll("stop") + .data(d3.range(0,colors.length)); + + stops.enter().append("stop") + .attr("stop-opacity",1); + + stops + .attr("offset",function(i){ + return Math.round((i/(colors.length-1))*100)+"%"; + }) + .attr("stop-color",function(i){ + return colors[i]; + }); + + stops.exit().remove(); + + var gradient = scale.selectAll("rect#gradient") + .data(["gradient"]); + + gradient.enter().append("rect") + .attr("id","gradient") + .attr("x",function(d){ + if (vars.legend.align == "middle") { + return vars.width.value/2; + } + else if (vars.legend.align == "end") { + return vars.width.value; + } + else { + return 0; + } + }) + .attr("y",vars.ui.padding) + .attr("width", 0) + .attr("height", vars.legend.gradient.height) + .attr("stroke",vars.legend.font.color) + .attr("stroke-width",1) + .style("fill", "url(#" + heatmapId + ")"); + + var text = scale.selectAll("text.d3plus_tick") + .data(d3.range(0,values.length)); + + text.enter().append("text") + .attr("class","d3plus_tick") + .attr("stroke", "none") + .attr("x",function(d){ + if (vars.legend.align == "middle") { + return vars.width.value/2; + } + else if (vars.legend.align == "end") { + return vars.width.value; + } + else { + return 0; + } + }) + .attr("y",function(d){ + return this.getBBox().height+vars.legend.gradient.height+vars.ui.padding*2; + }); + + var label_width = 0; + + text + .order() + .attr("font-weight",vars.legend.font.weight) + .attr("font-family",vars.legend.font.family.value) + .attr("font-size",vars.legend.font.size+"px") + .style("text-anchor",vars.legend.font.align) + .attr("fill",vars.legend.font.color) + .text(function(d){ + return vars.format.value(values[d], {"key": vars.color.value, "vars": vars}); + }) + .attr("y",function(d){ + return this.getBBox().height+vars.legend.gradient.height+vars.ui.padding*2; + }) + .each(function(d){ + var w = Math.ceil(this.getBBox().width); + if (w > label_width) label_width = w; + }); + + label_width += vars.labels.padding*2; + + var key_width = label_width * (values.length-1); + + if (key_width+label_width < vars.width.value) { + + if (key_width+label_width < vars.width.value/2) { + key_width = vars.width.value/2; + label_width = key_width/values.length; + key_width -= label_width; + } + + var start_x; + if (vars.legend.align == "start") { + start_x = vars.ui.padding; + } + else if (vars.legend.align == "end") { + start_x = vars.width.value - vars.ui.padding - key_width; + } + else { + start_x = vars.width.value/2 - key_width/2; + } + + text.transition().duration(vars.draw.timing) + .attr("x",function(d){ + return start_x + (label_width*d); + }); + + text.exit().transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove(); + + var ticks = scale.selectAll("rect.d3plus_tick") + .data(d3.range(0,values.length)); + + ticks.enter().append("rect") + .attr("class","d3plus_tick") + .attr("x",function(d){ + if (vars.legend.align == "middle") { + return vars.width.value/2; + } + else if (vars.legend.align == "end") { + return vars.width.value; + } + else { + return 0; + } + }) + .attr("y",vars.ui.padding) + .attr("width",0) + .attr("height",vars.ui.padding+vars.legend.gradient.height) + .attr("fill",vars.legend.font.color); + + ticks.transition().duration(vars.draw.timing) + .attr("x",function(d){ + var mod = d === 0 ? 1 : 0; + return start_x + (label_width*d) - mod; + }) + .attr("y",vars.ui.padding) + .attr("width",1) + .attr("height",vars.ui.padding+vars.legend.gradient.height) + .attr("fill",vars.legend.font.color); + + ticks.exit().transition().duration(vars.draw.timing) + .attr("width",0) + .remove(); + + gradient.transition().duration(vars.draw.timing) + .attr("x",function(d){ + if (vars.legend.align == "middle") { + return vars.width.value/2 - key_width/2; + } + else if (vars.legend.align == "end") { + return vars.width.value - key_width - vars.ui.padding; + } + else { + return vars.ui.padding; + } + }) + .attr("y",vars.ui.padding) + .attr("width", key_width) + .attr("height", vars.legend.gradient.height); + + scale.transition().duration(vars.draw.timing) + .attr("opacity",1); + + if ( vars.dev.value ) print.timeEnd("drawing color scale"); + + } + else { + key_display = false; + } + + } + else { + key_display = false; + } + + } + else { + key_display = false; + } + if (vars.legend.value && key && key_display) { + + if ( vars.dev.value ) print.time("positioning legend"); + + if (square_size) { + var key_height = square_size+vars.ui.padding; + } + else { + var key_box = vars.g.legend.node().getBBox(), + key_height = key_box.height+key_box.y; + } + + if (vars.margin.bottom === 0) { + vars.margin.bottom += vars.ui.padding; + } + vars.margin.bottom += key_height; + + vars.g.legend.transition().duration(vars.draw.timing) + .attr("transform","translate(0,"+(vars.height.value-vars.margin.bottom)+")") + + if ( vars.dev.value ) print.timeEnd("positioning legend") + + } + else { + + if ( vars.dev.value ) print.time("hiding legend") + + vars.g.legend.transition().duration(vars.draw.timing) + .attr("transform","translate(0,"+vars.height.value+")") + + if ( vars.dev.value ) print.timeEnd("hiding legend") + + } + +} + +},{"../../../array/sort.coffee":34,"../../../client/pointer.coffee":38,"../../../client/scroll.js":41,"../../../client/touch.coffee":43,"../../../color/text.coffee":50,"../../../core/console/print.coffee":52,"../../../core/data/nest.js":60,"../../../core/fetch/color.coffee":63,"../../../core/fetch/text.js":66,"../../../core/fetch/value.coffee":67,"../../../object/validate.coffee":172,"../../../string/strip.js":175,"../../../textwrap/textwrap.coffee":200,"../../../tooltip/remove.coffee":203,"../../../util/buckets.coffee":204,"../../../util/copy.coffee":207,"../../../util/dataURL.coffee":209,"../../../util/uniques.coffee":210,"../tooltip/create.js":240}],246:[function(require,module,exports){ +var events = require("../../../client/pointer.coffee"), + textColor = require("../../../color/text.coffee"); + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Creates Centered Server Message +//------------------------------------------------------------------------------ +module.exports = function(vars,message) { + + message = vars.messages.value ? message : null; + + var size = vars.messages.style.value || (message === vars.error.internal ? + "large" : vars.messages.style.backup); + + if (size === "large") { + var font = vars.messages, + position = "center" + } + else { + + if (vars.footer.value) { + var font = vars.footer + } + else if (vars.title.value) { + var font = vars.title + } + else if (vars.title.sub.value) { + var font = vars.title.sub + } + else if (vars.title.total.value) { + var font = vars.title.total + } + else { + var font = vars.title.sub + } + + var position = font.position + + } + + var font = { + "color": font.font.color, + "font-family": font.font.family.value, + "font-weight": font.font.weight, + "font-size": font.font.size+"px", + "padding": font.padding+"px" + } + + var bg = vars.messages.background.value; + if (!bg) { + bg = vars.background.value; + if (bg === "none" || bg === "transparent") { + bg = textColor(font.color); + } + } + + function style(elem) { + + elem + .style(font) + .style("position", "absolute") + .style("background-color", bg) + .style("text-align", "center") + .style("left",function(){ + return position == "center" ? "50%" : "0px" + }) + .style("width",function(){ + return position == "center" ? "auto" : vars.width.value+"px" + }) + .style("margin-left",function(){ + return position == "center" ? -(this.offsetWidth/2)+"px" : "0px"; + }) + .style("top",function(){ + if (position == "center") { + return "50%"; + } + else if (position == "top") { + return "0px" + } + else { + return "auto" + } + }) + .style("bottom",function(){ + if (position == "bottom") { + return "0px" + } + else { + return "auto" + } + }) + .style("margin-top",function(){ + if (size == "large") { + var height = this.offsetHeight || this.getBoundingClientRect().height + return -height/2+"px" + } + return "0px" + }) + + } + + // Enter Message Group + vars.g.message = vars.container.value.selectAll("div#d3plus_message") + .data(["message"]) + + var enter = vars.g.message.enter().append("div") + .attr("id","d3plus_message") + .attr("opacity",0); + + enter.append("div") + .attr("class", "d3plus_message_text") + .style("display", "block"); + + vars.g.message.select(".d3plus_message_text") + .text(message ? message : vars.g.message.text()) + + var online = navigator.onLine, square = 75; + + var branding = vars.g.message.selectAll(".d3plus_message_branding") + .data(vars.messages.branding.value && position === "center" ? [0] : []); + + branding.enter().append("div") + .attr("class", "d3plus_message_branding") + .style("margin-top", "15px") + .style("padding-top", "0px") + .style("display", "block") + .style("font-size", "11px") + .style("background-size", square + "px") + .style("background-position", "center 10px") + .style("background-repeat", "no-repeat") + .style("cursor", "pointer") + .on(events.click, function(){ + window.open("http://www.d3plus.org/", "_blank"); + }); + + var logo = d3.hsl(bg).l < 0.5 ? vars.messages.branding.image.dark : vars.messages.branding.image.light; + + branding + .text(online ? "Powered by:" : "Powered by D3plus") + .style("background-color", online ? bg : "transparent") + .style("background-image", online ? "url('" + logo + "')" : "none") + .style("min-width", online ? square + "px" : "auto") + .style("height", online ? square + "px" : "auto"); + + branding.exit().remove(); + + vars.g.message + .style("display", message ? "inline-block" : "none") + .call(style).style("opacity", message ? 1 : 0) + +} + +},{"../../../client/pointer.coffee":38,"../../../color/text.coffee":50}],247:[function(require,module,exports){ +var closest, css, events, fontSizes, mix, playInterval, prefix, print, textColor, timeDetect; + +closest = require("../../../util/closest.coffee"); + +css = require("../../../client/css.coffee"); + +fontSizes = require("../../../font/sizes.coffee"); + +events = require("../../../client/pointer.coffee"); + +mix = require("../../../color/mix.coffee"); + +prefix = require("../../../client/prefix.coffee"); + +print = require("../../../core/console/print.coffee"); + +textColor = require("../../../color/text.coffee"); + +timeDetect = require("../../../core/data/time.coffee"); + +playInterval = false; + +module.exports = function(vars) { + var availableWidth, background, brush, brushExtent, brush_group, brushed, brushend, d, end, handles, i, init, j, labelWidth, labels, len, max_index, min, min_index, oldWidth, playButton, playIcon, playIconChar, playIconStyle, playStyle, playUpdate, playbackWidth, setYears, start, start_x, step, stopPlayback, tallEnough, text, textFill, textStyle, tickColor, tickStep, ticks, timeFormat, timeReturn, timelineBox, timelineHeight, timelineOffset, timelineWidth, visible, x, yearHeight, yearMS, year_ticks, years; + if (vars.timeline.value && (!vars.error.internal || !vars.data.missing) && !vars.small && vars.data.time && vars.data.time.values.length > 1) { + if (vars.dev.value) { + print.time("drawing timeline"); + } + textStyle = { + "font-weight": vars.ui.font.weight, + "font-family": vars.ui.font.family.value, + "font-size": vars.ui.font.size + "px", + "text-anchor": "middle" + }; + years = vars.data.time.ticks.map(function(d) { + return new Date(d); + }); + timeReturn = timeDetect(vars, { + values: years, + style: textStyle + }); + visible = timeReturn.values.map(Number); + timeFormat = timeReturn.format; + if (vars.time.solo.value.length) { + init = d3.extent(vars.time.solo.value); + for (i = j = 0, len = init.length; j < len; i = ++j) { + d = init[i]; + if (d.constructor !== Date) { + d += ""; + if (d.length === 4 && parseInt(d) + "" === d) { + d += "/01/01"; + } + d = new Date(d); + init[i] = d; + } + } + } else { + init = d3.extent(years); + } + year_ticks = years.slice(); + yearHeight = d3.max(timeReturn.sizes.map(function(t) { + return t.height; + })); + labelWidth = ~~(d3.max(timeReturn.sizes.map(function(t) { + return t.width; + }))) + 1; + labelWidth += vars.ui.padding * 2; + timelineHeight = vars.timeline.height.value || yearHeight + vars.ui.padding * 2; + timelineWidth = labelWidth * years.length; + playbackWidth = timelineHeight; + tallEnough = timelineHeight - vars.ui.padding * 2 >= yearHeight; + availableWidth = vars.width.value - vars.ui.padding * 2; + if (tallEnough && vars.timeline.play.value) { + availableWidth -= playbackWidth + vars.ui.padding; + } + if (!tallEnough || visible.length < years.length || availableWidth < labelWidth * visible.length) { + oldWidth = labelWidth; + labelWidth = (availableWidth - labelWidth) / years.length; + timelineWidth = labelWidth * years.length; + timelineOffset = 1; + tickStep = ~~(oldWidth / (timelineWidth / visible.length)) + 1; + while (tickStep < visible.length - 1) { + if ((visible.length - 1) % tickStep === 0) { + break; + } + tickStep++; + } + visible = visible.filter(function(t, i) { + return i % tickStep === 0; + }); + } else { + timelineOffset = 0; + min = new Date(years[0]); + step = vars.data.time.stepType; + min["set" + step](min["get" + step]() + years.length); + year_ticks.push(min); + } + start = new Date(init[0]); + start = closest(year_ticks, start); + end = new Date(init[1]); + if (!timelineOffset) { + end["set" + vars.data.time.stepType](end["get" + vars.data.time.stepType]() + 1); + } + end = closest(year_ticks, end); + yearMS = year_ticks.map(Number); + min_index = yearMS.indexOf(+start); + max_index = yearMS.indexOf(+end); + brushExtent = [start, end]; + if (vars.timeline.align === "start") { + start_x = vars.ui.padding; + } else if (vars.timeline.align === "end") { + start_x = vars.width.value - vars.ui.padding - timelineWidth; + } else { + start_x = vars.width.value / 2 - timelineWidth / 2; + } + if (tallEnough && vars.timeline.play.value) { + start_x += (playbackWidth + vars.ui.padding) / 2; + } + stopPlayback = function() { + clearInterval(playInterval); + playInterval = false; + return playIcon.call(playIconChar, "icon"); + }; + brushed = function() { + var extent, max_val, min_val; + if (d3.event.sourceEvent !== null) { + if (playInterval) { + stopPlayback(); + } + brushExtent = brush.extent(); + min_val = closest(year_ticks, brushExtent[0]); + max_val = closest(year_ticks, brushExtent[1]); + if (min_val === max_val) { + min_index = yearMS.indexOf(+min_val); + if (min_val < brushExtent[0] || min_index === 0) { + max_val = year_ticks[min_index + 1]; + } else { + min_val = year_ticks[min_index - 1]; + } + } + min_index = yearMS.indexOf(+min_val); + max_index = yearMS.indexOf(+max_val); + if (max_index - min_index >= 1) { + extent = [min_val, max_val]; + } else if (min_index + 1 <= years.length) { + extent = [min_val, year_ticks[min_index + 1]]; + } else { + extent = [min_val]; + i = 1; + while (i <= 1) { + if (min_index + i <= years.length) { + extent.push(year_ticks[min_index + i]); + } else { + extent.unshift(year_ticks[min_index - ((min_index + i) - years.length)]); + } + i++; + } + extent = [extent[0], extent[extent.length - 1]]; + } + brushExtent = extent; + text.attr("fill", textFill); + return d3.select(this).call(brush.extent(extent)); + } + }; + setYears = function() { + var newYears; + if (max_index - min_index === years.length - timelineOffset) { + newYears = []; + } else { + newYears = yearMS.filter(function(t, i) { + return i >= min_index && i < (max_index + timelineOffset); + }); + newYears = newYears.map(function(t) { + return new Date(t); + }); + } + playUpdate(); + return vars.self.time({ + "solo": newYears + }).draw(); + }; + brushend = function() { + var change, old_max, old_min, solo; + if (d3.event.sourceEvent !== null) { + if (vars.time.solo.value.length) { + solo = d3.extent(vars.time.solo.value); + old_min = yearMS.indexOf(+closest(year_ticks, solo[0])); + old_max = yearMS.indexOf(+closest(year_ticks, solo[1])); + change = old_min !== min_index || old_max !== max_index; + } else { + change = max_index - min_index !== years.length - timelineOffset; + } + if (change) { + return setYears(); + } + } + }; + playButton = vars.g.timeline.selectAll("rect.d3plus_timeline_play").data(tallEnough && vars.timeline.play.value ? [0] : []); + playStyle = function(btn) { + return btn.attr("width", playbackWidth + 1).attr("height", timelineHeight + 1).attr("fill", vars.ui.color.primary.value).attr("stroke", vars.ui.color.primary.value).attr("stroke-width", 1).attr("x", start_x - playbackWidth - 1 - vars.ui.padding).attr("y", vars.ui.padding); + }; + playButton.enter().append("rect").attr("class", "d3plus_timeline_play").attr("shape-rendering", "crispEdges").attr("opacity", 0).call(playStyle); + playButton.transition().duration(vars.draw.timing).call(playStyle); + playButton.exit().transition().duration(vars.draw.timing).attr("opacity", 0).remove(); + playIcon = vars.g.timeline.selectAll("text.d3plus_timeline_playIcon").data(tallEnough && vars.timeline.play.value ? [0] : []); + playIconChar = function(text, char) { + var font; + char = vars.timeline.play[char]; + if (css("font-awesome")) { + char = char.awesome; + font = "FontAwesome"; + } else { + char = char.fallback; + font = "inherit"; + } + return text.style("font-family", font).text(char); + }; + playIconStyle = function(text) { + var y; + y = timelineHeight / 2 + vars.ui.padding + 1; + return text.attr("fill", textColor(vars.ui.color.primary.value)).attr("stroke", "none").attr(textStyle).attr("x", start_x - (playbackWidth - 1) / 2 - vars.ui.padding).attr("y", y).attr("dy", "0.5ex").call(playIconChar, playInterval ? "pause" : "icon"); + }; + playIcon.enter().append("text").attr("class", "d3plus_timeline_playIcon").call(playIconStyle).style("pointer-events", "none").attr("opacity", 0); + playIcon.call(playIconStyle).transition().duration(vars.draw.timing).attr("opacity", 1); + playIcon.exit().transition().duration(vars.draw.timing).attr("opacity", 0).remove(); + playUpdate = function() { + if (max_index - min_index === years.length - timelineOffset) { + playButton.on(events.hover, null).on(events.click, null).transition().duration(vars.draw.timing).attr("opacity", 0.3); + return playIcon.transition().duration(vars.draw.timing).attr("opacity", 0.3); + } else { + playButton.on(events.over, function() { + return d3.select(this).style("cursor", "pointer"); + }).on(events.out, function() { + return d3.select(this).style("cursor", "auto"); + }).on(events.click, function() { + if (playInterval) { + return stopPlayback(); + } else { + playIcon.call(playIconChar, "pause"); + if (max_index === years.length) { + max_index = max_index - min_index; + min_index = 0; + } else { + min_index++; + max_index++; + } + setYears(); + return playInterval = setInterval(function() { + if (max_index === years.length - timelineOffset) { + return stopPlayback(); + } else { + min_index++; + max_index++; + return setYears(); + } + }, vars.timeline.play.timing.value); + } + }).transition().duration(vars.draw.timing).attr("opacity", 1); + return playIcon.transition().duration(vars.draw.timing).attr("opacity", 1); + } + }; + playUpdate(); + textFill = function(d) { + var color, less, opacity; + less = timelineOffset ? d <= brushExtent[1] : d < brushExtent[1]; + if (d >= brushExtent[0] && less) { + opacity = 1; + color = textColor(vars.ui.color.secondary.value); + } else { + opacity = 0.5; + color = textColor(vars.ui.color.primary.value); + } + if (timelineOffset && vars.background.value && vars.background.value !== "none") { + color = d3.rgb(textColor(vars.background.value)); + } + color = d3.rgb(color); + return "rgba(" + color.r + "," + color.g + "," + color.b + "," + opacity + ")"; + }; + background = vars.g.timeline.selectAll("rect.d3plus_timeline_background").data(["background"]); + background.enter().append("rect").attr("class", "d3plus_timeline_background").attr("shape-rendering", "crispEdges").attr("width", timelineWidth + 2).attr("height", timelineHeight + 2).attr("fill", vars.ui.color.primary.value).attr("x", start_x - 1).attr("y", vars.ui.padding); + background.transition().duration(vars.draw.timing).attr("width", timelineWidth + 2).attr("height", timelineHeight + 2).attr("fill", vars.ui.color.primary.value).attr("x", start_x - 1).attr("y", vars.ui.padding); + ticks = vars.g.timeline.selectAll("g#ticks").data(["ticks"]); + ticks.enter().append("g").attr("id", "ticks").attr("transform", "translate(" + vars.width.value / 2 + "," + vars.ui.padding + ")"); + brush_group = vars.g.timeline.selectAll("g#brush").data(["brush"]); + brush_group.enter().append("g").attr("id", "brush"); + labels = vars.g.timeline.selectAll("g#labels").data(["labels"]); + labels.enter().append("g").attr("id", "labels"); + text = labels.selectAll("text").data(years, function(d, i) { + return i; + }); + text.enter().append("text").attr("stroke", "none").attr("y", 0).attr("dy", "0.5ex").attr("x", 0); + x = d3.time.scale().domain(d3.extent(year_ticks)).rangeRound([0, timelineWidth]); + text.order().attr(textStyle).text(function(d, i) { + if (visible.indexOf(+d) >= 0) { + return timeFormat(d); + } else { + return ""; + } + }).attr("opacity", function(d, i) { + if (vars.data.time.dataSteps.indexOf(i) >= 0) { + return 1; + } else { + return 0.4; + } + }).attr("fill", textFill).attr("transform", function(d, i) { + var dx, dy; + dx = start_x + x(d); + if (!timelineOffset) { + dx += labelWidth / 2; + } + dy = timelineHeight / 2 + vars.ui.padding + 1; + if (timelineOffset) { + dy += timelineHeight / 2 + yearHeight; + } + return "translate(" + Math.round(dx) + "," + Math.round(dy) + ")"; + }); + text.exit().transition().duration(vars.draw.timing).attr("opacity", 0).remove(); + brush = d3.svg.brush().x(x).extent(brushExtent).on("brush", brushed).on("brushend", brushend); + if (vars.axes.discrete && vars[vars.axes.discrete].value === vars.time.value) { + tickColor = vars[vars.axes.discrete].ticks.color; + } else { + tickColor = vars.x.ticks.color; + } + ticks.attr("transform", "translate(" + start_x + "," + (vars.ui.padding + 1) + ")").transition().duration(vars.draw.timing).call(d3.svg.axis().scale(x).orient("top").ticks(function() { + return year_ticks; + }).tickFormat("").tickSize(-timelineHeight).tickPadding(0)).selectAll("line").attr("stroke-width", 1).attr("shape-rendering", "crispEdges").attr("stroke", function(d) { + if (visible.indexOf(+d) >= 0) { + return tickColor; + } else { + return mix(tickColor, vars.background.value, 0.4, 1); + } + }); + ticks.selectAll("path").attr("fill", "none"); + brush_group.attr("transform", "translate(" + start_x + "," + (vars.ui.padding + 1) + ")").attr("opacity", 1).call(brush); + text.attr("pointer-events", "none"); + brush_group.selectAll("rect.background").attr("fill", "none").style("visibility", "visible").attr("height", timelineHeight).attr("shape-rendering", "crispEdges").on(events.move, function() { + var c; + c = vars.timeline.hover.value; + if (["grab", "grabbing"].indexOf(c) >= 0) { + c = prefix() + c; + } + return d3.select(this).style("cursor", c); + }); + brush_group.selectAll("rect.extent").attr("opacity", 0.75).attr("height", timelineHeight).attr("fill", vars.ui.color.secondary.value).attr("shape-rendering", "crispEdges").on(events.move, function() { + var c; + c = vars.timeline.hover.value; + if (["grab", "grabbing"].indexOf(c) >= 0) { + c = prefix() + c; + } + return d3.select(this).style("cursor", c); + }); + if (vars.timeline.handles.value) { + handles = brush_group.selectAll("g.resize").selectAll("rect.d3plus_handle").data(["d3plus_handle"]); + handles.enter().insert("rect", "rect").attr("class", "d3plus_handle"); + handles.attr("fill", vars.timeline.handles.color).attr("transform", function(d) { + var mod; + if (this.parentNode.className.baseVal === "resize e") { + mod = -vars.timeline.handles.size; + } else { + mod = 0; + } + return "translate(" + mod + ",0)"; + }).attr("width", vars.timeline.handles.size).style("visibility", "visible").attr("shape-rendering", "crispEdges").attr("opacity", vars.timeline.handles.opacity); + brush_group.selectAll("g.resize").selectAll("rect").attr("height", timelineHeight); + } else { + brush_group.selectAll("g.resize").remove(); + } + timelineBox = vars.g.timeline.node().getBBox(); + if (vars.margin.bottom === 0) { + vars.margin.bottom += vars.ui.padding; + } + vars.margin.bottom += timelineBox.height + timelineBox.y; + vars.g.timeline.transition().duration(vars.draw.timing).attr("transform", "translate(0," + Math.round(vars.height.value - vars.margin.bottom - vars.ui.padding / 2) + ")"); + vars.margin.bottom += vars.ui.padding; + if (vars.dev.value) { + return print.time("drawing timeline"); + } + } else { + return vars.g.timeline.transition().duration(vars.draw.timing).attr("transform", "translate(0," + vars.height.value + ")"); + } +}; + + +},{"../../../client/css.coffee":36,"../../../client/pointer.coffee":38,"../../../client/prefix.coffee":39,"../../../color/mix.coffee":46,"../../../color/text.coffee":50,"../../../core/console/print.coffee":52,"../../../core/data/time.coffee":62,"../../../font/sizes.coffee":102,"../../../util/closest.coffee":206}],248:[function(require,module,exports){ +var events = require("../../../client/pointer.coffee"), + fetchValue = require("../../../core/fetch/value.coffee"), + print = require("../../../core/console/print.coffee"), + rtl = require("../../../client/rtl.coffee"), + textWrap = require("../../../textwrap/textwrap.coffee") +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Draws appropriate titles +//------------------------------------------------------------------------------ +module.exports = function(vars) { + + var total_key = vars.size.value ? vars.size.value + : vars.color.type === "number" ? vars.color.value : false + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If there is no data or the title bar is not needed, + // set the total value to 'null' + //---------------------------------------------------------------------------- + if (!vars.data.viz || !vars.title.total.value || vars.small) { + var total = false + } + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Otherwise, let's calculate it! + //---------------------------------------------------------------------------- + else if (total_key) { + + if ( vars.dev.value ) { + print.time("calculating total value") + } + + var total_data = vars.data.pool; + if (vars.focus.value.length) { + total_data = vars.data.viz.filter(function(d){ + return d[vars.id.value] == vars.focus.value[0]; + }); + } + + var agg = vars.aggs.value[total_key] || "sum"; + var total; + if (agg.constructor === Function) { + total = agg(total_data); + } + else { + + total_data = total_data.reduce(function(arr, d){ + var vals = fetchValue(vars, d, total_key); + if (vals instanceof Array) arr = arr.concat(vals); + else arr.push(vals); + return arr; + }, []); + + total = d3[agg](total_data); + } + + if (total === 0 || total === null || total === undefined) { + total = false + } + + if (typeof total === "number") { + + var pct = "" + + if (vars.data.mute.length || vars.data.solo.length || vars.focus.value.length) { + + var overall_total = d3.sum(vars.data.value, function(d){ + if (vars.time.solo.value.length > 0) { + var match = vars.time.solo.value.indexOf(fetchValue(vars,d,vars.time.value)) >= 0 + } + else if (vars.time.mute.value.length > 0) { + var match = vars.time.solo.value.indexOf(fetchValue(vars,d,vars.time.value)) < 0 + } + else { + var match = true + } + if (match) { + return fetchValue(vars,d,total_key) + } + }) + + if (overall_total > total) { + + var pct = (total/overall_total)*100, + ot = vars.format.value(overall_total, {"key": vars.size.value, "vars": vars}); + + pct = " ("+vars.format.value(pct,{"key": "share", "vars": vars})+" of "+ot+")"; + + } + } + + total = vars.format.value(total, {"key": vars.size.value, "vars": vars}) + var obj = vars.title.total.value + , prefix = obj.prefix || vars.format.value(vars.format.locale.value.ui.total)+": " + total = prefix + total + obj.suffix ? total = total + obj.suffix : null + total += pct + + } + + if ( vars.dev.value ) { + print.timeEnd("calculating total value") + } + + } + else { + var total = false + } + + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Initialize titles and detect footer + //---------------------------------------------------------------------------- + var title_data = [] + + if (vars.footer.value) { + title_data.push({ + "link": vars.footer.link, + "style": vars.footer, + "type": "footer", + "value": vars.footer.value + }) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // If not in "small" mode, detect titles available + //---------------------------------------------------------------------------- + if (!vars.small) { + + if (vars.title.value) { + var title = vars.title.value; + if (typeof title === "function") title = title(vars.self); + title_data.push({ + "link": vars.title.link, + "style": vars.title, + "type": "title", + "value": title + }) + } + if (vars.title.sub.value) { + var title = vars.title.sub.value; + if (typeof title === "function") title = title(vars.self); + title_data.push({ + "link": vars.title.sub.link, + "style": vars.title.sub, + "type": "sub", + "value": title + }) + } + if (vars.title.total.value && total) { + title_data.push({ + "link": vars.title.total.link, + "style": vars.title.total, + "type": "total", + "value": total + }) + } + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Enter Titles + //---------------------------------------------------------------------------- + function style(title) { + + title + .attr("font-size",function(t){ + return t.style.font.size + }) + .attr("fill",function(t){ + return t.link ? vars.links.font.color : t.style.font.color + }) + .attr("font-family",function(t){ + return t.link ? vars.links.font.family.value : t.style.font.family.value + }) + .attr("font-weight",function(t){ + return t.link ? vars.links.font.weight : t.style.font.weight + }) + .style("text-decoration",function(t){ + return t.link ? vars.links.font.decoration.value : t.style.font.decoration.value + }) + .style("text-transform",function(t){ + return t.link ? vars.links.font.transform.value : t.style.font.transform.value + }) + + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Enter Titles + //---------------------------------------------------------------------------- + if ( vars.dev.value ) print.time("drawing titles") + var titles = vars.svg.selectAll("g.d3plus_title") + .data(title_data,function(t){ + return t.type + }) + + var titleWidth = vars.title.width || vars.width.value-vars.margin.left-vars.margin.right; + + titles.enter().append("g") + .attr("class", function(t){ + return "d3plus_title " + t.type; + }) + .attr("opacity",0) + .append("text") + .attr("stroke", "none") + .call(style) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Wrap text and calculate positions, then transition style and opacity + //---------------------------------------------------------------------------- + function getAlign(d) { + var align = d.style.font.align; + if (align == "center") { + return "middle"; + } + else if ((align == "left" && !rtl) || (align == "right" && rtl)) { + return "start"; + } + else if ((align == "left" && rtl) || (align == "right" && !rtl)) { + return "end"; + } + return align; + } + titles + .each(function(d){ + + var container = d3.select(this).select("text").call(style); + + var align = getAlign(d); + + textWrap() + .align(align) + .container(container) + .height(vars.height.value / 2) + .size(false) + .text(d.value) + .width(titleWidth) + .draw() + + d.y = vars.margin[d.style.position] + vars.margin[d.style.position] += this.getBBox().height + d.style.padding*2 + + }) + .on(events.over,function(t){ + if (t.link) { + d3.select(this) + .transition().duration(vars.timing.mouseevents) + .style("cursor","pointer") + .select("text") + .attr("fill",vars.links.hover.color) + .attr("font-family",vars.links.hover.family.value) + .attr("font-weight",vars.links.hover.weight) + .style("text-decoration",vars.links.hover.decoration.value) + .style("text-transform",vars.links.hover.transform.value) + } + }) + .on(events.out,function(t){ + if (t.link) { + d3.select(this) + .transition().duration(vars.timing.mouseevents) + .style("cursor","auto") + .select("text") + .call(style) + } + }) + .on(events.click,function(t){ + if (t.link) { + var target = t.link.charAt(0) != "/" ? "_blank" : "_self" + window.open(t.link,target) + } + }) + .attr("opacity",1) + .attr("transform",function(t){ + var pos = t.style.position, + y = pos == "top" ? 0+t.y : vars.height.value-t.y + if (pos == "bottom") { + y -= this.getBBox().height+t.style.padding + } + else { + y += t.style.padding + } + var align = getAlign(t); + if (align === "start") { + var x = vars.margin.left + vars.title.padding; + } + else { + var w = d3.select(this).select("text").node().getBBox().width; + if (align === "middle") { + x = vars.width.value/2 - titleWidth/2; + } + else { + x = vars.width.value - titleWidth - vars.margin.right - vars.title.padding; + } + } + return "translate("+x+","+y+")"; + }) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Exit unused titles + //---------------------------------------------------------------------------- + titles.exit().transition().duration(vars.draw.timing) + .attr("opacity",0) + .remove() + + if ( vars.margin.top > 0 ) { + vars.margin.top += vars.title.padding + } + + if ( vars.margin.bottom > 0 ) { + vars.margin.bottom += vars.title.padding + } + + var min = vars.title.height + if (min && vars.margin[vars.title.position] < min) { + vars.margin[vars.title.position] = min + } + + if ( vars.dev.value ) print.timeEnd("drawing titles") + +} + +},{"../../../client/pointer.coffee":38,"../../../client/rtl.coffee":40,"../../../core/console/print.coffee":52,"../../../core/fetch/value.coffee":67,"../../../textwrap/textwrap.coffee":200}],249:[function(require,module,exports){ +var labels, transform; + +labels = require("./labels.coffee"); + +transform = require("./transform.coffee"); + +module.exports = function(vars, b, timing) { + var aspect, extent, fit, max_scale, min, padding, scale, translate, type; + if (!b) { + b = vars.zoom.bounds; + } + if (typeof timing !== "number") { + timing = vars.timing.transitions; + } + vars.zoom.size = { + height: b[1][1] - b[0][1], + width: b[1][0] - b[0][0] + }; + type = vars.types[vars.type.value]; + fit = vars.coords.fit.value; + if (fit === "auto" || type.requirements.indexOf("coords") < 0) { + aspect = d3.max([vars.zoom.size.width / vars.width.viz, vars.zoom.size.height / vars.height.viz]); + } else { + aspect = vars.zoom.size[fit] / vars["app_" + fit]; + } + min = d3.min([vars.width.viz, vars.height.viz]); + padding = type.zoom ? vars.coords.padding * 2 : 0; + scale = ((min - padding) / min) / aspect; + extent = vars.zoom.behavior.scaleExtent(); + if (extent[0] === extent[1] || b === vars.zoom.bounds) { + vars.zoom.behavior.scaleExtent([scale, scale * 16]); + } + max_scale = vars.zoom.behavior.scaleExtent()[1]; + if (scale > max_scale) { + scale = max_scale; + } + vars.zoom.scale = scale; + translate = [vars.width.viz / 2 - (vars.zoom.size.width * scale) / 2 - (b[0][0] * scale), vars.height.viz / 2 - (vars.zoom.size.height * scale) / 2 - (b[0][1] * scale)]; + vars.zoom.translate = translate; + vars.zoom.behavior.translate(translate).scale(scale); + vars.zoom.size = { + height: vars.zoom.bounds[1][1] - vars.zoom.bounds[0][1], + width: vars.zoom.bounds[1][0] - vars.zoom.bounds[0][0] + }; + vars.zoom.reset = false; + if (vars.labels.value || vars.labels.changed) { + labels(vars); + } + return transform(vars, timing); +}; + + +},{"./labels.coffee":251,"./transform.coffee":254}],250:[function(require,module,exports){ +module.exports = function(data, vars) { + var depth, max_depth, nextDepth; + max_depth = vars.id.nesting.length - 1; + depth = vars.depth.value; + nextDepth = vars.id.nesting[depth + 1]; + if (vars.types[vars.type.value].nesting === false) { + return 0; + } else if ((data.d3plus.merged || (nextDepth in data && depth < max_depth)) && (!data || nextDepth in data)) { + return 1; + } else if (((depth === max_depth && depth > 0) || (data && nextDepth && (!(nextDepth in data)))) && (vars.small || !vars.tooltip.html.value)) { + return -1; + } else { + return 0; + } +}; + + +},{}],251:[function(require,module,exports){ +var print; + +print = require("../../../core/console/print.coffee"); + +module.exports = function(vars) { + var opacity, scale; + if (vars.dev.value) { + print.time("determining label visibility"); + } + scale = vars.zoom.behavior.scaleExtent(); + opacity = function(text) { + return text.attr("opacity", function(d) { + var size; + if (!d) { + d = {}; + } + size = parseFloat(d3.select(this).attr("font-size"), 10); + d.visible = size * (vars.zoom.scale / scale[1]) >= 2; + if (d.visible) { + return 1; + } else { + return 0; + } + }); + }; + if (vars.draw.timing) { + vars.g.viz.selectAll("text.d3plus_label").transition().duration(vars.draw.timing).call(opacity); + } else { + vars.g.viz.selectAll("text.d3plus_label").call(opacity); + } + if (vars.dev.value) { + return print.timeEnd("determining label visibility"); + } +}; + + +},{"../../../core/console/print.coffee":52}],252:[function(require,module,exports){ +var labels, removeTooltip, transform; + +labels = require("./labels.coffee"); + +removeTooltip = require("../../../tooltip/remove.coffee"); + +transform = require("./transform.coffee"); + +module.exports = function(vars) { + var delay, eventType, limits, scale, translate, xmax, xmin, xoffset, ymax, ymin, yoffset; + eventType = d3.event.sourceEvent ? d3.event.sourceEvent.type : null; + translate = d3.event.translate; + scale = d3.event.scale; + limits = vars.zoom.bounds; + xoffset = (vars.width.viz - (vars.zoom.size.width * scale)) / 2; + xmin = (xoffset > 0 ? xoffset : 0); + xmax = (xoffset > 0 ? vars.width.viz - xoffset : vars.width.viz); + yoffset = (vars.height.viz - (vars.zoom.size.height * scale)) / 2; + ymin = (yoffset > 0 ? yoffset : 0); + ymax = (yoffset > 0 ? vars.height.viz - yoffset : vars.height.viz); + if (translate[0] + limits[0][0] * scale > xmin) { + translate[0] = -limits[0][0] * scale + xmin; + } else if (translate[0] + limits[1][0] * scale < xmax) { + translate[0] = xmax - (limits[1][0] * scale); + } + if (translate[1] + limits[0][1] * scale > ymin) { + translate[1] = -limits[0][1] * scale + ymin; + } else if (translate[1] + limits[1][1] * scale < ymax) { + translate[1] = ymax - (limits[1][1] * scale); + } + vars.zoom.behavior.translate(translate).scale(scale); + vars.zoom.translate = translate; + vars.zoom.scale = scale; + if (eventType === "wheel") { + removeTooltip(vars.type.value); + } + if (vars.labels.value || vars.labels.changed) { + if (eventType === "wheel") { + delay = (vars.draw.timing ? 100 : 250); + clearTimeout(vars.zoom.wheel); + vars.zoom.wheel = setTimeout(function() { + return labels(vars); + }, delay); + } else { + labels(vars); + } + } + if (eventType === "dblclick") { + return transform(vars, vars.timing.transitions); + } else { + return transform(vars, 0); + } +}; + + +},{"../../../tooltip/remove.coffee":203,"./labels.coffee":251,"./transform.coffee":254}],253:[function(require,module,exports){ +module.exports = function(vars, event) { + var enabled, zoom, zoomable, zoomed; + zoom = vars.zoom; + if (!event) { + event = d3.event; + } + zoomed = zoom.scale > zoom.behavior.scaleExtent()[0]; + enabled = vars.types[vars.type.value].zoom && zoom.value && zoom.scroll.value; + zoomable = event.touches && event.touches.length > 1 && enabled; + if (!zoomable && !zoomed) { + event.stopPropagation(); + } +}; + + +},{}],254:[function(require,module,exports){ +module.exports = function(vars, timing) { + var translate; + if (typeof timing !== "number") { + timing = vars.timing.transitions; + } + translate = "translate(" + vars.zoom.translate + ")"; + translate += "scale(" + vars.zoom.scale + ")"; + if (timing) { + return vars.g.viz.transition().duration(timing).attr("transform", translate); + } else { + return vars.g.viz.attr("transform", translate); + } +}; + + +},{}],255:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [false, Function, Object, String], + deprecates: "active_var", + mute: filter(true), + solo: filter(true), + spotlight: { + accepted: [Boolean], + deprecates: "spotlight", + value: false + }, + value: false +}; + + +},{"../../core/methods/filter.coffee":81}],256:[function(require,module,exports){ +module.exports = { + accepted: [Object], + deprecated: "nesting_aggs", + objectAccess: false, + value: {} +}; + + +},{}],257:[function(require,module,exports){ +var process; + +process = require("../../core/methods/process/data.coffee"); + +module.exports = { + accepted: [false, Array, Object, String], + delimiter: { + accepted: String, + value: "|" + }, + filetype: { + accepted: [false, "json", "xml", "html", "csv", "dsv", "tsv", "txt"], + value: false + }, + keys: {}, + process: process, + value: false +}; + + +},{"../../core/methods/process/data.coffee":87}],258:[function(require,module,exports){ +var process, rendering; + +process = require("../../core/methods/process/margin.coffee"); + +rendering = require("../../core/methods/rendering.coffee"); + +module.exports = { + background: { + color: "#fafafa", + rendering: rendering(), + stroke: { + color: "#ccc", + width: 1 + } + }, + margin: { + accepted: [Number, Object, String], + process: function(value) { + var userValue; + if (value === void 0) { + value = this.value; + } + userValue = value; + process(value, this); + return userValue; + }, + value: 10 + }, + mirror: { + accepted: [Boolean], + deprecates: ["mirror_axis", "mirror_axes"], + value: false + }, + ticks: { + accepted: [Boolean], + value: true + } +}; + + +},{"../../core/methods/process/margin.coffee":90,"../../core/methods/rendering.coffee":92}],259:[function(require,module,exports){ +module.exports = { + accepted: [String], + value: "#ffffff" +}; + + +},{}],260:[function(require,module,exports){ +module.exports = { + accepted: [Function, String], + value: false +}; + + +},{}],261:[function(require,module,exports){ +var filter, scale; + +filter = require("../../core/methods/filter.coffee"); + +scale = require("../../color/scale.coffee"); + +module.exports = { + accepted: [false, Array, Function, Object, String], + deprecates: "color_var", + domain: { + accepted: [false, Array], + value: false + }, + focus: "#444444", + heatmap: ["#282F6B", "#419391", "#AFD5E8", "#EACE3F", "#B35C1E", "#B22200"], + missing: "#eeeeee", + mute: filter(true), + primary: "#d74b03", + range: ["#B22200", "#FFEE8D", "#759143"], + scale: { + accepted: [Array, Function, "d3plus", "category10", "category20", "category20b", "category20c"], + process: function(value) { + if (value instanceof Array) { + return d3.scale.ordinal().range(value); + } else if (value === "d3plus") { + return scale; + } else if (typeof value === "string") { + return d3.scale[value](); + } else { + return value; + } + }, + value: "d3plus" + }, + solo: filter(true), + secondary: "#e5b3bb", + value: false +}; + + +},{"../../color/scale.coffee":48,"../../core/methods/filter.coffee":81}],262:[function(require,module,exports){ +module.exports = { + "accepted": [Array, Function, String], + "index": { + "accepted": [Boolean], + "value": true + }, + "process": function(value, vars) { + if (typeof value === "string") value = [value] + return value + }, + "value": false +} + +},{}],263:[function(require,module,exports){ +arguments[4][108][0].apply(exports,arguments) +},{"dup":108}],264:[function(require,module,exports){ +var d3selection; + +d3selection = require("../../util/d3selection.coffee"); + +module.exports = { + accepted: [false, Array, Object, String], + id: "default", + process: function(value, vars) { + if (value === false) { + return false; + } + if (vars.container.id === "default") { + vars.self.container({ + id: "d3plus_" + +new Date() + }); + } + if (d3selection(value)) { + return value.append("div"); + } else if (value instanceof Array) { + return d3.select(value[0][0]).append("div"); + } else { + this.selector = value; + return d3.select(value).append("div"); + } + }, + value: false +}; + + +},{"../../util/d3selection.coffee":208}],265:[function(require,module,exports){ +var filter, process; + +filter = require("../../core/methods/filter.coffee"); + +process = require("../../core/methods/process/data.coffee"); + +module.exports = { + accepted: [false, Array, Function, Object, String], + center: [0, 0], + filetype: { + accepted: ["json"], + value: "json" + }, + fit: { + accepted: ["auto", "height", "width"], + value: "auto" + }, + key: false, + mute: filter(false), + padding: 20, + process: process, + projection: { + accepted: ["albers", "albersUsa", "azimuthalEqualArea", "azimuthalEquidistant", "conicConformal", "conicEqualArea", "conicEquidistant", "equirectangular", "gnomonic", "mercator", "orthographic", "stereographic", "transverseMercator", Function], + value: "mercator" + }, + simplify: { + accepted: [Boolean], + value: true + }, + solo: filter(false), + threshold: { + accepted: [Number], + value: 0.9 + }, + value: false +}; + + +},{"../../core/methods/filter.coffee":81,"../../core/methods/process/data.coffee":87}],266:[function(require,module,exports){ +var fetchValue, ie, stringStrip; + +fetchValue = require("../../core/fetch/value.coffee"); + +ie = require("../../client/ie.js"); + +stringStrip = require("../../string/strip.js"); + +module.exports = { + accepted: [void 0, true, Array, String], + chainable: false, + data: [], + process: function(value, vars) { + var blob, c, col, columns, csv_data, csv_to_return, d, dataString, encodedUri, i, j, k, l, len, len1, len2, len3, len4, len5, len6, len7, link, m, max_filename_len, n, node, o, p, q, ref, ref1, ref2, row, title, titles, val; + if (vars.returned === void 0) { + return []; + } + value = value || vars.cols.value; + if (value instanceof Array) { + columns = value; + } else if (typeof value === "string") { + columns = [value]; + } + csv_to_return = []; + titles = []; + if (vars.title.value) { + title = vars.title.value; + if (typeof title === "function") { + title = title(vars.self); + } + title = stringStrip(title); + max_filename_len = 250; + title = title.substr(0, max_filename_len); + } else { + title = "D3plus Visualization Data"; + } + if (value === true) { + columns = d3.keys(vars.data.keys); + csv_to_return.push(columns); + ref = vars.data.value; + for (j = 0, len = ref.length; j < len; j++) { + d = ref[j]; + row = []; + for (k = 0, len1 = columns.length; k < len1; k++) { + c = columns[k]; + val = d[c]; + if (vars.data.keys[c] === "string") { + val = '"' + val + '"'; + } + row.push(val); + } + csv_to_return.push(row); + } + } else { + if (!columns) { + columns = [vars.id.value]; + if (vars.time.value) { + columns.push(vars.time.value); + } + if (vars.size.value) { + columns.push(vars.size.value); + } + if (vars.text.value) { + columns.push(vars.text.value); + } + } + for (l = 0, len2 = columns.length; l < len2; l++) { + c = columns[l]; + titles.push(vars.format.value(c)); + } + csv_to_return.push(titles); + ref1 = vars.returned.nodes; + for (m = 0, len3 = ref1.length; m < len3; m++) { + node = ref1[m]; + if ((node.values != null) && node.values instanceof Array) { + ref2 = node.values; + for (n = 0, len4 = ref2.length; n < len4; n++) { + val = ref2[n]; + row = []; + for (o = 0, len5 = columns.length; o < len5; o++) { + col = columns[o]; + val = fetchValue(vars, val, col); + if (typeof val === "string") { + val = '"' + val + '"'; + } + row.push(val); + } + csv_to_return.push(row); + } + } else { + row = []; + for (p = 0, len6 = columns.length; p < len6; p++) { + col = columns[p]; + row.push(fetchValue(vars, node, col)); + } + csv_to_return.push(row); + } + } + } + csv_data = "data:text/csv;charset=utf-8,"; + for (i = q = 0, len7 = csv_to_return.length; q < len7; i = ++q) { + c = csv_to_return[i]; + dataString = c.join(","); + csv_data += (i < csv_to_return.length ? dataString + "\n" : dataString); + } + if (ie) { + blob = new Blob([csv_data], { + type: "text/csv;charset=utf-8;" + }); + navigator.msSaveBlob(blob, title + ".csv"); + } else { + encodedUri = encodeURI(csv_data); + link = document.createElement("a"); + link.setAttribute("href", encodedUri); + link.setAttribute("download", title + ".csv"); + link.click(); + } + this.data = csv_to_return; + return columns; + }, + value: void 0 +}; + + +},{"../../client/ie.js":37,"../../core/fetch/value.coffee":67,"../../string/strip.js":175}],267:[function(require,module,exports){ +var process; + +process = require("../../core/methods/process/data.coffee"); + +module.exports = { + accepted: [false, Array, Function, String], + cache: {}, + delimiter: { + accepted: [String], + value: "|" + }, + donut: { + size: 0.35 + }, + filetype: { + accepted: [false, "json", "xml", "html", "csv", "dsv", "tsv", "txt"], + value: false + }, + filters: [], + keys: {}, + mute: [], + large: 400, + opacity: 0.9, + padding: { + accepted: [Number], + value: 1 + }, + process: function(value, vars) { + return process(value, vars, this); + }, + solo: [], + stroke: { + width: 1 + }, + value: false +}; + + +},{"../../core/methods/process/data.coffee":87}],268:[function(require,module,exports){ +module.exports = { + accepted: [Function, Number], + value: 0 +}; + + +},{}],269:[function(require,module,exports){ +module.exports = { + accepted: [false, Function, Object], + value: false +}; + + +},{}],270:[function(require,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"dup":112}],271:[function(require,module,exports){ +var print = require("../../core/console/print.coffee"), + stringFormat = require("../../string/format.js") + +module.exports = { + "accepted" : [ undefined , Function ], + "first" : true, + "frozen" : false, + "process" : function (value, vars) { + + if ( this.initialized === false ) { + this.initialized = true + return value + } + + if ( value === undefined && typeof this.value === "function" ) { + value = this.value + } + + if ( vars.container.value === false ) { + + var str = vars.format.locale.value.dev.setContainer + print.warning( str , "container" ) + + } + else if ( vars.container.value.empty() ) { + + var str = vars.format.locale.value.dev.noContainer + var selector = vars.container.selector || ""; + print.warning( stringFormat(str, "\"" + selector + "\"") , "container" ) + + } + else { + + if ( vars.dev.value ) print.time("total draw time"); + + vars.container.value.call(vars.self); + + } + + if ( typeof value === "function" && vars.history.chain.length ) { + + var changesObject = {} + vars.history.chain.forEach(function(c){ + var method = c.method + delete c.method + changesObject[method] = c + }) + + value(changesObject) + + vars.history.chain = [] + + } + + return value + + }, + "update" : true, + "value" : undefined +} + +},{"../../core/console/print.coffee":52,"../../string/format.js":173}],272:[function(require,module,exports){ +var process = require("../../core/methods/process/data.coffee"); + +module.exports = { + "accepted": [false, Array, Function, String], + "arrows": { + "accepted": [ Boolean , Number ], + "direction": { + "accepted": [ "source" , "target" ], + "value": "target" + }, + "value": false + }, + "color": "#d0d0d0", + "connections": function(focus,id,objects) { + + var self = this + + if (!self.value) { + return [] + } + + if (!id) var id = "id" + + var edges = self.restricted || self.value, + targets = [] + + if (!focus) { + return edges + } + + var connections = edges.filter(function(edge){ + + var match = false + + if (edge[self.source][id] == focus) { + match = true + if (objects) { + targets.push(edge[self.target]) + } + } + else if (edge[self.target][id] == focus) { + match = true + if (objects) { + targets.push(edge[self.source]) + } + } + + return match + + }) + + return objects ? targets : connections + + }, + "delimiter": { + "accepted": [ String ], + "value": "|" + }, + "filetype": { + "accepted": [false, "json", "xml","html", "csv", "dsv", "tsv", "txt"], + "value": false + }, + "interpolate": { + "accepted": ["basis", "cardinal", "linear", "monotone", "step"], + "value": "basis" + }, + "label": false, + "large": 100, + "limit": { + "accepted": [false, Function, Number], + "value": false + }, + "opacity": { + "accepted": [Function, Number, String], + "min": { + "accepted": [Number], + "value": 0.25 + }, + "scale": { + "accepted": [Function], + "value": d3.scale.linear() + }, + "value": 1 + }, + "process": process, + "size": { + "accepted": [false, Number, String], + "min": 1, + "scale": 0.5, + "value": false + }, + "source": "source", + "strength": { + "accepted": [false, Function, Number, String], + "value": false + }, + "target": "target", + "value": false +}; + +},{"../../core/methods/process/data.coffee":87}],273:[function(require,module,exports){ +module.exports = { + accepted: [Boolean, String], + value: false +}; + + +},{}],274:[function(require,module,exports){ +module.exports = { + accepted: [false, Array, Function, Number, String], + deprecates: "highlight", + process: function(value) { + if (value === false) { + return []; + } else if (value instanceof Array) { + return value; + } else { + return [value]; + } + }, + tooltip: { + accepted: [Boolean], + value: true + }, + value: [] +}; + + +},{}],275:[function(require,module,exports){ +var align, decoration, family, transform; + +align = require("../../core/methods/font/align.coffee"); + +decoration = require("../../core/methods/font/decoration.coffee"); + +family = require("../../core/methods/font/family.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +module.exports = { + align: align(), + color: "#444444", + decoration: decoration(), + family: family(), + secondary: { + align: align(), + color: "#444444", + decoration: decoration(), + family: family(), + size: 12, + spacing: 0, + transform: transform(), + weight: 200 + }, + size: 12, + spacing: 0, + transform: transform(), + weight: 200 +}; + + +},{"../../core/methods/font/align.coffee":82,"../../core/methods/font/decoration.coffee":83,"../../core/methods/font/family.coffee":84,"../../core/methods/font/transform.coffee":86}],276:[function(require,module,exports){ +var decoration, family, transform; + +family = require("../../core/methods/font/family.coffee"); + +decoration = require("../../core/methods/font/decoration.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +module.exports = { + accepted: [false, Number, String], + font: { + align: "center", + color: "#444", + decoration: decoration(), + family: family(), + size: 11, + transform: transform(), + weight: 200 + }, + link: false, + padding: 0, + position: "bottom", + value: false +}; + + +},{"../../core/methods/font/decoration.coffee":83,"../../core/methods/font/family.coffee":84,"../../core/methods/font/transform.coffee":86}],277:[function(require,module,exports){ +var formatNumber, locale, mergeObject, titleCase; + +formatNumber = require("../../number/format.coffee"); + +locale = require("../../core/locale/locale.coffee"); + +mergeObject = require("../../object/merge.coffee"); + +titleCase = require("../../string/title.coffee"); + +module.exports = { + accepted: [Function, String], + affixes: { + accepted: [Object], + objectAccess: false, + value: {} + }, + deprecates: ["number_format", "text_format"], + locale: { + accepted: function() { + return d3.keys(locale); + }, + process: function(value) { + var defaultLocale, returnObject; + defaultLocale = "en_US"; + returnObject = locale[defaultLocale]; + if (value !== defaultLocale) { + returnObject = mergeObject(returnObject, locale[value]); + } + this.language = value; + return returnObject; + }, + value: "en_US" + }, + number: { + accepted: [false, Function], + value: false + }, + process: function(value, vars) { + if (typeof value === "string") { + vars.self.format({ + locale: value + }); + } else { + if (typeof value === "function") { + return value; + } + } + return this.value; + }, + text: { + accepted: [false, Function], + value: false + }, + value: function(value, opts) { + var f, v, vars; + if (!opts) { + opts = {}; + } + if (!opts.locale) { + opts.locale = this.locale.value; + } + vars = opts.vars || {}; + if (vars.time && vars.time.value && opts.key === vars.time.value) { + v = value.constructor === Date ? value : new Date(value); + return vars.data.time.format(v); + } else if (typeof value === "number") { + f = this.number.value || formatNumber; + return f(value, opts); + } else if (typeof value === "string") { + f = this.text.value || titleCase; + return f(value, opts); + } else { + return JSON.stringify(value); + } + } +}; + + +},{"../../core/locale/locale.coffee":79,"../../number/format.coffee":170,"../../object/merge.coffee":171,"../../string/title.coffee":176}],278:[function(require,module,exports){ +module.exports = { + accepted: [false, Number], + max: 600, + secondary: false, + small: 200, + value: false +}; + + +},{}],279:[function(require,module,exports){ +var align, decoration, family, filter, orientMap, position, rendering, transform; + +align = require("../../../core/methods/font/align.coffee"); + +decoration = require("../../../core/methods/font/decoration.coffee"); + +family = require("../../../core/methods/font/family.coffee"); + +filter = require("../../../core/methods/filter.coffee"); + +position = require("../../../core/methods/font/position.coffee"); + +rendering = require("../../../core/methods/rendering.coffee"); + +transform = require("../../../core/methods/font/transform.coffee"); + +orientMap = { + x: "bottom", + x2: "top", + y: "left", + y2: "right" +}; + +module.exports = function(axis) { + return { + accepted: [Array, Boolean, Function, Object, String], + affixes: { + accepted: [Boolean], + separator: { + accepted: [Boolean, Array], + value: true + }, + value: false + }, + axis: { + accepted: [Boolean], + color: "#444", + font: { + color: false, + decoration: decoration(false), + family: family(""), + size: false, + spacing: 0, + transform: transform(false), + weight: false + }, + rendering: rendering(), + value: true + }, + dataFilter: true, + deprecates: [axis + "axis", axis + "axis_val", axis + "axis_var"], + domain: { + accepted: [false, Array], + value: false + }, + grid: { + accepted: [Boolean], + color: "#ccc", + rendering: rendering(), + value: true + }, + label: { + accepted: [Boolean, String], + fetch: function(vars) { + if (this.value === true) { + return vars.format.value(vars[axis].value, { + key: axis, + vars: vars + }); + } + return this.value; + }, + font: { + color: "#444", + decoration: decoration(), + family: family(), + size: 12, + spacing: 0, + transform: transform(), + weight: 200 + }, + padding: 3, + value: true + }, + lines: { + accept: [false, Array, Number, Object], + dasharray: { + accepted: [Array, String], + process: function(value) { + if (value instanceof Array) { + value = value.filter(function(d) { + return !isNaN(d); + }); + value = value.length ? value.join(", ") : "none"; + } + return value; + }, + value: "10, 10" + }, + color: "#888", + font: { + align: align("right"), + color: "#444", + background: { + accepted: [Boolean], + value: true + }, + decoration: decoration(), + family: family(), + padding: { + accepted: [Number], + value: 10 + }, + position: position("middle"), + size: 12, + transform: transform(), + weight: 200 + }, + process: Array, + rendering: rendering(), + width: 1, + value: [] + }, + mouse: { + accept: [Boolean], + dasharray: { + accepted: [Array, String], + process: function(value) { + if (value instanceof Array) { + value = value.filter(function(d) { + return !isNaN(d); + }); + value = value.length ? value.join(", ") : "none"; + } + return value; + }, + value: "none" + }, + rendering: rendering(), + width: 2, + value: true + }, + mute: filter(true), + orient: { + accepted: ["top", "right", "bottom", "left"], + value: orientMap[axis] + }, + padding: { + accepted: [Number], + value: 0.1 + }, + persist: { + position: { + accepted: [Boolean], + value: false + }, + size: { + accepted: [Boolean], + value: true + } + }, + range: { + accepted: [false, Array], + value: false + }, + scale: { + accepted: ["linear", "log", "discrete", "share"], + deprecates: ["layout", "unique_axis", axis + "axis_scale"], + process: function(value, vars) { + var i, len, ref, scale; + ref = ["log", "discrete", "share"]; + for (i = 0, len = ref.length; i < len; i++) { + scale = ref[i]; + if (scale === value) { + vars.axes[scale] = axis; + } else { + if (vars.axes[scale] === axis) { + vars.axes[scale] = false; + } + } + } + if (value === "discrete") { + vars.axes.opposite = (axis.indexOf("x") === 0 ? "y" : "x"); + } + return value; + }, + value: "linear" + }, + solo: filter(true), + stacked: { + accepted: [Boolean], + process: function(value, vars) { + if (!value && vars.axes.stacked === axis) { + vars.axes.stacked = false; + } else { + if (value) { + vars.axes.stacked = axis; + } + } + return value; + }, + value: false + }, + ticks: { + accepted: [false, Array], + color: "#ccc", + font: { + color: "#666", + decoration: decoration(), + family: family(), + size: 10, + spacing: 0, + transform: transform(), + weight: 200 + }, + labels: { + accepted: [Boolean, Array], + value: true + }, + rendering: rendering(), + size: 10, + width: 1, + value: false + }, + value: false, + zerofill: { + accepted: [Boolean], + value: false + } + }; +}; + + +},{"../../../core/methods/filter.coffee":81,"../../../core/methods/font/align.coffee":82,"../../../core/methods/font/decoration.coffee":83,"../../../core/methods/font/family.coffee":84,"../../../core/methods/font/position.coffee":85,"../../../core/methods/font/transform.coffee":86,"../../../core/methods/rendering.coffee":92}],280:[function(require,module,exports){ +module.exports = { + accepted: [Boolean], + back: function() { + if (this.states.length) { + return this.states.pop()(); + } + }, + chain: [], + reset: function() { + var results; + results = []; + while (this.states.length) { + results.push(this.states.pop()()); + } + return results; + }, + states: [], + value: true +}; + + +},{}],281:[function(require,module,exports){ +var process; + +process = require("../../core/methods/process/icon.coffee"); + +module.exports = { + accepted: [false, Array, Function, Object, String], + back: { + accepted: [false, String], + fallback: "❮", + opacity: 1, + process: process, + rotate: 0, + value: "fa-angle-left" + }, + deprecates: "icon_var", + style: { + accepted: [Object, String], + deprecates: "icon_style", + value: "default" + }, + value: false +}; + + +},{"../../core/methods/process/icon.coffee":89}],282:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [Array, String], + dataFilter: true, + deprecates: ["id_var", "nesting"], + grouping: { + accepted: [Boolean], + value: true + }, + mute: filter(true), + nesting: ["id"], + solo: filter(true), + value: "id" +}; + + +},{"../../core/methods/filter.coffee":81}],283:[function(require,module,exports){ +var decoration, family, transform; + +decoration = require("../../core/methods/font/decoration.coffee"); + +family = require("../../core/methods/font/family.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +module.exports = { + accepted: [Boolean], + align: { + accepted: ["start", "middle", "end", "left", "center", "right"], + process: function(value) { + var css; + css = ["left", "center", "right"].indexOf(value); + if (css >= 0) { + value = this.accepted[css]; + } + return value; + }, + value: "middle" + }, + color: { + accepted: [false, String], + value: false + }, + font: { + decoration: decoration(), + family: family(), + size: 11, + transform: transform(), + weight: 200 + }, + padding: 7, + resize: { + accepted: [Boolean], + value: true + }, + text: { + accepted: [false, Function, String], + value: false + }, + segments: 2, + valign: { + accepted: [false, "top", "middle", "bottom"], + value: "middle" + }, + value: true +}; + + +},{"../../core/methods/font/decoration.coffee":83,"../../core/methods/font/family.coffee":84,"../../core/methods/font/transform.coffee":86}],284:[function(require,module,exports){ +var family; + +family = require("../../core/methods/font/family.coffee"); + +module.exports = { + accepted: [Boolean], + align: "middle", + data: { + accepted: [Boolean], + value: true + }, + filters: { + accepted: [Boolean], + value: false + }, + font: { + align: "middle", + color: "#444444", + family: family(), + size: [8, 14], + weight: 200 + }, + gradient: { + height: 10 + }, + icons: { + accepted: [Boolean], + value: true + }, + labels: { + accepted: [Boolean], + value: true + }, + order: { + accepted: ["color", "id", "size", "text", Function], + sort: { + accepted: ["asc", "desc"], + value: "asc" + }, + value: "color" + }, + size: [8, 30], + tooltip: { + accepted: [Boolean], + value: true + }, + text: { + accepted: [false, Function, String], + value: false + }, + title: { + accepted: [false, Function, String], + value: false + }, + value: true +}; + + +},{"../../core/methods/font/family.coffee":84}],285:[function(require,module,exports){ +var decoration, family, transform; + +decoration = require("../../core/methods/font/decoration.coffee"); + +family = require("../../core/methods/font/family.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +module.exports = { + font: { + color: "#444444", + decoration: decoration(), + family: family(), + transform: transform(), + weight: 200 + }, + hover: { + color: "#444444", + decoration: decoration(), + family: family(), + transform: transform(), + weight: 200 + } +}; + + +},{"../../core/methods/font/decoration.coffee":83,"../../core/methods/font/family.coffee":84,"../../core/methods/font/transform.coffee":86}],286:[function(require,module,exports){ +arguments[4][123][0].apply(exports,arguments) +},{"../../core/methods/process/margin.coffee":90,"dup":123}],287:[function(require,module,exports){ +var decoration, family, transform; + +decoration = require("../../core/methods/font/decoration.coffee"); + +family = require("../../core/methods/font/family.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +module.exports = { + accepted: [Boolean, String], + background: { + accepted: [false, String], + value: false + }, + branding: { + accepted: [Boolean], + image: { + dark: "http://d3plus.org/assets/img/icon-transparent-invert.png", + light: "http://d3plus.org/assets/img/icon-transparent.png" + }, + value: false + }, + font: { + color: "#444", + decoration: decoration(), + family: family(), + size: 16, + transform: transform(), + weight: 200 + }, + padding: 5, + style: { + accepted: [false, "small", "large"], + value: false + }, + value: true +}; + + +},{"../../core/methods/font/decoration.coffee":83,"../../core/methods/font/family.coffee":84,"../../core/methods/font/transform.coffee":86}],288:[function(require,module,exports){ +module.exports = { + accepted: [Boolean], + click: { + accepted: [Boolean, Function], + value: true + }, + move: { + accepted: [Boolean, Function], + value: true + }, + out: { + accepted: [Boolean, Function], + value: true + }, + over: { + accepted: [Boolean, Function], + value: true + }, + value: true +}; + + +},{}],289:[function(require,module,exports){ +var process; + +process = require("../../core/methods/process/data.coffee"); + +module.exports = { + accepted: [false, Array, Function, String], + delimiter: { + accepted: [String], + value: "|" + }, + filetype: { + accepted: [false, "json", "xml", "html", "csv", "dsv", "tsv", "txt"], + value: false + }, + overlap: 0.6, + process: process, + value: false +}; + + +},{"../../core/methods/process/data.coffee":87}],290:[function(require,module,exports){ +module.exports = { + accepted: [Boolean, Function, String], + agg: { + accepted: [false, Function, "sum", "min", "max", "mean", "median"], + value: false + }, + deprecates: ["sort"], + sort: { + accepted: ["asc", "desc"], + value: "desc" + }, + value: false +}; + + +},{}],291:[function(require,module,exports){ +module.exports = { + accepted: [Boolean], + value: false, + timeout: 400, + process: function(value, vars) { + var resize, resizeEnd; + if (!value) { + return false; + } + resize = null; + resizeEnd = function() { + var height, mainNode, width; + mainNode = vars.container.value.node().parentNode.getBoundingClientRect(); + width = mainNode.width; + height = mainNode.height; + vars.self.width(width); + vars.self.height(height); + if (vars.width.changed || vars.height.changed) { + return vars.self.draw(); + } + }; + d3.select(window).on("resize." + vars.container.id, (function(_this) { + return function(e) { + clearTimeout(resize); + return resize = setTimeout(resizeEnd, _this.timeout); + }; + })(this)); + return value; + } +}; + + +},{}],292:[function(require,module,exports){ +var rendering; + +rendering = require("../../core/methods/rendering.coffee"); + +module.exports = { + accepted: function(vars) { + var list; + list = vars.types[vars.type.value].shapes; + if (list && !(list instanceof Array)) { + list = [list]; + } + if (list.length) { + return list; + } else { + return ["square"]; + } + }, + interpolate: { + accepted: ["basis", "basis-open", "cardinal", "cardinal-open", "linear", "monotone", "step", "step-before", "step-after"], + deprecates: "stack_type", + value: "linear" + }, + rendering: rendering(), + value: false +}; + + +},{"../../core/methods/rendering.coffee":92}],293:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [false, Function, Number, Object, String], + dataFilter: true, + deprecates: ["value", "value_var"], + mute: filter(true), + scale: { + accepted: [Function], + deprecates: "size_scale", + domain: { + min: { + accepted: [false, Number], + value: false + }, + max: { + accepted: [false, Number], + value: false + } + }, + range: { + max: { + accepted: [Function, Number], + value: function(vars) { + return Math.floor(d3.max([d3.min([vars.width.viz, vars.height.viz]) / 15, 6])); + } + }, + min: { + accepted: [Function, Number], + value: 3 + } + }, + value: d3.scale.sqrt() + }, + solo: filter(true), + threshold: { + accepted: [Boolean, Function, Number], + value: false + }, + value: false +}; + + +},{"../../core/methods/filter.coffee":81}],294:[function(require,module,exports){ +module.exports = { + value: false +}; + + +},{}],295:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [false, Function, Object, String], + deprecates: ["else_var", "else"], + mute: filter(true), + solo: filter(true), + value: false +}; + + +},{"../../core/methods/filter.coffee":81}],296:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [Array, Boolean, Function, Object, String], + deprecates: ["name_array", "text_var"], + nesting: true, + mute: filter(true), + solo: filter(true), + value: false +}; + + +},{"../../core/methods/filter.coffee":81}],297:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [Array, Boolean, Function, Object, String], + dataFilter: true, + deprecates: ["year", "year_var"], + fixed: { + accepted: [Boolean], + deprecates: ["static_axis", "static_axes"], + value: true + }, + format: { + accepted: [false, Array, Function, String], + value: false + }, + mute: filter(false), + solo: filter(false), + value: false +}; + + +},{"../../core/methods/filter.coffee":81}],298:[function(require,module,exports){ +module.exports = { + accepted: [Boolean], + align: "middle", + hover: { + accepted: ["all-scroll", "col-resize", "crosshair", "default", "grab", "grabbing", "move", "pointer"], + value: "pointer" + }, + handles: { + accepted: [Boolean], + color: "#666", + opacity: 1, + size: 3, + stroke: "#666", + value: true + }, + height: { + accepted: [false, Number], + value: false + }, + play: { + accepted: [Boolean], + icon: { + accepted: [false, String], + awesome: "", + fallback: "►" + }, + pause: { + accepted: [false, String], + awesome: "", + fallback: "❚❚" + }, + timing: { + accepted: [Number], + value: 1500 + }, + value: true + }, + value: true +}; + + +},{}],299:[function(require,module,exports){ +module.exports = { + mouseevents: 60, + transitions: 600, + ui: 200 +}; + + +},{}],300:[function(require,module,exports){ +var decoration, family, stringStrip, transform; + +decoration = require("../../core/methods/font/decoration.coffee"); + +family = require("../../core/methods/font/family.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +stringStrip = require("../../string/strip.js"); + +module.exports = { + accepted: [false, Function, String], + font: { + align: "center", + color: "#444444", + decoration: decoration(), + family: family(), + size: 16, + transform: transform(), + weight: 400 + }, + height: false, + link: false, + padding: 2, + position: "top", + process: function(value, vars) { + var id; + if (vars.container.id.indexOf("default") === 0 && value) { + id = stringStrip(value).toLowerCase(); + vars.self.container({ + id: id + }); + } + return value; + }, + sub: { + accepted: [false, Function, String], + deprecates: "sub_title", + font: { + align: "center", + color: "#444444", + decoration: decoration(), + family: family(), + size: 12, + transform: transform(), + weight: 200 + }, + link: false, + padding: 1, + position: "top", + value: false + }, + total: { + accepted: [Boolean, Object], + deprecates: "total_bar", + font: { + align: "center", + color: "#444444", + decoration: decoration(), + family: family(), + size: 12, + transform: transform(), + weight: 200, + value: false + }, + link: false, + padding: 1, + position: "top", + value: false + }, + width: false, + value: false +}; + + +},{"../../core/methods/font/decoration.coffee":83,"../../core/methods/font/family.coffee":84,"../../core/methods/font/transform.coffee":86,"../../string/strip.js":175}],301:[function(require,module,exports){ +var family, transform; + +family = require("../../core/methods/font/family.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +module.exports = { + accepted: [Boolean, Array, Function, Object, String], + anchor: "top center", + background: "#ffffff", + children: { + accepted: [Boolean, Number], + value: true + }, + connections: { + accepted: [Boolean], + value: true + }, + curtain: { + color: "#ffffff", + opacity: 0.8 + }, + deprecates: "tooltip_info", + extent: { + accepted: [Boolean], + value: true + }, + font: { + color: "#444", + family: family(), + size: 12, + transform: transform(), + weight: 200 + }, + fullscreen: { + accepted: [Boolean], + value: false + }, + html: { + accepted: [false, Function, Object, String], + deprecates: "click_function", + value: false + }, + iqr: { + accepted: [Boolean], + value: true + }, + large: 250, + share: { + accepted: [Boolean], + value: true + }, + size: { + accepted: [Boolean], + value: true + }, + small: 225, + stacked: { + accepted: [Boolean], + value: false + }, + sub: { + accepted: [false, Function, String], + value: false + }, + value: true +}; + + +},{"../../core/methods/font/family.coffee":84,"../../core/methods/font/transform.coffee":86}],302:[function(require,module,exports){ +var filter; + +filter = require("../../core/methods/filter.coffee"); + +module.exports = { + accepted: [false, Function, Object, String], + deprecates: ["total_var"], + mute: filter(true), + solo: filter(true), + value: false +}; + + +},{"../../core/methods/filter.coffee":81}],303:[function(require,module,exports){ +module.exports = { + accepted: function(vars) { + return d3.keys(vars.types); + }, + mode: { + accepted: function(vars) { + return vars.types[vars.type.value].modes || [false]; + }, + value: false + }, + value: "tree_map" +}; + + +},{}],304:[function(require,module,exports){ +var align, decoration, family, transform; + +family = require("../../core/methods/font/family.coffee"); + +align = require("../../core/methods/font/align.coffee"); + +decoration = require("../../core/methods/font/decoration.coffee"); + +transform = require("../../core/methods/font/transform.coffee"); + +module.exports = { + accepted: [Array, Boolean], + align: align("center"), + border: 1, + color: { + primary: { + process: function(value, vars) { + var primary; + primary = this.value; + if (!vars.ui.color.secondary.value) { + vars.ui.color.secondary.value = d3.rgb(primary).darker(0.75).toString(); + } + return value; + }, + value: "#ffffff" + }, + secondary: { + value: false + } + }, + display: { + acceped: ["block", "inline-block"], + value: "inline-block" + }, + font: { + align: "center", + color: "#444", + decoration: decoration(), + family: family(), + size: 11, + transform: transform(), + weight: 200 + }, + margin: 5, + padding: 5, + position: { + accepted: ["top", "right", "bottom", "left"], + value: "bottom" + }, + value: false +}; + + +},{"../../core/methods/font/align.coffee":82,"../../core/methods/font/decoration.coffee":83,"../../core/methods/font/family.coffee":84,"../../core/methods/font/transform.coffee":86}],305:[function(require,module,exports){ +module.exports = { + accepted: [false, Number], + secondary: false, + small: 200, + value: false +}; + + +},{}],306:[function(require,module,exports){ +module.exports = { + "accepted" : [ Boolean ], + "behavior" : d3.behavior.zoom().scaleExtent([ 1 , 1 ]).duration(0), + "click" : { + "accepted" : [ Boolean ], + "value" : true + }, + "pan" : { + "accepted" : [ Boolean ], + "value" : true + }, + "scroll" : { + "accepted" : [ Boolean ], + "deprecates" : "scroll_zoom", + "value" : true + }, + "value" : true +} + +},{}],307:[function(require,module,exports){ +var area, closest, fetchValue, graph, nest, sort, stack, threshold; + +closest = require("../../util/closest.coffee"); + +fetchValue = require("../../core/fetch/value.coffee"); + +graph = require("./helpers/graph/draw.coffee"); + +nest = require("./helpers/graph/nest.coffee"); + +sort = require("../../array/sort.coffee"); + +stack = require("./helpers/graph/stack.coffee"); + +threshold = require("../../core/data/threshold.js"); + +area = function(vars) { + var d, data, discrete, domains, i, j, len, len1, opposite, point, ref; + graph(vars, { + buffer: vars.axes.opposite, + zero: true + }); + domains = vars.x.domain.viz.concat(vars.y.domain.viz); + if (domains.indexOf(void 0) >= 0) { + return []; + } + data = sort(vars.data.viz, null, null, null, vars); + discrete = vars[vars.axes.discrete]; + opposite = vars[vars.axes.opposite]; + for (i = 0, len = data.length; i < len; i++) { + point = data[i]; + if (!point.d3plus) { + point.d3plus = {}; + } + ref = point.values; + for (j = 0, len1 = ref.length; j < len1; j++) { + d = ref[j]; + if (!d.d3plus) { + d.d3plus = {}; + } + d.d3plus.x = discrete.scale.viz(fetchValue(vars, d, discrete.value)); + d.d3plus.x += vars.axes.margin.viz.left; + d.d3plus.y = opposite.scale.viz(fetchValue(vars, d, opposite.value)); + d.d3plus.y += vars.axes.margin.viz.top; + if (d.d3plus.merged instanceof Array) { + if (!point.d3plus.merged) { + point.d3plus.merged = []; + } + point.d3plus.merged = point.d3plus.merged.concat(d.d3plus.merged); + } + if (d.d3plus.text && !point.d3plus.text) { + point.d3plus.text = d.d3plus.text; + } + } + } + return stack(vars, data); +}; + +area.filter = function(vars, data) { + return nest(vars, threshold(vars, data, vars[vars.axes.discrete].value)); +}; + +area.requirements = ["data", "x", "y"]; + +area.setup = function(vars) { + var axis, size, y; + if (!vars.axes.discrete) { + axis = vars.time.value === vars.y.value ? "y" : "x"; + vars.self[axis]({ + scale: "discrete" + }); + } + if (!vars[vars.axes.discrete].zerofill.value) { + vars.self[vars.axes.discrete]({ + zerofill: true + }); + } + if (!vars[vars.axes.opposite].stacked.value && vars.type.value === "stacked") { + vars.self[vars.axes.opposite]({ + stacked: true + }); + } + y = vars[vars.axes.opposite]; + size = vars.size; + if ((!y.value && size.value) || (size.changed && size.previous === y.value)) { + return vars.self[vars.axes.opposite](size.value); + } else if ((!size.value && y.value) || (y.changed && y.previous === size.value)) { + return vars.self.size(y.value); + } +}; + +area.shapes = ["area"]; + +area.threshold = function(vars) { + return 20 / vars.height.viz; +}; + +area.tooltip = "static"; + +module.exports = area; + + +},{"../../array/sort.coffee":34,"../../core/data/threshold.js":61,"../../core/fetch/value.coffee":67,"../../util/closest.coffee":206,"./helpers/graph/draw.coffee":314,"./helpers/graph/nest.coffee":320,"./helpers/graph/stack.coffee":321}],308:[function(require,module,exports){ +var bar, buckets, fetchValue, graph, nest, stack, uniques, + indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; + +buckets = require("../../util/buckets.coffee"); + +fetchValue = require("../../core/fetch/value.coffee"); + +graph = require("./helpers/graph/draw.coffee"); + +nest = require("./helpers/graph/nest.coffee"); + +stack = require("./helpers/graph/stack.coffee"); + +uniques = require("../../util/uniques.coffee"); + +bar = function(vars) { + var bars, base, cMargin, d, data, discrete, discreteVal, divisions, domains, h, i, ids, j, k, l, len, len1, len2, length, maxBars, maxSize, mod, nested, newSize, oMargin, offset, oppDomain, oppMethod, oppVal, opposite, p, padding, point, ref, ref1, space, value, w, x, zero; + discrete = vars.axes.discrete; + h = discrete === "x" ? "height" : "width"; + w = discrete === "x" ? "width" : "height"; + opposite = vars.axes.opposite; + cMargin = discrete === "x" ? "left" : "top"; + oMargin = discrete === "x" ? "top" : "left"; + graph(vars, { + buffer: true, + zero: opposite + }); + domains = vars.x.domain.viz.concat(vars.y.domain.viz); + if (domains.indexOf(void 0) >= 0) { + return []; + } + nested = vars.data.viz; + if (vars.axes.stacked) { + for (j = 0, len = nested.length; j < len; j++) { + point = nested[j]; + stack(vars, point.values); + } + } + space = vars.axes[w] / vars[vars.axes.discrete].ticks.values.length; + padding = vars[vars.axes.discrete].padding.value; + if (padding < 1) { + padding *= space; + } + if (padding * 2 > space) { + padding = space * 0.1; + } + maxSize = space - padding * 2; + if (!vars.axes.stacked) { + if (vars[discrete].persist.position.value) { + if (ref = vars[discrete].value, indexOf.call(vars.id.nesting, ref) >= 0) { + divisions = d3.max(nested, function(b) { + return b.values.length; + }); + } else { + divisions = uniques(nested, vars.id.value, fetchValue, vars).length; + } + maxSize /= divisions; + offset = space / 2 - maxSize / 2 - padding; + x = d3.scale.ordinal(); + if (divisions === 1) { + x.domain([0]).range([0]); + } else { + x.domain([0, divisions - 1]).range([-offset, offset]); + } + } else { + x = d3.scale.linear(); + } + } + data = []; + oppMethod = vars[opposite]; + oppDomain = oppMethod.scale.viz.domain().slice(); + if (opposite.indexOf("y") === 0) { + oppDomain = oppDomain.reverse(); + } + if (oppDomain[0] <= 0 && oppDomain[1] >= 0) { + zero = 0; + } else if (oppDomain[0] < 0) { + zero(d3.max(oppDomain)); + } else { + zero = d3.min(oppDomain); + } + if (vars[discrete].persist.position.value && !vars.axes.stacked) { + ids = uniques(d3.merge(nested.map(function(d) { + return d.values; + })), vars.id.value, fetchValue, vars, vars.id.value, false); + x.domain(ids); + if (ids.length === 1) { + x.range([0]); + } else { + x.range(buckets(x.range(), ids.length)); + } + } + maxBars = d3.max(nested, function(b) { + return b.values.length; + }); + for (k = 0, len1 = nested.length; k < len1; k++) { + p = nested[k]; + if (vars.axes.stacked) { + bars = 1; + newSize = maxSize; + } else if (vars[discrete].persist.position.value) { + bars = divisions; + newSize = maxSize; + } else { + bars = p.values.length; + if (vars[discrete].persist.size.value) { + newSize = maxSize / maxBars; + offset = space / 2 - ((maxBars - bars) * (newSize / 2)) - newSize / 2 - padding; + } else { + newSize = maxSize / bars; + offset = space / 2 - newSize / 2 - padding; + } + x.domain([0, bars - 1]); + x.range([-offset, offset]); + } + ref1 = p.values; + for (i = l = 0, len2 = ref1.length; l < len2; i = ++l) { + d = ref1[i]; + if (vars.axes.stacked) { + mod = 0; + } else if (vars[discrete].persist.position.value) { + mod = x(fetchValue(vars, d, vars.id.value)); + } else { + mod = x(i % bars); + } + if (vars.axes.stacked) { + value = d.d3plus[opposite]; + base = d.d3plus[opposite + "0"]; + } else { + oppVal = fetchValue(vars, d, oppMethod.value); + if (oppVal === null) { + oppMethod = vars[opposite + "2"]; + oppVal = fetchValue(vars, d, oppMethod.value); + } + if (oppVal === 0) { + continue; + } + if (oppMethod.scale.value === "log") { + zero = oppVal < 0 ? -1 : 1; + } + value = oppMethod.scale.viz(oppVal); + base = oppMethod.scale.viz(zero); + } + discreteVal = fetchValue(vars, d, vars[discrete].value); + d.d3plus[discrete] = vars[discrete].scale.viz(discreteVal); + d.d3plus[discrete] += vars.axes.margin.viz[cMargin] + mod; + length = base - value; + d.d3plus[opposite] = base - length / 2; + if (!vars.axes.stacked) { + d.d3plus[opposite] += vars.axes.margin.viz[oMargin]; + } + delete d.d3plus.r; + d.d3plus[w] = newSize; + d.d3plus[h] = Math.abs(length); + d.d3plus.init = {}; + d.d3plus.init[opposite] = oppMethod.scale.viz(zero); + d.d3plus.init[opposite] -= d.d3plus[opposite]; + d.d3plus.init[opposite] += vars.axes.margin.viz[oMargin]; + d.d3plus.init[w] = d.d3plus[w]; + if (vars.text.value) { + delete d.d3plus.label; + } else { + d.d3plus.label = false; + } + data.push(d); + } + } + return data; +}; + +bar.filter = function(vars, data) { + return nest(vars, data, vars[vars.axes.discrete].value); +}; + +bar.requirements = ["data", "x", "y"]; + +bar.setup = function(vars) { + var axis, size, y; + if (!vars.axes.discrete) { + axis = vars.time.value === vars.y.value ? "y" : "x"; + vars.self[axis]({ + scale: "discrete" + }); + } + y = vars[vars.axes.opposite]; + size = vars.size; + if ((!y.value && size.value) || (size.changed && size.previous === y.value)) { + return vars.self[vars.axes.opposite](size.value); + } else if ((!size.value && y.value) || (y.changed && y.previous === size.value)) { + return vars.self.size(y.value); + } +}; + +bar.shapes = ["square"]; + +module.exports = bar; + + +},{"../../core/fetch/value.coffee":67,"../../util/buckets.coffee":204,"../../util/uniques.coffee":210,"./helpers/graph/draw.coffee":314,"./helpers/graph/nest.coffee":320,"./helpers/graph/stack.coffee":321}],309:[function(require,module,exports){ +var box, fetchValue, graph, stringFormat, strip, uniques; + +fetchValue = require("../../core/fetch/value.coffee"); + +graph = require("./helpers/graph/draw.coffee"); + +stringFormat = require("../../string/format.js"); + +strip = require("../../string/strip.js"); + +uniques = require("../../util/uniques.coffee"); + +box = function(vars) { + var botstr, disMargin, discrete, domains, h, iqrstr, maxstr, medians, medstr, mergeData, minstr, mode, noData, oppMargin, opposite, pctstr, qt1str, qt3str, returnData, size, space, topstr, w; + graph(vars, { + buffer: true + }); + domains = vars.x.domain.viz.concat(vars.y.domain.viz); + if (domains.indexOf(void 0) >= 0) { + return []; + } + discrete = vars.axes.discrete; + opposite = vars.axes.opposite; + disMargin = discrete === "x" ? vars.axes.margin.viz.left : vars.axes.margin.viz.top; + oppMargin = opposite === "x" ? vars.axes.margin.viz.left : vars.axes.margin.viz.top; + h = discrete === "x" ? "height" : "width"; + w = discrete === "x" ? "width" : "height"; + space = vars.axes[w] / vars[discrete].ticks.values.length; + size = vars.size.value; + size = typeof size === "number" ? size : 100; + space = d3.min([space - vars.labels.padding * 2, size]); + mode = vars.type.mode.value; + if (!(mode instanceof Array)) { + mode = [mode, mode]; + } + mergeData = function(arr) { + var key, obj, vals; + obj = {}; + for (key in vars.data.keys) { + vals = uniques(arr, key, fetchValue, vars); + obj[key] = vals.length === 1 ? vals[0] : vals; + } + return obj; + }; + noData = false; + medians = []; + iqrstr = vars.format.value(vars.format.locale.value.ui.iqr); + maxstr = vars.format.value(vars.format.locale.value.ui.max); + minstr = vars.format.value(vars.format.locale.value.ui.min); + pctstr = vars.format.value(vars.format.locale.value.ui.percentile); + botstr = vars.format.value(vars.format.locale.value.ui.tukey_bottom); + topstr = vars.format.value(vars.format.locale.value.ui.tukey_top); + qt1str = vars.format.value(vars.format.locale.value.ui.quartile_first); + qt3str = vars.format.value(vars.format.locale.value.ui.quartile_third); + medstr = vars.format.value(vars.format.locale.value.ui.median); + returnData = []; + d3.nest().key(function(d) { + return fetchValue(vars, d, vars[discrete].value); + }).rollup(function(leaves) { + var bottom, bottomLabel, bottomWhisker, boxData, d, diff1, diff2, first, i, iqr, j, key, label, len, len1, median, medianBuffer, medianData, medianHeight, medianText, outliers, scale, second, tooltipData, top, topLabel, topWhisker, uniqs, val, values, x, y; + scale = vars[opposite].scale.viz; + values = leaves.map(function(d) { + return fetchValue(vars, d, vars[opposite].value); + }); + values.sort(function(a, b) { + return a - b; + }); + uniqs = uniques(values); + first = d3.quantile(values, 0.25); + median = d3.quantile(values, 0.50); + second = d3.quantile(values, 0.75); + tooltipData = {}; + if (mode[1] === "tukey") { + iqr = first - second; + top = second - iqr * 1.5; + topLabel = topstr; + } else if (mode[1] === "extent") { + top = d3.max(values); + topLabel = maxstr; + } else if (typeof mode[1] === "number") { + top = d3.quantile(values, (100 - mode[1]) / 100); + topLabel = stringFormat(pctstr, mode[1]); + } + top = d3.min([d3.max(values), top]); + if (vars.tooltip.extent.value) { + tooltipData[topLabel] = { + key: vars[opposite].value, + value: top + }; + } + if (vars.tooltip.iqr.value) { + tooltipData[qt3str] = { + key: vars[opposite].value, + value: second + }; + tooltipData[medstr] = { + key: vars[opposite].value, + value: median + }; + tooltipData[qt1str] = { + key: vars[opposite].value, + value: first + }; + } + if (mode[0] === "tukey") { + iqr = first - second; + bottom = first + iqr * 1.5; + bottomLabel = botstr; + } else if (mode[0] === "extent") { + bottom = d3.min(values); + bottomLabel = minstr; + } else if (typeof mode[0] === "number") { + bottom = d3.quantile(values, mode[0] / 100); + topLabel = stringFormat(pctstr, mode[0]); + } + bottom = d3.max([d3.min(values), bottom]); + if (vars.tooltip.extent.value) { + tooltipData[bottomLabel] = { + key: vars[opposite].value, + value: bottom + }; + } + boxData = []; + bottomWhisker = []; + topWhisker = []; + outliers = []; + for (i = 0, len = leaves.length; i < len; i++) { + d = leaves[i]; + val = fetchValue(vars, d, vars[opposite].value); + if (val >= first && val <= second) { + boxData.push(d); + } else if (val >= bottom && val < first) { + bottomWhisker.push(d); + } else if (val <= top && val > second) { + topWhisker.push(d); + } else { + outliers.push(d); + } + } + key = fetchValue(vars, leaves[0], vars[discrete].value); + x = vars[discrete].scale.viz(key); + x += disMargin; + label = vars.format.value(key, { + key: vars[discrete].value, + vars: vars + }); + if (key.constructor === Date) { + key = key.getTime(); + } + key = strip(key); + boxData = mergeData(boxData); + boxData.d3plus = { + color: "white", + id: "box_" + key, + init: {}, + label: false, + shape: "square", + stroke: "#444", + text: stringFormat(iqrstr, label) + }; + boxData.d3plus[w] = space; + boxData.d3plus.init[w] = space; + boxData.d3plus[h] = Math.abs(scale(first) - scale(second)); + boxData.d3plus[discrete] = x; + y = d3.min([scale(first), scale(second)]) + boxData.d3plus[h] / 2; + y += oppMargin; + boxData.d3plus[opposite] = y; + boxData.d3plus.tooltip = tooltipData; + returnData.push(boxData); + medianData = { + d3plus: { + id: "median_line_" + key, + position: h === "height" ? "top" : "right", + shape: "whisker", + "static": true + } + }; + medianText = vars.format.value(median, { + key: vars[opposite].value, + vars: vars + }); + label = { + background: "#fff", + names: [medianText], + padding: 0, + resize: false, + x: 0, + y: 0 + }; + diff1 = Math.abs(scale(median) - scale(first)); + diff2 = Math.abs(scale(median) - scale(second)); + medianHeight = d3.min([diff1, diff2]) * 2; + medianBuffer = vars.data.stroke.width * 2 + vars.labels.padding * 2; + label[w === "width" ? "w" : "h"] = space - medianBuffer; + label[h === "width" ? "w" : "h"] = medianHeight - medianBuffer; + medianData.d3plus.label = label; + medianData.d3plus[w] = space; + medianData.d3plus[discrete] = x; + medianData.d3plus[opposite] = scale(median) + oppMargin; + returnData.push(medianData); + bottomWhisker = mergeData(bottomWhisker); + bottomWhisker.d3plus = { + id: "bottom_whisker_line_" + key, + offset: boxData.d3plus[h] / 2, + position: h === "height" ? "bottom" : "left", + shape: "whisker", + "static": true + }; + if (opposite === "x") { + bottomWhisker.d3plus.offset *= -1; + } + bottomWhisker.d3plus[h] = Math.abs(scale(bottom) - scale(first)); + bottomWhisker.d3plus[w] = space; + bottomWhisker.d3plus[discrete] = x; + bottomWhisker.d3plus[opposite] = y; + returnData.push(bottomWhisker); + topWhisker = mergeData(topWhisker); + topWhisker.d3plus = { + id: "top_whisker_line_" + key, + offset: boxData.d3plus[h] / 2, + position: h === "height" ? "top" : "right", + shape: "whisker", + "static": true + }; + if (opposite === "y") { + topWhisker.d3plus.offset *= -1; + } + topWhisker.d3plus[h] = Math.abs(scale(top) - scale(second)); + topWhisker.d3plus[w] = space; + topWhisker.d3plus[discrete] = x; + topWhisker.d3plus[opposite] = y; + returnData.push(topWhisker); + for (j = 0, len1 = outliers.length; j < len1; j++) { + d = outliers[j]; + d.d3plus[discrete] = x; + d.d3plus[opposite] = scale(fetchValue(vars, d, vars.y.value)); + d.d3plus[opposite] += oppMargin; + d.d3plus.r = 4; + d.d3plus.shape = vars.shape.value; + } + noData = !outliers.length && top - bottom === 0; + medians.push(median); + returnData = returnData.concat(outliers); + return leaves; + }).entries(vars.data.viz); + if (noData && uniques(medians).length === 1) { + return []; + } else { + return returnData; + } +}; + +box.modes = ["tukey", "extent", Array, Number]; + +box.requirements = ["data", "x", "y"]; + +box.shapes = ["circle", "check", "cross", "diamond", "square", "triangle", "triangle_up", "triangle_down"]; + +box.setup = function(vars) { + var axis; + if (!vars.axes.discrete) { + axis = vars.time.value === vars.y.value ? "y" : "x"; + return vars.self[axis]({ + scale: "discrete" + }); + } +}; + +module.exports = box; + + +},{"../../core/fetch/value.coffee":67,"../../string/format.js":173,"../../string/strip.js":175,"../../util/uniques.coffee":210,"./helpers/graph/draw.coffee":314}],310:[function(require,module,exports){ +var arraySort, bubbles, fetchColor, fetchText, fetchValue, groupData, legible; + +arraySort = require("../../array/sort.coffee"); + +fetchValue = require("../../core/fetch/value.coffee"); + +fetchColor = require("../../core/fetch/color.coffee"); + +fetchText = require("../../core/fetch/text.js"); + +legible = require("../../color/legible.coffee"); + +groupData = require("../../core/data/group.coffee"); + +bubbles = function(vars) { + var column_height, column_width, columns, d, data, dataLength, domain, domainMax, domainMin, downscale, groupedData, i, j, k, l, labelHeight, len, len1, len2, obj, pack, padding, row, rows, screenRatio, size, size_max, size_min, t, temp, userDomainMax, userDomainMin, xPadding, xoffset, yMod, yPadding, yoffset; + groupedData = groupData(vars, vars.data.viz); + groupedData = arraySort(groupedData, null, null, null, vars); + dataLength = groupedData.length; + if (dataLength < 4) { + columns = dataLength; + rows = 1; + } else { + screenRatio = vars.width.viz / vars.height.viz; + columns = Math.ceil(Math.sqrt(dataLength * screenRatio)); + rows = Math.ceil(Math.sqrt(dataLength / screenRatio)); + } + if (dataLength > 0) { + while ((rows - 1) * columns >= dataLength) { + rows--; + } + } + column_width = vars.width.viz / columns; + column_height = vars.height.viz / rows; + if (vars.size.value) { + userDomainMin = vars.size.scale.domain.min.value; + userDomainMax = vars.size.scale.domain.max.value; + if (typeof userDomainMin === 'number') { + domainMin = userDomainMin; + } else { + domainMin = d3.min(vars.data.viz, function(d) { + return fetchValue(vars, d, vars.size.value, vars.id.value, "min"); + }); + } + if (typeof userDomainMax === 'number') { + domainMax = userDomainMax; + } else { + domainMax = d3.max(vars.data.viz, function(d) { + return fetchValue(vars, d, vars.size.value, vars.id.value); + }); + } + domain = [domainMin, domainMax]; + } else { + domain = [0, 0]; + } + padding = 5; + size_max = (d3.min([column_width, column_height]) / 2) - (padding * 2); + labelHeight = vars.labels.value && !vars.small && size_max >= 40 ? d3.max([20, d3.min([size_max * 0.25, 50])]) : 0; + size_max -= labelHeight; + size_min = d3.min([size_max, vars.size.scale.range.min.value]); + size = vars.size.scale.value.domain(domain).rangeRound([size_min, size_max]); + pack = d3.layout.pack().children(function(d) { + return d.values; + }).padding(padding).radius(function(d) { + return size(d); + }).size([column_width - padding * 2, column_height - padding * 2 - labelHeight]).value(function(d) { + return d.value; + }); + data = []; + row = 0; + for (i = j = 0, len = groupedData.length; j < len; i = ++j) { + d = groupedData[i]; + temp = pack.nodes(d); + xoffset = (column_width * i) % vars.width.viz; + yoffset = column_height * row; + for (k = 0, len1 = temp.length; k < len1; k++) { + t = temp[k]; + if (t.children) { + obj = { + d3plus: {} + }; + obj[vars.id.value] = t.key; + } else { + obj = t.d3plus; + } + obj.d3plus.depth = vars.id.grouping.value ? t.depth : vars.depth.value; + obj.d3plus.x = t.x; + obj.d3plus.xOffset = xoffset; + obj.d3plus.y = t.y; + obj.d3plus.yOffset = yoffset + labelHeight; + obj.d3plus.r = t.r; + data.push(obj); + } + if ((i + 1) % columns === 0) { + row++; + } + } + downscale = size_max / d3.max(data, function(d) { + return d.d3plus.r; + }); + xPadding = pack.size()[0] / 2; + yPadding = pack.size()[1] / 2; + for (l = 0, len2 = data.length; l < len2; l++) { + d = data[l]; + d.d3plus.x = ((d.d3plus.x - xPadding) * downscale) + xPadding + d.d3plus.xOffset; + d.d3plus.y = ((d.d3plus.y - yPadding) * downscale) + yPadding + d.d3plus.yOffset; + d.d3plus.r = d.d3plus.r * downscale; + delete d.d3plus.xOffset; + delete d.d3plus.yOffset; + d.d3plus["static"] = d.d3plus.depth < vars.depth.value && vars.id.grouping.value; + if (labelHeight && (d.d3plus.depth === 0 || vars.id.grouping.value === false)) { + d.d3plus.text = fetchText(vars, d[vars.id.value], d.d3plus.depth); + yMod = labelHeight > vars.labels.padding * 3 ? vars.labels.padding : 0; + d.d3plus.label = { + x: 0, + y: -(size_max + yMod + labelHeight / 2), + w: size_max * 2, + h: labelHeight - yMod, + padding: 0, + resize: true, + color: legible(fetchColor(vars, d, d.d3plus.depth)), + force: true + }; + } else { + delete d.d3plus.label; + } + } + return data.sort(function(a, b) { + return a.d3plus.depth - b.d3plus.depth; + }); +}; + +bubbles.fill = true; + +bubbles.requirements = ["data"]; + +bubbles.scale = 1.05; + +bubbles.shapes = ["circle", "donut"]; + +module.exports = bubbles; + + +},{"../../array/sort.coffee":34,"../../color/legible.coffee":44,"../../core/data/group.coffee":57,"../../core/fetch/color.coffee":63,"../../core/fetch/text.js":66,"../../core/fetch/value.coffee":67}],311:[function(require,module,exports){ +var chart, print; + +print = require("../../../core/console/print.coffee"); + +chart = function(vars) { + var type, types; + types = { + circle: "scatter", + donut: "scatter", + line: "line", + square: "scatter", + area: "stacked" + }; + type = types[vars.shape.value]; + print.warning("The \"chart\" visualization type has been deprecated and will be removed in version 2.0. Please use the \"" + type + "\" visualization type."); + vars.self.type(type).draw(); +}; + +chart.shapes = ["circle", "donut", "line", "square", "area"]; + +module.exports = chart; + + +},{"../../../core/console/print.coffee":52}],312:[function(require,module,exports){ +var geo_map; + +geo_map = function(vars) { + var coords, features, key, mute, solo, topo; + coords = vars.coords.value; + key = vars.coords.key || d3.keys(coords.objects)[0]; + topo = topojson.feature(coords, coords.objects[key]); + features = topo.features; + solo = vars.coords.solo.value; + mute = vars.coords.mute.value; + features = features.filter(function(f) { + f[vars.id.value] = f.id; + if (solo.length) { + return solo.indexOf(f.id) >= 0; + } else if (mute.length) { + return mute.indexOf(f.id) < 0; + } else { + return true; + } + }); + return features; +}; + +geo_map.libs = ["topojson"]; + +geo_map.nesting = false; + +geo_map.requirements = ["coords"]; + +geo_map.scale = 1; + +geo_map.shapes = ["coordinates"]; + +geo_map.zoom = true; + +module.exports = geo_map; + + +},{}],313:[function(require,module,exports){ +var color, legible, print; + +color = require("../../../../core/fetch/color.coffee"); + +legible = require("../../../../color/legible.coffee"); + +print = require("../../../../core/console/print.coffee"); + +module.exports = function(vars) { + var axes, axis, axisData, data, i, len, margin, ref, style, tick, ticks, timing; + axes = vars.axes; + margin = vars.axes.margin.viz; + data = axes.stacked || !axes.ticks.value ? [] : vars.data.viz; + timing = data.length * 2 > vars.data.large ? 0 : vars.draw.timing; + style = function(line, axis) { + if (axis.indexOf("y") === 0) { + line.attr("x1", -2).attr("x2", -8).attr("y1", function(d) { + return d.d3plus.y - margin.top; + }).attr("y2", function(d) { + return d.d3plus.y - margin.top; + }); + } else { + line.attr("x1", function(d) { + return d.d3plus.x - margin.left; + }).attr("x2", function(d) { + return d.d3plus.x - margin.left; + }).attr("y1", axes.height + 2).attr("y2", axes.height + 8); + } + return line.style("stroke", function(d) { + return legible(color(vars, d)); + }).style("stroke-width", vars.data.stroke.width).attr("shape-rendering", vars.shape.rendering.value); + }; + if (vars.dev.value) { + print.time("creating axis tick groups"); + } + ticks = vars.group.select("g#d3plus_graph_plane").selectAll("g.d3plus_data_tick").data(data, function(d) { + var mod; + mod = axes.discrete ? "_" + d.d3plus[axes.discrete] : ""; + return "tick_" + d[vars.id.value] + "_" + d.d3plus.depth + mod; + }); + ticks.enter().append("g").attr("class", "d3plus_data_tick").attr("opacity", 0); + if (vars.dev.value) { + print.timeEnd("creating axis tick groups"); + } + ref = ["x", "y"]; + for (i = 0, len = ref.length; i < len; i++) { + axis = ref[i]; + if (vars.dev.value && timing) { + print.time("creating " + axis + " ticks"); + } + axisData = timing && axis !== axes.discrete ? data : []; + tick = ticks.selectAll("line.d3plus_data_" + axis).data(axisData, function(d) { + return "tick_" + d[vars.id.value] + "_" + d.d3plus.depth; + }); + if (vars.dev.value && timing) { + print.timeEnd("creating " + axis + " ticks"); + } + if (vars.dev.value && timing) { + print.time("styling " + axis + " ticks"); + } + if (timing > 0) { + tick.transition().duration(timing).call(style, axis); + } else { + tick.call(style, axis); + } + tick.enter().append("line").attr("class", "d3plus_data_" + axis).call(style, axis); + if (vars.dev.value && timing) { + print.timeEnd("styling " + axis + " ticks"); + } + } + if (timing > 0) { + ticks.transition().duration(timing).attr("opacity", 1); + ticks.exit().transition().duration(timing).attr("opacity", 0).remove(); + } else { + ticks.attr("opacity", 1); + ticks.exit().remove(); + } +}; + + +},{"../../../../color/legible.coffee":44,"../../../../core/console/print.coffee":52,"../../../../core/fetch/color.coffee":63}],314:[function(require,module,exports){ +var axes, draw, mouse, plot; + +axes = require("./includes/axes.coffee"); + +draw = require("./includes/svg.coffee"); + +mouse = require("./includes/mouse.coffee"); + +plot = require("./includes/plot.coffee"); + +module.exports = function(vars, opts) { + if (opts === void 0) { + opts = {}; + } + axes(vars, opts); + plot(vars, opts); + draw(vars, opts); + vars.mouse.viz = opts.mouse === true ? mouse : false; +}; + + +},{"./includes/axes.coffee":315,"./includes/mouse.coffee":317,"./includes/plot.coffee":318,"./includes/svg.coffee":319}],315:[function(require,module,exports){ +var arraySort, axisRange, buckets, buffer, dataChange, fetchData, fetchValue, getData, getScale, print, sizeScale, uniques; + +arraySort = require("../../../../../array/sort.coffee"); + +buffer = require("./buffer.coffee"); + +buckets = require("../../../../../util/buckets.coffee"); + +fetchData = require("../../../../../core/fetch/data.js"); + +fetchValue = require("../../../../../core/fetch/value.coffee"); + +print = require("../../../../../core/console/print.coffee"); + +uniques = require("../../../../../util/uniques.coffee"); + +module.exports = function(vars, opts) { + var axes, axis, changed, domains, i, j, len, len1, oppAxis, range, reorder, zero; + changed = dataChange(vars); + if (changed || !vars.axes.dataset) { + vars.axes.dataset = getData(vars); + } + vars.axes.scale = opts.buffer && opts.buffer !== true ? sizeScale(vars, opts.buffer) : false; + axes = vars.width.viz > vars.height.viz ? ["y", "y2", "x", "x2"] : ["x", "x2", "y", "y2"]; + for (i = 0, len = axes.length; i < len; i++) { + axis = axes[i]; + oppAxis = axis.indexOf("x") === 0 ? "y" : "x"; + reorder = vars.order.changed || vars.order.sort.changed || (vars.order.value === true && vars[oppAxis].changed); + if (vars[axis].value && (!vars[axis].ticks.values || changed || reorder || (vars[axis].value === vars.time.value && vars.time.fixed.value))) { + if (vars.dev.value) { + print.time("calculating " + axis + " axis"); + } + vars[axis].reset = true; + vars[axis].ticks.values = false; + if (axis === vars.axes.discrete && vars[axis].value !== vars.time.value) { + vars[axis].ticks.values = uniques(vars.axes.dataset, vars[axis].value, fetchValue, vars); + } + zero = opts.zero === true || axis.indexOf(opts.zero) === 0 ? true : false; + range = axisRange(vars, axis, zero); + if (axis.indexOf("y") === 0) { + range = range.reverse(); + } + vars[axis].scale.viz = getScale(vars, axis, range); + vars[axis].domain.viz = range; + if (vars.dev.value) { + print.timeEnd("calculating " + axis + " axis"); + } + } + } + if (vars.axes.mirror.value) { + domains = d3.extent(vars.y.domain.viz.concat(vars.x.domain.viz)); + vars.x.domain.viz = domains; + vars.x.scale.viz.domain(domains); + domains = domains.slice().reverse(); + vars.y.domain.viz = domains; + vars.y.scale.viz.domain(domains); + } + if (opts.buffer) { + for (j = 0, len1 = axes.length; j < len1; j++) { + axis = axes[j]; + if (axis !== vars.axes.discrete) { + buffer(vars, axis, opts.buffer); + } + } + } +}; + +dataChange = function(vars) { + var axis, changed, check, i, j, k, l, len, len1, len2, ref, sub, subs; + changed = !vars.time.fixed.value && (vars.time.solo.changed || vars.time.mute.changed); + if (!changed) { + changed = vars.id.solo.changed || vars.id.mute.changed; + } + if (changed) { + return changed; + } + check = ["data", "time", "id", "depth", "type", "width", "height", "x", "y", "x2", "y2"]; + for (i = 0, len = check.length; i < len; i++) { + k = check[i]; + if (vars[k].changed) { + changed = true; + break; + } + } + if (changed) { + return changed; + } + subs = ["mute", "range", "scale", "solo", "stacked", "zerofill"]; + ref = ["x", "y", "x2", "y2"]; + for (j = 0, len1 = ref.length; j < len1; j++) { + axis = ref[j]; + for (l = 0, len2 = subs.length; l < len2; l++) { + sub = subs[l]; + if (vars[axis][sub].changed) { + changed = true; + break; + } + } + } + return changed; +}; + +getData = function(vars) { + var d, depths; + if (!vars.time.fixed.value) { + return vars.data.viz; + } else { + depths = d3.range(0, vars.id.nesting.length); + return d3.merge(d3.merge([ + (function() { + var i, len, results; + results = []; + for (i = 0, len = depths.length; i < len; i++) { + d = depths[i]; + results.push(fetchData(vars, "all", d)); + } + return results; + })() + ])); + } +}; + +axisRange = function(vars, axis, zero, buffer) { + var agg, aggType, allNegative, allPositive, axisSums, counts, d, group, i, j, k, l, len, len1, len2, len3, m, min, oppAxis, ref, ref1, ref2, ref3, sort, sortKey, splitData, v, val, values; + oppAxis = axis.indexOf("x") === 0 ? "y" : "x"; + if (vars[axis].range.value && vars[axis].range.value.length === 2) { + return vars[axis].range.value.slice(); + } else if (vars[axis].scale.value === "share") { + vars[axis].ticks.values = d3.range(0, 1.1, 0.1); + return [0, 1]; + } else if (vars[axis].stacked.value) { + splitData = []; + ref = vars.axes.dataset; + for (i = 0, len = ref.length; i < len; i++) { + d = ref[i]; + if (d.values) { + splitData = splitData.concat(d.values); + } else { + splitData.push(d); + } + } + axisSums = d3.nest().key(function(d) { + return fetchValue(vars, d, vars[oppAxis].value); + }).rollup(function(leaves) { + var negatives, positives; + positives = d3.sum(leaves, function(d) { + var val; + val = fetchValue(vars, d, vars[axis].value); + if (val > 0) { + return val; + } else { + return 0; + } + }); + negatives = d3.sum(leaves, function(d) { + var val; + val = fetchValue(vars, d, vars[axis].value); + if (val < 0) { + return val; + } else { + return 0; + } + }); + return [negatives, positives]; + }).entries(splitData); + values = d3.merge(axisSums.map(function(d) { + return d.values; + })); + return d3.extent(values); + } else if (vars[axis].value === vars.time.value) { + if (vars.time.solo.value.length) { + return d3.extent(vars.time.solo.value).map(function(v) { + if (v.constructor !== Date) { + v = v + ""; + if (v.length === 4 && parseInt(v) + "" === v) { + v += "/01/01"; + } + return new Date(v); + } else { + return v; + } + }); + } else { + return d3.extent(vars.data.time.ticks); + } + } else { + values = []; + ref1 = vars.axes.dataset; + for (j = 0, len1 = ref1.length; j < len1; j++) { + d = ref1[j]; + val = fetchValue(vars, d, vars[axis].value); + if (val instanceof Array) { + values = values.concat(val); + } else { + values.push(val); + } + } + values = values.filter(function(d) { + return d !== null; + }); + if (axis === vars.axes.discrete) { + if (vars.order.value === true) { + sortKey = vars[oppAxis].value; + } else { + sortKey = vars.order.value; + } + if (sortKey) { + sort = vars.order.sort.value; + agg = vars.order.agg.value || vars.aggs.value[sortKey] || "max"; + aggType = typeof agg; + counts = values.reduce(function(obj, val) { + obj[val] = []; + return obj; + }, {}); + ref2 = vars.axes.dataset; + for (l = 0, len2 = ref2.length; l < len2; l++) { + d = ref2[l]; + if (d.values) { + ref3 = d.values; + for (m = 0, len3 = ref3.length; m < len3; m++) { + v = ref3[m]; + group = fetchValue(vars, v, vars[axis].value); + counts[group].push(fetchValue(vars, v, sortKey)); + } + } else { + group = fetchValue(vars, d, vars[axis].value); + counts[group].push(fetchValue(vars, d, sortKey)); + } + } + for (k in counts) { + v = counts[k]; + if (aggType === "string") { + counts[k] = d3[agg](v); + } else if (aggType === "function") { + counts[k] = agg(v, sortKey); + } + } + counts = arraySort(d3.entries(counts), "value", sort); + counts = counts.reduce(function(arr, v) { + arr.push(v.key); + return arr; + }, []); + return counts; + } else if (values[0].constructor === String) { + return uniques(values).sort(function(a, b) { + return "" + a.localeCompare("" + b); + }); + } else { + return uniques(values).sort(function(a, b) { + return a - b; + }); + } + } else { + values.sort(function(a, b) { + return a - b; + }); + if (vars[axis].scale.value === "log") { + if (values[0] === 0) { + values[0] = 1; + } + if (values[values.length - 1] === 0) { + values[values.length - 1] = -1; + } + } + if (zero) { + allPositive = values.every(function(v) { + return v > 0; + }); + allNegative = values.every(function(v) { + return v < 0; + }); + if (allPositive || allNegative) { + min = allPositive ? 1 : -1; + values.push(vars[axis].scale.value === "log" ? min : 0); + } + } + return d3.extent(values); + } + } +}; + +getScale = function(vars, axis, range) { + var rangeArray, rangeMax, retScale, scaleType, t; + rangeMax = axis.indexOf("x") === 0 ? vars.width.viz : vars.height.viz; + scaleType = vars[axis].scale.value; + if (["discrete", "share"].indexOf(scaleType) >= 0) { + scaleType = "linear"; + } + t = 10; + if (typeof range[0] === "string") { + scaleType = "ordinal"; + rangeArray = buckets([0, rangeMax], range.length); + } else { + rangeArray = [0, rangeMax]; + if (vars[axis].scale.value === "linear") { + t = Math.floor(rangeMax / (vars[axis].ticks.font.size * 4)); + } + } + vars[axis].scale.ticks = t; + retScale = d3.scale[scaleType]().domain(range).range(rangeArray); + if ("clamp" in retScale) { + retScale.clamp(true); + } + return retScale; +}; + +sizeScale = function(vars, value) { + var domain, max, min; + if (value === true) { + value = "size"; + } + if (value in vars) { + value = vars[value].value; + } + min = vars.size.scale.range.min.value; + if (typeof min === "function") { + min = min(vars); + } + max = vars.size.scale.range.max.value; + if (typeof max === "function") { + max = max(vars); + } + if (value === false) { + return vars.size.scale.value.domain([0, 1]).rangeRound([max, max]); + } else if (typeof value === "number") { + return vars.size.scale.value.domain([0, 1]).rangeRound([value, value]); + } else if (value) { + if (vars.dev.value) { + print.time("calculating buffer scale"); + } + domain = d3.extent(vars.axes.dataset, function(d) { + var val; + val = fetchValue(vars, d, value); + if (!val) { + return 0; + } else { + return val; + } + }); + if (domain[0] === domain[1]) { + min = max; + } + if (vars.dev.value) { + print.timeEnd("calculating buffer scale"); + } + return vars.size.scale.value.domain(domain).rangeRound([min, max]); + } +}; + + +},{"../../../../../array/sort.coffee":34,"../../../../../core/console/print.coffee":52,"../../../../../core/fetch/data.js":64,"../../../../../core/fetch/value.coffee":67,"../../../../../util/buckets.coffee":204,"../../../../../util/uniques.coffee":210,"./buffer.coffee":316}],316:[function(require,module,exports){ +var buckets, closest; + +buckets = require("../../../../../util/buckets.coffee"); + +closest = require("../../../../../util/closest.coffee"); + +module.exports = function(vars, axis, buffer) { + var add, additional, allNegative, allPositive, closestTime, copy, d, diff, difference, domain, domainCompare, domainHigh, domainLow, i, lowerDiff, lowerMod, lowerScale, lowerValue, maxSize, opp, orig_domain, range, rangeMax, second, strings, testScale, timeIndex, upperDiff, upperMod, upperScale, upperValue, zero; + if (vars[axis].scale.value !== "share" && !vars[axis].range.value && vars[axis].reset) { + testScale = vars[axis].scale.viz.copy(); + if ("clamp" in testScale) { + testScale.clamp(false); + } + if (axis === vars.axes.discrete) { + domain = testScale.domain(); + if (typeof domain[0] === "string") { + i = domain.length; + while (i >= 0) { + domain.splice(i, 0, "d3plus_buffer_" + i); + i--; + } + range = testScale.range(); + range = buckets(d3.extent(range), domain.length); + return vars[axis].scale.viz.domain(domain).range(range); + } else { + if (axis.indexOf("y") === 0) { + domain = domain.slice().reverse(); + } + if (vars[axis].ticks.values.length === 1) { + domain = [domain[0], domain[0]]; + if (vars[axis].value === vars.time.value && vars.data.time.ticks.length !== 1) { + closestTime = closest(vars.data.time.ticks, domain[0]); + timeIndex = vars.data.time.ticks.indexOf(closestTime); + if (timeIndex > 0) { + domain[0] = vars.data.time.ticks[timeIndex - 1]; + } else { + diff = vars.data.time.ticks[timeIndex + 1] - closestTime; + domain[0] = new Date(closestTime.getTime() - diff); + } + if (timeIndex < vars.data.time.ticks.length - 1) { + domain[1] = vars.data.time.ticks[timeIndex + 1]; + } else { + diff = closestTime - vars.data.time.ticks[timeIndex - 1]; + domain[1] = new Date(closestTime.getTime() + diff); + } + } else { + domain[0] -= 1; + domain[1] += 1; + } + } else if (vars.axes.scale) { + difference = Math.abs(domain[1] - domain[0]); + additional = difference / (vars[axis].ticks.values.length - 1); + additional = additional / 2; + rangeMax = testScale.range()[1]; + maxSize = vars.axes.scale.range()[1] * 1.5; + domainLow = testScale.invert(-maxSize); + domainHigh = testScale.invert(rangeMax + maxSize); + if (domain[0] - additional < domainLow) { + domain[0] = domain[0] - additional; + domain[domain.length - 1] = domain[domain.length - 1] + additional; + } else { + domain = [domainLow, domainHigh]; + if (axis.indexOf("y") === 0) { + domain = domain.reverse(); + } + domainCompare = testScale.domain(); + domainCompare = domainCompare[1] - domainCompare[0]; + if (!domainCompare) { + domain[0] -= 1; + domain[1] += 1; + } + } + } else if (vars[axis].value === vars.time.value) { + difference = Math.abs(domain[1] - domain[0]); + additional = difference / (vars[axis].ticks.values.length - 1); + additional = additional / 2; + domain[0] = domain[0] - additional; + domain[1] = domain[1] + additional; + } else { + difference = Math.abs(domain[1] - domain[0]); + add = difference / 2; + i = domain.length; + orig_domain = domain.slice(); + while (i >= 0) { + d = i ? orig_domain[i - 1] + add : orig_domain[i] - add; + domain.splice(i, 0, d); + i--; + } + range = testScale.range(); + range = buckets(d3.extent(range), domain.length); + vars[axis].scale.viz.domain(domain).range(range); + } + if (axis.indexOf("y") === 0) { + domain = domain.reverse(); + } + return vars[axis].scale.viz.domain(domain); + } + } else if ((buffer === "x" && axis.indexOf("x") === 0) || (buffer === "y" && axis.indexOf("y") === 0) || (buffer === true)) { + domain = testScale.domain(); + allPositive = domain[0] >= 0 && domain[1] >= 0; + allNegative = domain[0] <= 0 && domain[1] <= 0; + if (vars[axis].scale.value === "log") { + zero = allPositive ? 1 : -1; + if (allPositive && axis.indexOf("y") === 0) { + domain = domain.slice().reverse(); + } + lowerScale = Math.pow(10, parseInt(Math.abs(domain[0])).toString().length - 1) * zero; + lowerMod = domain[0] % lowerScale; + lowerDiff = lowerMod; + if (lowerMod && lowerDiff / lowerScale <= 0.1) { + lowerDiff += lowerScale * zero; + } + lowerValue = lowerMod === 0 ? lowerScale : lowerDiff; + domain[0] -= lowerValue; + if (domain[0] === 0) { + domain[0] = zero; + } + upperScale = Math.pow(10, parseInt(Math.abs(domain[1])).toString().length - 1) * zero; + upperMod = domain[1] % upperScale; + upperDiff = Math.abs(upperScale - upperMod); + if (upperMod && upperDiff / upperScale <= 0.1) { + upperDiff += upperScale * zero; + } + upperValue = upperMod === 0 ? upperScale : upperDiff; + domain[1] += upperValue; + if (domain[1] === 0) { + domain[1] = zero; + } + if (allPositive && axis.indexOf("y") === 0) { + domain = domain.reverse(); + } + } else { + zero = 0; + if (axis.indexOf("y") === 0) { + domain = domain.slice().reverse(); + } + strings = domain.filter(function(d) { + return d.constructor === String; + }); + additional = Math.abs(domain[1] - domain[0]) * 0.05 || 1; + if (!strings.length) { + domain[0] = domain[0] - additional; + domain[1] = domain[1] + additional; + if ((allPositive && domain[0] < zero) || (allNegative && domain[0] > zero)) { + domain[0] = zero; + } + if ((allPositive && domain[1] < zero) || (allNegative && domain[1] > zero)) { + domain[1] = zero; + } + } + if (axis.indexOf("y") === 0) { + domain = domain.reverse(); + } + } + return vars[axis].scale.viz.domain(domain); + } else if (vars.axes.scale) { + copy = false; + if (vars.axes.mirror.value) { + opp = axis.indexOf("y") === 0 ? "x" : "y"; + copy = vars[opp].scale.viz; + second = vars.width.viz > vars.height.viz ? "x" : "y"; + } + if (axis === second && copy) { + domain = copy.domain().slice().reverse(); + } else { + rangeMax = testScale.range()[1]; + maxSize = vars.axes.scale.range()[1]; + domainLow = testScale.invert(-maxSize * 1.5); + domainHigh = testScale.invert(rangeMax + maxSize * 1.5); + domain = [domainLow, domainHigh]; + if (axis.indexOf("y") === 0) { + domain = domain.reverse(); + } + domainCompare = testScale.domain(); + domainCompare = domainCompare[1] - domainCompare[0]; + if (!domainCompare) { + domain[0] -= 1; + domain[1] += 1; + } + if (axis.indexOf("y") === 0) { + domain = domain.reverse(); + } + } + return vars[axis].scale.viz.domain(domain); + } + } +}; + + +},{"../../../../../util/buckets.coffee":204,"../../../../../util/closest.coffee":206}],317:[function(require,module,exports){ +var copy, events, fetchColor, fetchValue, legible, textColor; + +copy = require("../../../../../util/copy.coffee"); + +events = require("../../../../../client/pointer.coffee"); + +fetchColor = require("../../../../../core/fetch/color.coffee"); + +fetchValue = require("../../../../../core/fetch/value.coffee"); + +legible = require("../../../../../color/legible.coffee"); + +textColor = require("../../../../../color/text.coffee"); + +module.exports = function(node, vars) { + var clickRemove, color, create, graph, lineData, lineInit, lineStyle, lineUpdate, lines, margin, r, rectStyle, rects, s, textStyle, texts, timing, x, y; + clickRemove = d3.event.type === events.click && (vars.tooltip.value.long || vars.tooltip.html.value); + create = [events.over, events.move].indexOf(d3.event.type) >= 0; + x = node.d3plus.x; + y = node.d3plus.y; + r = node.d3plus.r || 0; + s = vars.types[vars.type.value].scale || 1; + r = r * s; + graph = vars.axes; + margin = vars.axes.margin.viz; + timing = vars.draw.timing ? vars.timing.mouseevents : 0; + if (!clickRemove && create) { + color = legible(fetchColor(vars, node)); + lineData = ["x", "y", "x2", "y2"].filter(function(axis) { + var val; + val = fetchValue(vars, node, vars[axis].value); + return val && !(val instanceof Array) && axis !== vars.axes.stacked && vars[axis].mouse.value; + }); + } else { + lineData = []; + } + lineInit = function(line) { + return line.attr("x1", function(d) { + if (d.indexOf("x") === 0) { + return x; + } else { + return x - r; + } + }).attr("y1", function(d) { + if (d.indexOf("y") === 0) { + return y; + } else { + return y + r; + } + }).attr("x2", function(d) { + if (d.indexOf("x") === 0) { + return x; + } else { + return x - r; + } + }).attr("y2", function(d) { + if (d.indexOf("y") === 0) { + return y; + } else { + return y + r; + } + }).attr("opacity", 0); + }; + lineStyle = function(line) { + return line.style("stroke", function(d) { + if (vars.shape.value === "area") { + return "white"; + } else { + return color; + } + }).attr("stroke-dasharray", function(d) { + return vars[d].mouse.dasharray.value; + }).attr("shape-rendering", function(d) { + return vars[d].mouse.rendering.value; + }).style("stroke-width", function(d) { + return vars[d].mouse.width; + }); + }; + lineUpdate = function(line) { + return line.attr("x1", function(d) { + if (d.indexOf("x") === 0) { + return x; + } else { + return x - r; + } + }).attr("y1", function(d) { + if (d.indexOf("y") === 0) { + return y; + } else { + return y + r; + } + }).attr("x2", function(d) { + if (d.indexOf("x") === 0) { + return x; + } else if (node.d3plus.x0) { + return node.d3plus.x0; + } else if (d === "y") { + return margin.left - vars[d].ticks.size; + } else { + return margin.left + graph.width + vars[d].ticks.size; + } + }).attr("y2", function(d) { + if (d.indexOf("y") === 0) { + return y; + } else if (node.d3plus.y0) { + return node.d3plus.y0; + } else if (d === "x") { + return graph.height + margin.top + vars[d].ticks.size; + } else { + return margin.top - vars[d].ticks.size; + } + }).style("opacity", 1); + }; + lines = vars.g.labels.selectAll("line.d3plus_mouse_axis_label").data(lineData); + if (timing) { + lines.enter().append("line").attr("class", "d3plus_mouse_axis_label").attr("pointer-events", "none").call(lineInit).call(lineStyle); + lines.transition().duration(timing).call(lineUpdate).call(lineStyle); + lines.exit().transition().duration(timing).call(lineInit).remove(); + } else { + lines.call(lineUpdate).call(lineStyle); + lines.enter().append("line").attr("class", "d3plus_mouse_axis_label").attr("pointer-events", "none").call(lineInit).call(lineStyle); + lines.exit().remove(); + } + textStyle = function(text) { + return text.attr("font-size", function(d) { + return vars[d].ticks.font.size + "px"; + }).attr("font-family", function(d) { + return vars[d].ticks.font.family.value; + }).attr("font-weight", function(d) { + return vars[d].ticks.font.weight; + }).attr("x", function(d) { + if (d.indexOf("x") === 0) { + return x; + } else if (d === "y") { + return margin.left - 5 - vars[d].ticks.size; + } else { + return margin.left + graph.width + 5 + vars[d].ticks.size; + } + }).attr("y", function(d) { + if (d.indexOf("y") === 0) { + return y; + } else if (node.d3plus.y0) { + return node.d3plus.y + (node.d3plus.y0 - node.d3plus.y) / 2 + margin.top - 6; + } else if (d === "x") { + return graph.height + margin.top + 5 + vars[d].ticks.size; + } else { + return margin.top - 5 - vars[d].ticks.size - (vars[d].ticks.font.size * 1.35); + } + }).attr("fill", vars.shape.value === "area" ? "white" : textColor(color)); + }; + texts = vars.g.labels.selectAll("text.d3plus_mouse_axis_label").data(lineData); + texts.enter().append("text").attr("class", "d3plus_mouse_axis_label").attr("id", function(d) { + return d + "_d3plusmouseaxislabel"; + }).attr("dy", function(d) { + if (d.indexOf("y") === 0) { + return vars[d].ticks.font.size * 0.35; + } else { + return vars[d].ticks.font.size; + } + }).style("text-anchor", function(d) { + if (d === "y") { + return "end"; + } else if (d === "y2") { + return "start"; + } else { + return "middle"; + } + }).attr("opacity", 0).attr("pointer-events", "none").call(textStyle); + texts.text(function(d) { + var axis, val; + axis = vars.axes.stacked || d; + val = fetchValue(vars, node, vars[axis].value); + return vars.format.value(val, { + key: vars[axis].value, + vars: vars, + labels: vars[axis].affixes.value + }); + }); + if (timing) { + texts.transition().duration(timing).delay(timing).attr("opacity", 1).call(textStyle); + texts.exit().transition().duration(timing).attr("opacity", 0).remove(); + } else { + texts.attr("opacity", 1).call(textStyle); + texts.exit().remove(); + } + rectStyle = function(rect) { + var getText; + getText = function(axis) { + var l; + l = d3.select("text#" + axis + "_d3plusmouseaxislabel"); + if (l.size()) { + return l.node().getBBox(); + } else { + return { + "width": 0, + "height": 0 + }; + } + }; + return rect.attr("x", function(d) { + var width; + width = getText(d).width; + if (d.indexOf("x") === 0) { + return x - width / 2 - 5; + } else if (d === "y") { + return margin.left - vars[d].ticks.size - width - 10; + } else { + return margin.left + graph.width + vars[d].ticks.size; + } + }).attr("y", function(d) { + var height; + height = getText(d).height; + if (d.indexOf("y") === 0) { + return y - (height / 2 + 5); + } else if (node.d3plus.y0) { + return node.d3plus.y + (node.d3plus.y0 - node.d3plus.y) / 2 + margin.top - (height / 2 + 5); + } else if (d === "x") { + return graph.height + margin.top + vars[d].ticks.size; + } else { + return margin.top - vars[d].ticks.size - height - 10; + } + }).attr("width", function(d) { + return getText(d).width + 10; + }).attr("height", function(d) { + return getText(d).height + 10; + }).style("stroke", vars.shape.value === "area" ? "transparent" : color).attr("fill", color).attr("shape-rendering", function(d) { + return vars[d].mouse.rendering.value; + }).style("stroke-width", function(d) { + return vars[d].mouse.width; + }); + }; + rects = vars.g.labels.selectAll("rect.d3plus_mouse_axis_label").data(lineData); + if (timing) { + rects.enter().insert("rect", "text.d3plus_mouse_axis_label").attr("class", "d3plus_mouse_axis_label").attr("pointer-events", "none").attr("opacity", 0).call(rectStyle); + rects.transition().duration(timing).delay(timing).attr("opacity", 1).call(rectStyle); + return rects.exit().transition().duration(timing).attr("opacity", 0).remove(); + } else { + rects.attr("opacity", 1).call(rectStyle); + rects.enter().insert("rect", "text.d3plus_mouse_axis_label").attr("class", "d3plus_mouse_axis_label").attr("pointer-events", "none").call(rectStyle); + return rects.exit().remove(); + } +}; + + +},{"../../../../../client/pointer.coffee":38,"../../../../../color/legible.coffee":44,"../../../../../color/text.coffee":50,"../../../../../core/fetch/color.coffee":63,"../../../../../core/fetch/value.coffee":67,"../../../../../util/copy.coffee":207}],318:[function(require,module,exports){ +var buckets, buffer, createAxis, fetchValue, fontSizes, formatPower, labelPadding, superscript, textwrap, timeDetect, uniques; + +buckets = require("../../../../../util/buckets.coffee"); + +buffer = require("./buffer.coffee"); + +fetchValue = require("../../../../../core/fetch/value.coffee"); + +fontSizes = require("../../../../../font/sizes.coffee"); + +textwrap = require("../../../../../textwrap/textwrap.coffee"); + +timeDetect = require("../../../../../core/data/time.coffee"); + +uniques = require("../../../../../util/uniques.coffee"); + +module.exports = function(vars, opts) { + var axes, axis, axisStyle, extent, j, k, l, len, len1, len2, newtick, opp, otherScale, scale, step, tens, tick, ticks, timeReturn, values; + vars.axes.margin.viz = { + top: vars.axes.margin.top, + right: vars.axes.margin.right, + bottom: vars.axes.margin.bottom, + left: vars.axes.margin.left + }; + vars.axes.height = vars.height.viz; + vars.axes.width = vars.width.viz; + axes = vars.width.viz > vars.height.viz ? ["y", "y2", "x", "x2"] : ["x", "x2", "y", "y2"]; + for (j = 0, len = axes.length; j < len; j++) { + axis = axes[j]; + if (vars[axis].value) { + if (vars[axis].ticks.values === false) { + if (vars[axis].value === vars.time.value) { + ticks = vars.time.solo.value; + if (ticks.length) { + ticks = ticks.map(function(d) { + if (d.constructor !== Date) { + d = d + ""; + if (d.length === 4 && parseInt(d) + "" === d) { + d += "/01/01"; + } + d = new Date(d); + } + return d; + }); + } else { + ticks = vars.data.time.values; + } + extent = d3.extent(ticks); + step = vars.data.time.stepType; + ticks = [extent[0]]; + tick = extent[0]; + while (tick < extent[1]) { + newtick = new Date(tick); + tick = new Date(newtick["set" + step](newtick["get" + step]() + 1)); + ticks.push(tick); + } + vars[axis].ticks.values = ticks; + } else { + if (axis.indexOf("2") === 1) { + otherScale = vars[axis.slice(0, 1)].scale.viz; + scale = vars[axis].scale.viz; + ticks = vars[axis.slice(0, 1)].scale.ticks; + vars[axis].ticks.values = otherScale.ticks(ticks).map(function(t) { + return parseFloat(d3.format(".5f")(scale.invert(otherScale(t)))); + }); + } else { + vars[axis].ticks.values = vars[axis].scale.viz.ticks(vars[axis].scale.ticks); + } + } + } + if (!vars[axis].ticks.values.length) { + values = fetchValue(vars, vars.data.viz, vars[axis].value); + if (!(values instanceof Array)) { + values = [values]; + } + vars[axis].ticks.values = values; + } + opp = axis.indexOf("x") === 0 ? "y" : "x"; + if (vars[axis].ticks.values.length === 1 || (opts.buffer && opts.buffer !== opp && axis === vars.axes.discrete && vars[axis].reset === true)) { + buffer(vars, axis, opts.buffer); + } + vars[axis].reset = false; + if (vars[axis].value === vars.time.value) { + axisStyle = { + "font-family": vars[axis].ticks.font.family.value, + "font-weight": vars[axis].ticks.font.weight, + "font-size": vars[axis].ticks.font.size + "px", + "text-transform": vars[axis].ticks.font.transform.value, + "letter-spacing": vars[axis].ticks.font.spacing + "px" + }; + timeReturn = timeDetect(vars, { + values: vars[axis].ticks.values, + limit: vars.width.viz, + style: axisStyle + }); + if (vars[axis].ticks.value) { + vars[axis].ticks.visible = vars[axis].ticks.value.map(Number); + } else if (vars[axis].ticks.labels.value.constructor === Array) { + vars[axis].ticks.visible = vars[axis].ticks.labels.value.map(Number); + } else { + vars[axis].ticks.visible = timeReturn.values.map(Number); + } + vars[axis].ticks.format = timeReturn.format; + } else if (vars[axis].ticks.value) { + vars[axis].ticks.values = vars[axis].ticks.value; + if (vars[axis].ticks.labels.value.constructor === Array) { + vars[axis].ticks.visible = vars[axis].ticks.labels.value; + } else { + vars[axis].ticks.visible = vars[axis].ticks.value; + } + } else if (vars[axis].ticks.labels.value.constructor === Array) { + vars[axis].ticks.visible = vars[axis].ticks.labels.value; + } else if (vars[axis].scale.value === "log") { + ticks = vars[axis].ticks.values; + tens = ticks.filter(function(t) { + return Math.abs(t).toString().charAt(0) === "1"; + }); + if (tens.length < 3) { + vars[axis].ticks.visible = ticks; + } else { + vars[axis].ticks.visible = tens; + } + } else { + vars[axis].ticks.visible = vars[axis].ticks.values; + } + if (vars[axis].value === vars.time.value) { + vars[axis].ticks.visible = vars[axis].ticks.visible.map(function(d) { + if (d.constructor === Number && ("" + d).length > 4) { + return d; + } + d += ""; + if (d.length === 4 && parseInt(d) + "" === d) { + d += "/01/01"; + } + return new Date(d).getTime(); + }); + } + } + } + if (vars.small) { + vars.axes.width -= vars.axes.margin.viz.left + vars.axes.margin.viz.right; + vars.axes.height -= vars.axes.margin.viz.top + vars.axes.margin.viz.bottom; + for (k = 0, len1 = axes.length; k < len1; k++) { + axis = axes[k]; + vars[axis].label.height = 0; + } + } else { + if (!vars.small) { + labelPadding(vars); + } + } + for (l = 0, len2 = axes.length; l < len2; l++) { + axis = axes[l]; + vars[axis].axis.svg = createAxis(vars, axis); + } +}; + +labelPadding = function(vars) { + var axis, j, k, lastTick, len, len1, margin, ref, ref1, rightLabel, rightMod, x2Domain, xAttrs, xAxisHeight, xAxisWidth, xDomain, xLabel, xLabelAttrs, xMaxWidth, xSizes, xText, xValues, y2Domain, yAttrs, yAxisWidth, yDomain, yLabel, yLabelAttrs, yText, yValues; + xDomain = vars.x.scale.viz.domain(); + yDomain = vars.y.scale.viz.domain(); + if (vars.x2.value) { + x2Domain = vars.x2.scale.viz.domain(); + } + if (vars.y2.value) { + y2Domain = vars.y2.scale.viz.domain(); + } + ref = ["y", "y2"]; + for (j = 0, len = ref.length; j < len; j++) { + axis = ref[j]; + if (vars[axis].value) { + margin = axis === "y" ? "left" : "right"; + yAttrs = { + "font-size": vars[axis].ticks.font.size + "px", + "font-family": vars[axis].ticks.font.family.value, + "font-weight": vars[axis].ticks.font.weight, + "text-transform": vars[axis].ticks.font.transform.value, + "letter-spacing": vars[axis].ticks.font.spacing + "px" + }; + yValues = vars[axis].ticks.visible; + if (vars[axis].scale.value === "log") { + yText = yValues.map(function(d) { + return formatPower(d); + }); + } else if (vars[axis].scale.value === "share") { + yText = yValues.map(function(d) { + return vars.format.value(d * 100, { + key: "share", + vars: vars, + output: axis + }); + }); + } else if (vars[axis].value === vars.time.value) { + yText = yValues.map(function(d, i) { + return vars[axis].ticks.format(new Date(d)); + }); + } else { + if (typeof yValues[0] === "string") { + yValues = vars[axis].scale.viz.domain().filter(function(d) { + return d.indexOf("d3plus_buffer_") !== 0; + }); + } + yText = yValues.map(function(d) { + return vars.format.value(d, { + key: vars[axis].value, + vars: vars, + labels: vars[axis].affixes.value, + output: axis + }); + }); + } + if (vars[axis].ticks.labels.value) { + vars[axis].ticks.hidden = false; + yAxisWidth = d3.max(fontSizes(yText, yAttrs), function(d) { + return d.width; + }); + if (yAxisWidth) { + yAxisWidth = Math.ceil(yAxisWidth + vars.labels.padding); + vars.axes.margin.viz[margin] += yAxisWidth; + } + } else { + vars[axis].ticks.hidden = true; + } + yLabel = vars[axis].label.fetch(vars); + if (yLabel) { + yLabelAttrs = { + "font-family": vars[axis].label.font.family.value, + "font-weight": vars[axis].label.font.weight, + "font-size": vars[axis].label.font.size + "px", + "text-transform": vars[axis].label.font.transform.value, + "letter-spacing": vars[axis].label.font.spacing + "px" + }; + vars[axis].label.height = fontSizes([yLabel], yLabelAttrs)[0].height; + } else { + vars[axis].label.height = 0; + } + if (vars[axis].label.value) { + vars.axes.margin.viz[margin] += vars[axis].label.height; + vars.axes.margin.viz[margin] += vars[axis].label.padding * 2; + } + } + } + vars.axes.width -= vars.axes.margin.viz.left + vars.axes.margin.viz.right; + vars.x.scale.viz.range(buckets([0, vars.axes.width], xDomain.length)); + if (x2Domain) { + vars.x2.scale.viz.range(buckets([0, vars.axes.width], x2Domain.length)); + } + ref1 = ["x", "x2"]; + for (k = 0, len1 = ref1.length; k < len1; k++) { + axis = ref1[k]; + if (vars[axis].value) { + margin = axis === "x" ? "bottom" : "top"; + if (vars[axis].ticks.labels.value) { + vars[axis].ticks.hidden = false; + xAttrs = { + "font-size": vars[axis].ticks.font.size + "px", + "font-family": vars[axis].ticks.font.family.value, + "font-weight": vars[axis].ticks.font.weight, + "text-transform": vars[axis].ticks.font.transform.value, + "letter-spacing": vars[axis].ticks.font.spacing + "px" + }; + xValues = vars[axis].ticks.visible; + if (vars[axis].scale.value === "log") { + xText = xValues.map(function(d) { + return formatPower(d); + }); + } else if (vars[axis].scale.value === "share") { + xText = xValues.map(function(d) { + return vars.format.value(d * 100, { + key: "share", + vars: vars, + output: axis + }); + }); + } else if (vars[axis].value === vars.time.value) { + xText = xValues.map(function(d, i) { + return vars[axis].ticks.format(new Date(d)); + }); + } else { + if (typeof xValues[0] === "string") { + xValues = vars[axis].scale.viz.domain().filter(function(d) { + return d.indexOf("d3plus_buffer_") !== 0; + }); + } + xText = xValues.map(function(d) { + return vars.format.value(d, { + key: vars[axis].value, + vars: vars, + labels: vars[axis].affixes.value, + output: axis + }); + }); + } + xSizes = fontSizes(xText, xAttrs); + xAxisWidth = d3.max(xSizes, function(d) { + return d.width; + }); + xAxisHeight = d3.max(xSizes, function(d) { + return d.height; + }); + if (xValues.length === 1) { + xMaxWidth = vars.axes.width; + } else { + xMaxWidth = vars[axis].scale.viz(xValues[1]) - vars[axis].scale.viz(xValues[0]); + xMaxWidth = Math.abs(xMaxWidth); + } + if (xAxisWidth > xMaxWidth && xText.join("").indexOf(" ") > 0) { + vars[axis].ticks.wrap = true; + xSizes = fontSizes(xText, xAttrs, { + mod: function(elem) { + return textwrap().container(d3.select(elem)).height(vars.axes.height / 2).width(xMaxWidth).draw(); + } + }); + xAxisWidth = d3.max(xSizes, function(d) { + return d.width; + }); + xAxisHeight = d3.max(xSizes, function(d) { + return d.height; + }); + } else { + vars[axis].ticks.wrap = false; + } + vars[axis].ticks.baseline = "auto"; + if (xAxisWidth <= xMaxWidth) { + vars[axis].ticks.rotate = 0; + } else if (xAxisWidth < vars.axes.height / 2) { + xSizes = fontSizes(xText, xAttrs, { + mod: function(elem) { + return textwrap().container(d3.select(elem)).width(vars.axes.height / 2).height(xMaxWidth).draw(); + } + }); + xAxisHeight = d3.max(xSizes, function(d) { + return d.width; + }); + xAxisWidth = d3.max(xSizes, function(d) { + return d.height; + }); + vars[axis].ticks.rotate = -90; + } else { + xAxisWidth = 0; + xAxisHeight = 0; + } + if (!(xAxisWidth && xAxisHeight)) { + vars[axis].ticks.hidden = true; + vars[axis].ticks.rotate = 0; + } + xAxisWidth = Math.ceil(xAxisWidth); + xAxisHeight = Math.ceil(xAxisHeight); + vars[axis].ticks.maxHeight = xAxisHeight; + vars[axis].ticks.maxWidth = xAxisWidth; + if (xAxisHeight) { + vars.axes.margin.viz[margin] += xAxisHeight + vars.labels.padding; + } + lastTick = vars[axis].ticks.visible[vars[axis].ticks.visible.length - 1]; + rightLabel = vars[axis].scale.viz(lastTick); + rightLabel += xAxisWidth / 2 + vars.axes.margin.viz.left; + if (rightLabel > vars.width.value) { + rightMod = rightLabel - vars.width.value + vars.axes.margin.viz.right; + vars.axes.width -= rightMod; + vars.axes.margin.viz.right += rightMod; + } + } else { + vars[axis].ticks.hidden = true; + } + xLabel = vars[axis].label.fetch(vars); + if (xLabel) { + xLabelAttrs = { + "font-family": vars[axis].label.font.family.value, + "font-weight": vars[axis].label.font.weight, + "font-size": vars[axis].label.font.size + "px", + "text-transform": vars[axis].label.font.transform.value, + "letter-spacing": vars[axis].label.font.spacing + "px" + }; + vars[axis].label.height = fontSizes([xLabel], xLabelAttrs)[0].height; + } else { + vars[axis].label.height = 0; + } + if (vars[axis].label.value) { + vars.axes.margin.viz[margin] += vars[axis].label.height; + vars.axes.margin.viz[margin] += vars[axis].label.padding * 2; + } + } + } + vars.axes.height -= vars.axes.margin.viz.top + vars.axes.margin.viz.bottom; + vars.x.scale.viz.range(buckets([0, vars.axes.width], xDomain.length)); + if (x2Domain) { + vars.x2.scale.viz.range(buckets([0, vars.axes.width], x2Domain.length)); + } + vars.y.scale.viz.range(buckets([0, vars.axes.height], yDomain.length)); + if (y2Domain) { + return vars.y2.scale.viz.range(buckets([0, vars.axes.height], y2Domain.length)); + } +}; + +createAxis = function(vars, axis) { + return d3.svg.axis().tickSize(vars[axis].ticks.size).tickPadding(5).orient(vars[axis].orient.value).scale(vars[axis].scale.viz).tickValues(vars[axis].ticks.values).tickFormat(function(d, i) { + var c, scale; + if (vars[axis].ticks.hidden) { + return null; + } + scale = vars[axis].scale.value; + c = d.constructor === Date ? +d : d; + if (vars[axis].ticks.visible.indexOf(c) >= 0) { + if (scale === "share") { + return vars.format.value(d * 100, { + key: "share", + vars: vars, + labels: vars[axis].affixes.value, + output: axis + }); + } else if (d.constructor === Date) { + return vars[axis].ticks.format(d); + } else if (scale === "log") { + return formatPower(d); + } else { + return vars.format.value(d, { + key: vars[axis].value, + vars: vars, + labels: vars[axis].affixes.value, + output: axis + }); + } + } else { + return null; + } + }); +}; + +superscript = "⁰¹²³⁴⁵⁶⁷⁸⁹"; + +formatPower = function(d) { + var n, p, t; + p = Math.round(Math.log(Math.abs(d)) / Math.LN10); + t = Math.abs(d).toString().charAt(0); + n = 10 + " " + (p + "").split("").map(function(c) { + return superscript[c]; + }).join(""); + if (t !== "1") { + n = t + " x " + n; + } + if (d < 0) { + return "-" + n; + } else { + return n; + } +}; + + +},{"../../../../../core/data/time.coffee":62,"../../../../../core/fetch/value.coffee":67,"../../../../../font/sizes.coffee":102,"../../../../../textwrap/textwrap.coffee":200,"../../../../../util/buckets.coffee":204,"../../../../../util/uniques.coffee":210,"./buffer.coffee":316}],319:[function(require,module,exports){ +var mix, textwrap, validObject; + +mix = require("../../../../../color/mix.coffee"); + +textwrap = require("../../../../../textwrap/textwrap.coffee"); + +validObject = require("../../../../../object/validate.coffee"); + +module.exports = function(vars) { + var affixes, alignMap, axis, axisData, axisGroup, axisLabel, bg, bgStyle, d, domain, domains, getFontStyle, grid, gridData, groupEnter, j, k, l, label, labelData, labelStyle, len, len1, len2, len3, len4, line, lineData, lineFont, lineGroup, lineRects, lineStyle, lines, linetexts, m, mirror, n, opp, plane, planeTrans, position, realData, rectData, rectStyle, ref, ref1, ref2, ref3, rotated, sep, style, textData, textPad, textPos, tickFont, tickPosition, tickStyle, userLines, valid, xStyle, yStyle; + domains = vars.x.domain.viz.concat(vars.y.domain.viz); + if (domains.indexOf(void 0) >= 0) { + return null; + } + bgStyle = { + width: vars.axes.width, + height: vars.axes.height, + fill: vars.axes.background.color, + stroke: vars.axes.background.stroke.color, + "stroke-width": vars.axes.background.stroke.width, + "shape-rendering": vars.axes.background.rendering.value + }; + alignMap = { + left: "start", + center: "middle", + right: "end" + }; + axisData = vars.small ? [] : [0]; + tickPosition = function(tick, axis) { + return tick.attr("x1", function(d) { + if (axis.indexOf("x") === 0) { + return vars.x.scale.viz(d); + } else { + return 0; + } + }).attr("x2", function(d) { + if (axis.indexOf("x") === 0) { + return vars.x.scale.viz(d); + } else { + return vars.axes.width; + } + }).attr("y1", function(d) { + if (axis.indexOf("y") === 0) { + return vars.y.scale.viz(d); + } else { + return 0; + } + }).attr("y2", function(d) { + if (axis.indexOf("y") === 0) { + return vars.y.scale.viz(d); + } else { + return vars.axes.height; + } + }); + }; + tickStyle = function(tick, axis, grid) { + var color, log, visibles; + color = grid ? vars[axis].grid.color : vars[axis].ticks.color; + log = vars[axis].scale.value === "log"; + visibles = vars[axis].ticks.visible || []; + return tick.attr("stroke", function(d) { + var visible; + if (d === 0) { + return vars[axis].axis.color; + } + if (d.constructor === Date) { + d = +d; + } + visible = visibles.indexOf(d) >= 0; + if (visible && (!log || Math.abs(d).toString().charAt(0) === "1")) { + return color; + } else if (grid && vars.axes.background.color !== "transparent") { + return mix(color, vars.axes.background.color, 0.4, 1); + } else if (vars.background.value !== "transparent") { + return mix(color, vars.background.value, 0.4, 1); + } else { + return mix(color, "white", 0.4, 1); + } + }).attr("stroke-width", vars[axis].ticks.width).attr("shape-rendering", vars[axis].ticks.rendering.value); + }; + getFontStyle = function(axis, val, style) { + var type; + type = val === 0 ? "axis" : "ticks"; + val = vars[axis][type].font[style]; + if (val && (val.length || typeof val === "number")) { + return val; + } else { + return vars[axis].ticks.font[style]; + } + }; + tickFont = function(tick, axis) { + var log; + log = vars[axis].scale.value === "log"; + return tick.attr("font-size", function(d) { + return getFontStyle(axis, d, "size") + "px"; + }).attr("stroke", "none").attr("fill", function(d) { + var color; + color = getFontStyle(axis, d, "color"); + if (!log || Math.abs(d).toString().charAt(0) === "1") { + return color; + } else { + return mix(color, vars.background.value, 0.4, 1); + } + }).attr("font-family", function(d) { + return getFontStyle(axis, d, "family").value; + }).attr("font-weight", function(d) { + return getFontStyle(axis, d, "weight"); + }).style("text-transform", function(d) { + return getFontStyle(axis, d, "transform").value; + }).style("letter-spacing", function(d) { + return getFontStyle(axis, d, "spacing") + "px"; + }); + }; + lineStyle = function(line, axis) { + var max, opp; + max = axis.indexOf("x") === 0 ? "height" : "width"; + opp = axis.indexOf("x") === 0 ? "y" : "x"; + return line.attr(opp + "1", 0).attr(opp + "2", vars.axes[max]).attr(axis + "1", function(d) { + return d.coords.line; + }).attr(axis + "2", function(d) { + return d.coords.line; + }).attr("stroke", function(d) { + return d.color || vars[axis].lines.color; + }).attr("stroke-width", vars[axis].lines.width).attr("shape-rendering", vars[axis].lines.rendering.value).attr("stroke-dasharray", vars[axis].lines.dasharray.value); + }; + lineFont = function(text, axis) { + var opp; + opp = axis.indexOf("x") === 0 ? "y" : "x"; + return text.attr(opp, function(d) { + return d.coords.text[opp] + "px"; + }).attr(axis, function(d) { + return d.coords.text[axis] + "px"; + }).attr("dy", vars[axis].lines.font.position.value).attr("text-anchor", alignMap[vars[axis].lines.font.align.value]).attr("transform", function(d) { + return d.transform; + }).attr("font-size", vars[axis].lines.font.size + "px").attr("fill", function(d) { + return d.color || vars[axis].lines.color; + }).attr("font-family", vars[axis].lines.font.family.value).attr("font-weight", vars[axis].lines.font.weight); + }; + planeTrans = "translate(" + vars.axes.margin.viz.left + "," + vars.axes.margin.viz.top + ")"; + plane = vars.group.selectAll("g#d3plus_graph_plane").data([0]); + plane.transition().duration(vars.draw.timing).attr("transform", planeTrans); + plane.enter().append("g").attr("id", "d3plus_graph_plane").attr("transform", planeTrans); + bg = plane.selectAll("rect#d3plus_graph_background").data([0]); + bg.transition().duration(vars.draw.timing).attr(bgStyle); + bg.enter().append("rect").attr("id", "d3plus_graph_background").attr("x", 0).attr("y", 0).attr(bgStyle); + mirror = plane.selectAll("path#d3plus_graph_mirror").data([0]); + mirror.enter().append("path").attr("id", "d3plus_graph_mirror").attr("fill", "#000").attr("fill-opacity", 0.03).attr("stroke-width", 1).attr("stroke", "#ccc").attr("stroke-dasharray", "10,10").attr("opacity", 0); + mirror.transition().duration(vars.draw.timing).attr("opacity", function() { + if (vars.axes.mirror.value) { + return 1; + } else { + return 0; + } + }).attr("d", function() { + var h, w; + w = bgStyle.width; + h = bgStyle.height; + return "M " + w + " " + h + " L 0 " + h + " L " + w + " 0 Z"; + }); + rotated = vars.x.ticks.rotate !== 0; + xStyle = function(group, axis) { + var groups, offset; + offset = axis === "x" ? vars.axes.height : 0; + groups = group.attr("transform", "translate(0," + offset + ")").call(vars[axis].axis.svg.scale(vars[axis].scale.viz)).selectAll("g.tick"); + groups.selectAll("line").attr("y2", function(d) { + var y2; + if (d.constructor === Date) { + d = +d; + } + y2 = d3.select(this).attr("y2"); + if (vars[axis].ticks.visible.indexOf(d) >= 0) { + return y2; + } else { + return y2 / 2; + } + }); + return groups.select("text").style("text-anchor", rotated && axis === "x" ? "end" : rotated ? "start" : "middle").call(tickFont, axis).each(function(d) { + d3.select(this).attr("dy", "0px").attr("font-size", function(d) { + return getFontStyle(axis, d, "size") + "px"; + }); + if (d.constructor === Date) { + d = +d; + } + if (!vars[axis].ticks.hidden && vars[axis].ticks.visible.indexOf(d) >= 0) { + return textwrap().container(d3.select(this)).rotate(vars[axis].ticks.rotate).align(rotated ? "end" : "center").valign(rotated ? "middle" : axis === "x" ? "top" : "bottom").width(vars[axis].ticks.maxWidth + 2).height(vars[axis].ticks.maxHeight).padding(0).x(-vars[axis].ticks.maxWidth / 2).y(axis === "x2" ? -(vars[axis].ticks.maxHeight + vars.labels.padding * 2) : 0).draw(); + } + }); + }; + yStyle = function(group, axis) { + var groups, offset; + offset = axis === "y2" ? vars.axes.width : 0; + groups = group.attr("transform", "translate(" + offset + ", 0)").call(vars[axis].axis.svg.scale(vars[axis].scale.viz)).selectAll("g.tick"); + groups.selectAll("line").attr("y2", function(d) { + var y2; + if (d.constructor === Date) { + d = +d; + } + y2 = d3.select(this).attr("y2"); + if (vars.x.ticks.visible.indexOf(d) >= 0) { + return y2; + } else { + return y2 / 2; + } + }); + return groups.select("text").call(tickFont, axis); + }; + ref = ["x", "x2", "y", "y2"]; + for (j = 0, len = ref.length; j < len; j++) { + axis = ref[j]; + style = axis.indexOf("x") === 0 ? xStyle : yStyle; + realData = axisData.length && vars[axis].value ? [0] : []; + axisGroup = plane.selectAll("g#d3plus_graph_" + axis + "ticks").data(realData); + axisGroup.transition().duration(vars.draw.timing).call(style, axis); + axisGroup.selectAll("line").transition().duration(vars.draw.timing).call(tickStyle, axis); + groupEnter = axisGroup.enter().append("g").attr("id", "d3plus_graph_" + axis + "ticks").call(style, axis); + groupEnter.selectAll("path").attr("fill", "none").attr("stroke", "none"); + groupEnter.selectAll("line").call(tickStyle, axis); + axisGroup.exit().transition().duration(vars.data.timing).attr("opacity", 0).remove(); + } + labelStyle = function(label, axis) { + return label.attr("x", axis.indexOf("x") === 0 ? vars.width.viz / 2 : -(vars.axes.height / 2 + vars.axes.margin.viz.top)).attr("y", axis === "x" ? vars.height.viz - vars[axis].label.height / 2 - vars[axis].label.padding : axis === "y2" ? vars.width.viz - vars[axis].label.height / 2 - vars[axis].label.padding : vars[axis].label.height / 2 + vars[axis].label.padding).attr("transform", axis.indexOf("y") === 0 ? "rotate(-90)" : null).attr("font-family", vars[axis].label.font.family.value).attr("font-weight", vars[axis].label.font.weight).attr("font-size", vars[axis].label.font.size + "px").attr("fill", vars[axis].label.font.color).style("text-anchor", "middle").attr("dominant-baseline", "central").style("text-transform", vars[axis].label.font.transform.value).style("letter-spacing", vars[axis].label.font.spacing + "px"); + }; + ref1 = ["x", "y"]; + for (k = 0, len1 = ref1.length; k < len1; k++) { + axis = ref1[k]; + if (vars[axis].grid.value) { + if (vars[axis].ticks.value) { + gridData = vars[axis].ticks.value; + } else { + gridData = vars[axis].ticks.values; + } + } else { + gridData = []; + opp = axis === "x" ? "y" : "x"; + if (vars[axis].ticks.values.indexOf(0) >= 0 && vars[opp].axis.value) { + gridData = [0]; + } + } + if (vars[axis].value === vars.time.value) { + gridData = gridData.map(function(d) { + d += ""; + if (d.length === 4 && parseInt(d) + "" === d) { + d += "/01/01"; + } + return new Date(d).getTime(); + }); + } + grid = plane.selectAll("g#d3plus_graph_" + axis + "grid").data([0]); + grid.enter().append("g").attr("id", "d3plus_graph_" + axis + "grid"); + lines = grid.selectAll("line").data(gridData, function(d, i) { + if (d.constructor === Date) { + return d.getTime(); + } else { + return d; + } + }); + lines.transition().duration(vars.draw.timing).call(tickPosition, axis).call(tickStyle, axis, true); + lines.enter().append("line").style("opacity", 0).call(tickPosition, axis).call(tickStyle, axis, true).transition().duration(vars.draw.timing).delay(vars.draw.timing / 2).style("opacity", 1); + lines.exit().transition().duration(vars.draw.timing / 2).style("opacity", 0).remove(); + } + ref2 = ["x", "x2", "y", "y2"]; + for (l = 0, len2 = ref2.length; l < len2; l++) { + axis = ref2[l]; + if (vars[axis].value) { + axisLabel = vars[axis].label.fetch(vars); + labelData = axisData && axisLabel && !vars.small ? [0] : []; + affixes = vars.format.affixes.value[vars[axis].value]; + if (axisLabel && !vars[axis].affixes.value && affixes) { + sep = vars[axis].affixes.separator.value; + if (sep === true) { + sep = ["[", "]"]; + } else if (sep === false) { + sep = ["", ""]; + } + axisLabel += " " + sep[0] + affixes[0] + " " + affixes[1] + sep[1]; + } + } else { + axisLabel = ""; + labelData = []; + } + label = vars.group.selectAll("text#d3plus_graph_" + axis + "label").data(labelData); + label.text(axisLabel).transition().duration(vars.draw.timing).call(labelStyle, axis); + label.enter().append("text").attr("stroke", "none").attr("id", "d3plus_graph_" + axis + "label").text(axisLabel).call(labelStyle, axis); + label.exit().transition().duration(vars.data.timing).attr("opacity", 0).remove(); + } + ref3 = ["x", "y", "x2", "y2"]; + for (m = 0, len3 = ref3.length; m < len3; m++) { + axis = ref3[m]; + if (vars[axis].value) { + lineGroup = plane.selectAll("g#d3plus_graph_" + axis + "_userlines").data([0]); + lineGroup.enter().append("g").attr("id", "d3plus_graph_" + axis + "_userlines"); + domain = vars[axis].scale.viz.domain(); + if (axis.indexOf("y") === 0) { + domain = domain.slice().reverse(); + } + textData = []; + lineData = []; + userLines = vars[axis].lines.value || []; + for (n = 0, len4 = userLines.length; n < len4; n++) { + line = userLines[n]; + d = validObject(line) ? line.position : line; + if (axis === vars.axes.discrete) { + valid = domain.indexOf(d) >= 0; + } else { + valid = d >= domain[0] && d <= domain[1]; + } + if (valid) { + d = !validObject(line) ? { + "position": d + } : line; + d.coords = { + line: vars[axis].scale.viz(d.position) + }; + lineData.push(d); + if (d.text) { + d.axis = axis; + d.padding = vars[axis].lines.font.padding.value * 0.5; + d.align = vars[axis].lines.font.align.value; + position = vars[axis].lines.font.position.text; + textPad = position === "middle" ? 0 : d.padding * 2; + if (position === "top") { + textPad = -textPad; + } + if (axis.indexOf("x") === 0) { + textPos = d.align === "left" ? vars.axes.height : d.align === "center" ? vars.axes.height / 2 : 0; + if (d.align === "left") { + textPos -= d.padding * 2; + } + if (d.align === "right") { + textPos += d.padding * 2; + } + } else { + textPos = d.align === "left" ? 0 : d.align === "center" ? vars.axes.width / 2 : vars.axes.width; + if (d.align === "right") { + textPos -= d.padding * 2; + } + if (d.align === "left") { + textPos += d.padding * 2; + } + } + d.coords.text = {}; + d.coords.text[axis.indexOf("x") === 0 ? "y" : "x"] = textPos; + d.coords.text[axis] = vars[axis].scale.viz(d.position) + textPad; + d.transform = axis.indexOf("x") === 0 ? "rotate(-90," + d.coords.text.x + "," + d.coords.text.y + ")" : null; + textData.push(d); + } + } + } + lines = lineGroup.selectAll("line.d3plus_graph_" + axis + "line").data(lineData, function(d) { + return d.position; + }); + lines.enter().append("line").attr("class", "d3plus_graph_" + axis + "line").attr("opacity", 0).call(lineStyle, axis); + lines.transition().duration(vars.draw.timing).attr("opacity", 1).call(lineStyle, axis); + lines.exit().transition().duration(vars.draw.timing).attr("opacity", 0).remove(); + linetexts = lineGroup.selectAll("text.d3plus_graph_" + axis + "line_text").data(textData, function(d) { + return d.position; + }); + linetexts.enter().append("text").attr("class", "d3plus_graph_" + axis + "line_text").attr("id", function(d) { + var id; + id = d.position + ""; + id = id.replace("-", "neg"); + id = id.replace(".", "p"); + return "d3plus_graph_" + axis + "line_text_" + id; + }).attr("opacity", 0).call(lineFont, axis); + linetexts.text(function(d) { + return d.text; + }).transition().duration(vars.draw.timing).attr("opacity", 1).call(lineFont, axis); + linetexts.exit().transition().duration(vars.draw.timing).attr("opacity", 0).remove(); + rectStyle = function(rect) { + var getText; + getText = function(d) { + var id; + id = d.position + ""; + id = id.replace("-", "neg"); + id = id.replace(".", "p"); + return plane.select("text#d3plus_graph_" + d.axis + "line_text_" + id).node().getBBox(); + }; + return rect.attr("x", function(d) { + return getText(d).x - d.padding; + }).attr("y", function(d) { + return getText(d).y - d.padding; + }).attr("transform", function(d) { + return d.transform; + }).attr("width", function(d) { + return getText(d).width + (d.padding * 2); + }).attr("height", function(d) { + return getText(d).height + (d.padding * 2); + }).attr("fill", vars.axes.background.color !== "transparent" ? vars.axes.background.color : "white"); + }; + rectData = vars[axis].lines.font.background.value ? textData : []; + lineRects = lineGroup.selectAll("rect.d3plus_graph_" + axis + "line_rect").data(rectData, function(d) { + return d.position; + }); + lineRects.enter().insert("rect", "text.d3plus_graph_" + axis + "line_text").attr("class", "d3plus_graph_" + axis + "line_rect").attr("pointer-events", "none").attr("opacity", 0).call(rectStyle); + lineRects.transition().delay(vars.draw.timing).each("end", function(d) { + return d3.select(this).transition().duration(vars.draw.timing).attr("opacity", 1).call(rectStyle); + }); + lineRects.exit().transition().duration(vars.draw.timing).attr("opacity", 0).remove(); + } + } +}; + + +},{"../../../../../color/mix.coffee":46,"../../../../../object/validate.coffee":172,"../../../../../textwrap/textwrap.coffee":200}],320:[function(require,module,exports){ +var fetchValue, stringStrip, uniqueValues; + +fetchValue = require("../../../../core/fetch/value.coffee"); + +stringStrip = require("../../../../string/strip.js"); + +uniqueValues = require("../../../../util/uniques.coffee"); + +module.exports = function(vars, data, keys) { + var discrete, extras, key, opposite, serialized, ticks, timeAxis; + if (keys === void 0) { + keys = vars.id.nesting.slice(0, vars.depth.value + 1); + } else if (keys.constructor !== Array) { + keys = [keys]; + } + if (extras === void 0) { + extras = []; + } + if (!data) { + data = vars.data.viz; + } + discrete = vars[vars.axes.discrete]; + opposite = vars[vars.axes.opposite]; + timeAxis = discrete.value === vars.time.value; + if (timeAxis) { + ticks = vars.data.time.ticks; + key = vars.time.solo.value.length ? "solo" : "mute"; + if (vars.time[key].value.length) { + serialized = vars.time[key].value.slice().map(function(f) { + if (f.constructor !== Date) { + f = f + ""; + if (f.length === 4 && parseInt(f) + "" === f) { + f += "/01/01"; + } + f = new Date(f); + } + return +f; + }); + ticks = ticks.filter(function(f) { + if (key === "solo") { + return serialized.indexOf(+f) >= 0; + } else { + return serialized.indexOf(+f) < 0; + } + }); + } + } else if (discrete.ticks.values) { + ticks = discrete.ticks.values; + } else { + ticks = uniqueValues(data, discrete.value, fetchValue, vars); + } + return d3.nest().key(function(d) { + var id, j, len, return_id, val; + return_id = "nesting"; + for (j = 0, len = keys.length; j < len; j++) { + id = keys[j]; + val = fetchValue(vars, d, id); + if (val instanceof Array) { + val = val.join("_"); + } + return_id += "_" + stringStrip(val); + } + return return_id; + }).rollup(function(leaves) { + var availables, filler, i, j, k, len, len1, obj, ref, tester, tick, timeVar; + availables = uniqueValues(leaves, discrete.value, fetchValue, vars); + timeVar = availables.length && availables[0].constructor === Date; + if (timeVar) { + availables = availables.map(Number); + } + if (discrete.zerofill.value) { + if (discrete.scale.value === "log") { + if (opposite.scale.viz.domain().every(function(d) { + return d < 0; + })) { + filler = -1; + } else { + filler = 1; + } + } else { + filler = 0; + } + for (i = j = 0, len = ticks.length; j < len; i = ++j) { + tick = ticks[i]; + tester = timeAxis ? +tick : tick; + if (availables.indexOf(tester) < 0) { + obj = { + d3plus: {} + }; + ref = vars.id.nesting; + for (k = 0, len1 = ref.length; k < len1; k++) { + key = ref[k]; + if (key in leaves[0]) { + obj[key] = leaves[0][key]; + } + } + obj[discrete.value] = tick; + obj[opposite.value] = 0; + obj[opposite.value] = filler; + leaves.splice(i, 0, obj); + } + } + } + if (typeof leaves[0][discrete.value] === "string") { + return leaves; + } else { + return leaves.sort(function(a, b) { + var ad, ao, bd, bo, xsort; + ad = fetchValue(vars, a, discrete.value); + bd = fetchValue(vars, b, discrete.value); + xsort = ad - bd; + if (xsort) { + return xsort; + } + ao = fetchValue(vars, a, opposite.value); + bo = fetchValue(vars, b, opposite.value); + return ao - bo; + }); + } + }).entries(data); +}; + + +},{"../../../../core/fetch/value.coffee":67,"../../../../string/strip.js":175,"../../../../util/uniques.coffee":210}],321:[function(require,module,exports){ +var fetchValue; + +fetchValue = require("../../../../core/fetch/value.coffee"); + +module.exports = function(vars, data) { + var d, flip, i, j, len, len1, margin, neg, negativeData, offset, opposite, positiveData, scale, stack, stacked, v, val; + stacked = vars.axes.stacked || vars.axes.opposite; + flip = vars[stacked].scale.viz(0); + scale = vars[stacked].scale.value; + opposite = stacked === "x" ? "y" : "x"; + margin = stacked === "y" ? vars.axes.margin.viz.top : vars.axes.margin.viz.left; + offset = scale === "share" ? "expand" : "zero"; + stack = d3.layout.stack().values(function(d) { + return d.values || [d]; + }).offset(offset).x(function(d) { + return d.d3plus[opposite]; + }).y(function(d) { + return flip - vars[stacked].scale.viz(fetchValue(vars, d, vars[stacked].value)); + }).out(function(d, y0, y) { + var negative, value; + value = fetchValue(vars, d, vars[stacked].value); + negative = value < 0; + if (scale === "share") { + d.d3plus[stacked + "0"] = (1 - y0) * flip; + d.d3plus[stacked] = d.d3plus[stacked + "0"] - (y * flip); + } else { + d.d3plus[stacked + "0"] = flip; + if (vars.axes.stacked) { + d.d3plus[stacked + "0"] -= y0; + } + d.d3plus[stacked] = d.d3plus[stacked + "0"] - y; + } + d.d3plus[stacked] += margin; + return d.d3plus[stacked + "0"] += margin; + }); + positiveData = []; + negativeData = []; + for (i = 0, len = data.length; i < len; i++) { + d = data[i]; + val = fetchValue(vars, d, vars[stacked].value); + if (val instanceof Array) { + neg = true; + for (j = 0, len1 = val.length; j < len1; j++) { + v = val[j]; + if (v >= 0) { + neg = false; + break; + } + } + if (neg) { + negativeData.push(d); + } else { + positiveData.push(d); + } + } else { + if (val >= 0) { + positiveData.push(d); + } + if (val < 0) { + negativeData.push(d); + } + } + } + if (positiveData.length === 0 || negativeData.length === 0) { + return stack(data); + } else { + if (positiveData.length) { + positiveData = stack(positiveData); + } + if (negativeData.length) { + negativeData = stack(negativeData); + } + return positiveData.concat(negativeData); + } +}; + + +},{"../../../../core/fetch/value.coffee":67}],322:[function(require,module,exports){ +var fetchValue, graph, line, nest, sort, stack; + +fetchValue = require("../../core/fetch/value.coffee"); + +graph = require("./helpers/graph/draw.coffee"); + +nest = require("./helpers/graph/nest.coffee"); + +sort = require("../../array/sort.coffee"); + +stack = require("./helpers/graph/stack.coffee"); + +line = function(vars) { + var d, data, domains, i, j, len, len1, point, ref, xval, yval; + graph(vars, { + buffer: vars.axes.opposite, + mouse: true + }); + domains = vars.x.domain.viz.concat(vars.y.domain.viz); + if (domains.indexOf(void 0) >= 0) { + return []; + } + data = sort(vars.data.viz, null, null, null, vars); + for (i = 0, len = data.length; i < len; i++) { + point = data[i]; + ref = point.values; + for (j = 0, len1 = ref.length; j < len1; j++) { + d = ref[j]; + xval = fetchValue(vars, d, vars.x.value); + if (xval !== null) { + d.d3plus.x2 = false; + d.d3plus.x = vars.x.scale.viz(xval); + } else { + d.d3plus.x2 = true; + d.d3plus.x = vars.x2.scale.viz(fetchValue(vars, d, vars.x2.value)); + } + d.d3plus.x += vars.axes.margin.viz.left; + yval = fetchValue(vars, d, vars.y.value); + if (yval !== null) { + d.d3plus.y2 = false; + d.d3plus.y = vars.y.scale.viz(yval); + } else { + d.d3plus.y2 = true; + d.d3plus.y = vars.y2.scale.viz(fetchValue(vars, d, vars.y2.value)); + } + d.d3plus.y += vars.axes.margin.viz.top; + } + } + if (vars.axes.stacked) { + return stack(vars, data); + } else { + return data; + } +}; + +line.filter = function(vars, data) { + return nest(vars, data); +}; + +line.requirements = ["data", "x", "y"]; + +line.setup = function(vars) { + var axis; + if (!vars.axes.discrete) { + axis = vars.time.value === vars.y.value ? "y" : "x"; + vars.self[axis]({ + scale: "discrete" + }); + } +}; + +line.shapes = ["line"]; + +line.tooltip = "static"; + +module.exports = line; + + +},{"../../array/sort.coffee":34,"../../core/fetch/value.coffee":67,"./helpers/graph/draw.coffee":314,"./helpers/graph/nest.coffee":320,"./helpers/graph/stack.coffee":321}],323:[function(require,module,exports){ +var smallestGap = require("../../network/smallestGap.coffee"), + fetchValue = require("../../core/fetch/value.coffee"); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Network +//------------------------------------------------------------------------------ +var network = function(vars) { + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Use filtered lists if they are available + //---------------------------------------------------------------------------- + var nodes = vars.nodes.restricted || vars.nodes.value, + edges = vars.edges.restricted || vars.edges.value; + + var x_range = d3.extent(nodes,function(n){return n.x}), + y_range = d3.extent(nodes,function(n){return n.y}) + + var val_range = [ 1 , 1 ] + if (typeof vars.size.value === "number"){ + val_range = [vars.size.value, vars.size.value] + } + else if (vars.size.value){ + val_range = d3.extent(nodes, function(d){ + var val = fetchValue( vars , d , vars.size.value ) + return val === 0 ? null : val + }) + } + if (typeof val_range[0] == "undefined") val_range = [1,1] + + if (typeof vars.size.value === "number"){ + var max_size = vars.size.value; + var min_size = vars.size.value; + } + else { + + var max_size = smallestGap(nodes, {"accessor": function(n){ + return [n.x, n.y]; + }}); + + var limit = max_size/2; + + var overlap = vars.size.value ? vars.nodes.overlap : 0.4 + max_size = max_size * overlap; + + if (vars.edges.arrows.value) { + max_size = max_size * 0.5; + } + + if (val_range[0] === val_range[1]) { + var min_size = limit; + max_size = limit; + } + else { + + var width = (x_range[1]+max_size*1.1)-(x_range[0]-max_size*1.1), + height = (y_range[1]+max_size*1.1)-(y_range[0]-max_size*1.1), + aspect = width/height, + app = vars.width.viz/vars.height.viz; + + if ( app > aspect ) { + var scale = vars.height.viz/height; + } + else { + var scale = vars.width.viz/width; + } + var min_size = max_size * 0.25; + if ( min_size * scale < 2 ) { + min_size = 2/scale; + } + + } + } + + // Create size scale + var radius = vars.size.scale.value + .domain(val_range) + .range([min_size, max_size]) + + vars.zoom.bounds = [ [ x_range[0]-max_size*1.1 , y_range[0]-max_size*1.1 ] + , [ x_range[1]+max_size*1.1 , y_range[1]+max_size*1.1 ] ] + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Match nodes to data + //---------------------------------------------------------------------------- + var data = [], lookup = {} + nodes.forEach(function(n){ + + var d = vars.data.viz.filter(function(a){ + return a[vars.id.value] == n[vars.id.value] + })[0] + + var obj = d || {} + + obj[vars.id.value] = n[vars.id.value] + + obj.d3plus = {} + obj.d3plus.x = n.x + obj.d3plus.y = n.y + var val = fetchValue(vars,obj,vars.size.value) + obj.d3plus.r = val ? radius(val) : radius.range()[0] + lookup[obj[vars.id.value]] = { + "x": obj.d3plus.x, + "y": obj.d3plus.y, + "r": obj.d3plus.r + } + + data.push(obj) + }) + + data.sort(function(a,b){ + return b.d3plus.r - a.d3plus.r + }) + + edges.forEach(function(l,i){ + + if (l.d3plus) { + delete l.d3plus.spline + } + + l[vars.edges.source].d3plus = {} + var source = lookup[l[vars.edges.source][vars.id.value]] + if (source !== undefined) { + l[vars.edges.source].d3plus.r = source.r + l[vars.edges.source].d3plus.x = source.x + l[vars.edges.source].d3plus.y = source.y + } else { + delete l[vars.edges.source].d3plus; + } + + l[vars.edges.target].d3plus = {} + var target = lookup[l[vars.edges.target][vars.id.value]] + if (target !== undefined) { + l[vars.edges.target].d3plus.r = target.r + l[vars.edges.target].d3plus.x = target.x + l[vars.edges.target].d3plus.y = target.y + } else { + delete l[vars.edges.target].d3plus; + } + + }) + + return {"nodes": data, "edges": edges} + +} + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Visualization Settings and Helper Functions +//------------------------------------------------------------------------------ +network.nesting = false +network.requirements = ["nodes","edges"] +network.scale = 1.05 +network.shapes = [ "circle" , "square" , "donut" ] +network.tooltip = "static" +network.zoom = true + +module.exports = network + +},{"../../core/fetch/value.coffee":67,"../../network/smallestGap.coffee":168}],324:[function(require,module,exports){ +var fetchValue, shortestPath, uniqueValues, viz, + indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; + +shortestPath = require("../../network/shortestPath.coffee"); + +fetchValue = require("../../core/fetch/value.coffee"); + +uniqueValues = require("../../util/uniques.coffee"); + +viz = function(vars) { + var base, base1, base2, base3, col, colIndex, columnWidth, columns, edge, edgeInt, edges, i, id, j, k, l, labelSpace, lastDir, lastHop, len, len1, len2, len3, len4, len5, len6, len7, m, maxRadius, minRadius, n, newPath, next, nextDir, nextHop, nextIndex, node, o, p, path, pathInt, pathLookup, paths, prev, prevIndex, q, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, rowHeight, rows, size, sizeDomain, val, x, xDiff, y, yDomain; + edges = []; + pathLookup = {}; + pathLookup[vars.focus.value[0]] = 0; + pathLookup[vars.focus.value[1]] = 0; + paths = { + all: [[vars.focus.value[0]], [vars.focus.value[1]]] + }; + ref = viz.paths; + for (pathInt = j = 0, len = ref.length; j < len; pathInt = ++j) { + path = ref[pathInt]; + edges = edges.concat(path.edges); + lastHop = vars.focus.value[0]; + paths[pathInt] = [lastHop]; + ref1 = path.edges; + for (edgeInt = k = 0, len1 = ref1.length; k < len1; edgeInt = ++k) { + edge = ref1[edgeInt]; + edge[vars.edges.source] = vars.data.viz.filter(function(d) { + return edge[vars.edges.source][vars.id.value] === d[vars.id.value]; + })[0]; + edge[vars.edges.target] = vars.data.viz.filter(function(d) { + return edge[vars.edges.target][vars.id.value] === d[vars.id.value]; + })[0]; + nextDir = edge[vars.edges.source][vars.id.value] === lastHop ? "target" : "source"; + nextHop = edge[vars.edges[nextDir]][vars.id.value]; + if (pathLookup[nextHop] === void 0) { + pathLookup[nextHop] = pathInt; + } + paths[pathInt].push(nextHop); + lastHop = nextHop; + } + } + rows = 0; + for (pathInt in paths) { + path = paths[pathInt]; + if (pathInt !== "all") { + newPath = 0; + for (i = l = 0, len2 = path.length; l < len2; i = ++l) { + id = path[i]; + if ((i !== 0 && i !== (path.length - 1)) && pathLookup[id] === parseFloat(pathInt)) { + newPath = 1; + prev = path[i - 1]; + next = path[i + 1]; + prevIndex = null; + nextIndex = null; + ref2 = paths.all; + for (colIndex = m = 0, len3 = ref2.length; m < len3; colIndex = ++m) { + col = ref2[colIndex]; + if (indexOf.call(col, prev) >= 0) { + prevIndex = colIndex; + } + if (indexOf.call(col, next) >= 0) { + nextIndex = colIndex; + } + } + if (prevIndex !== null && nextIndex === null) { + if (prevIndex + 1 === paths.all.length - 1) { + paths.all.splice(prevIndex + 1, 0, [id]); + } else { + paths.all[prevIndex + 1].push(id); + } + } else if (nextIndex - prevIndex === 1) { + paths.all.splice(nextIndex, 0, [id]); + } else if (nextIndex - prevIndex > 1) { + paths.all[nextIndex - 1].push(id); + } + } + } + rows += newPath; + } + } + rowHeight = Math.floor(vars.height.viz / rows); + yDomain = []; + i = 0; + while (i < rows) { + if (i % 2 === 0) { + yDomain.push(i); + } else { + yDomain.unshift(i); + } + i++; + } + labelSpace = vars.size.value && !vars.small ? 30 : 0; + y = d3.scale.ordinal().domain(yDomain).range(d3.range(rowHeight / 2 - labelSpace, vars.height.viz + rowHeight / 2 - labelSpace, (vars.height.viz - rowHeight) / (rows - 1))); + columns = paths["all"].length; + columnWidth = Math.floor(vars.width.viz / columns); + x = d3.scale.linear().domain([0, columns - 1]).rangeRound([columnWidth / 2, vars.width.viz - columnWidth / 2]); + minRadius = 5; + maxRadius = d3.min([columnWidth, rowHeight - labelSpace]) * 0.4; + sizeDomain = d3.extent(vars.data.viz, function(node) { + var val; + val = fetchValue(vars, node, vars.size.value); + return val || 0; + }); + size = vars.size.scale.value.domain(sizeDomain).rangeRound([minRadius, maxRadius]); + ref3 = vars.data.viz; + for (n = 0, len4 = ref3.length; n < len4; n++) { + node = ref3[n]; + if (node.d3plus == null) { + node.d3plus = {}; + } + ref4 = paths["all"]; + for (colIndex = o = 0, len5 = ref4.length; o < len5; colIndex = ++o) { + col = ref4[colIndex]; + if (ref5 = node[vars.id.value], indexOf.call(col, ref5) >= 0) { + node.d3plus.x = x(colIndex); + } + } + node.d3plus.y = y(pathLookup[node[vars.id.value]]); + if (vars.size.value) { + val = fetchValue(vars, node, vars.size.value); + node.d3plus.r = val ? size(val) : minRadius; + } else { + node.d3plus.r = maxRadius; + } + if (node.d3plus.r < columnWidth * 0.1 && !vars.small) { + node.d3plus.label = { + x: 0, + y: node.d3plus.r + vars.labels.padding * 2, + w: columnWidth * 0.6, + h: labelSpace + maxRadius - node.d3plus.r, + resize: false + }; + } else { + delete node.d3plus.label; + } + } + ref6 = viz.paths; + for (pathInt = p = 0, len6 = ref6.length; p < len6; pathInt = ++p) { + path = ref6[pathInt]; + lastHop = vars.focus.value[0]; + ref7 = path.edges; + for (edgeInt = q = 0, len7 = ref7.length; q < len7; edgeInt = ++q) { + edge = ref7[edgeInt]; + nextDir = edge[vars.edges.source][vars.id.value] === lastHop ? "target" : "source"; + lastDir = nextDir === "target" ? "source" : "target"; + nextHop = edge[vars.edges[nextDir]][vars.id.value]; + if (pathLookup[lastHop] !== pathLookup[nextHop]) { + edge.d3plus = { + spline: true + }; + if ((base = edge[vars.edges.source]).d3plus == null) { + base.d3plus = {}; + } + if ((base1 = edge[vars.edges.source].d3plus).edges == null) { + base1.edges = {}; + } + if ((base2 = edge[vars.edges.target]).d3plus == null) { + base2.d3plus = {}; + } + if ((base3 = edge[vars.edges.target].d3plus).edges == null) { + base3.edges = {}; + } + xDiff = edge[nextDir].d3plus.x - edge[lastDir].d3plus.x; + edge[lastDir].d3plus.edges[edge[nextDir][vars.id.value]] = { + angle: Math.PI, + radius: columnWidth / 2 + }; + edge[nextDir].d3plus.edges[edge[lastDir][vars.id.value]] = { + angle: 0, + radius: columnWidth / 2, + offset: xDiff - columnWidth + }; + } else { + delete edge.d3plus; + } + lastHop = nextHop; + } + } + return { + nodes: vars.data.viz, + edges: edges + }; +}; + +viz.filter = function(vars, data) { + var added, d, edge, edges, id, ids, j, k, l, len, len1, len2, obj, path, ref, ref1, returnData, source, target; + edges = vars.edges.filtered || vars.edges.value; + viz.paths = shortestPath(edges, vars.focus.value[0], { + target: vars.focus.value[1], + distance: vars.edges.size.value || void 0, + nodeid: vars.id.value, + startpoint: vars.edges.source, + endpoint: vars.edges.target, + K: vars.edges.limit.value || 5 + }); + viz.nodes = []; + added = []; + ref = viz.paths; + for (j = 0, len = ref.length; j < len; j++) { + path = ref[j]; + ref1 = path.edges; + for (k = 0, len1 = ref1.length; k < len1; k++) { + edge = ref1[k]; + source = edge[vars.edges.source]; + target = edge[vars.edges.target]; + if (added.indexOf(source[vars.id.value]) < 0) { + viz.nodes.push(source); + added.push(source[vars.id.value]); + } + if (added.indexOf(target[vars.id.value]) < 0) { + viz.nodes.push(target); + added.push(target[vars.id.value]); + } + } + } + ids = uniqueValues(viz.nodes, vars.id.value, fetchValue, vars); + returnData = []; + for (l = 0, len2 = ids.length; l < len2; l++) { + id = ids[l]; + d = data.filter(function(d) { + return d[vars.id.value] === id; + }); + if (!d[0]) { + obj = { + d3plus: {} + }; + obj[vars.id.value] = id; + returnData.push(obj); + } else { + returnData.push(d[0]); + } + } + return returnData; +}; + +viz.nesting = false; + +viz.requirements = [ + function(vars) { + return { + status: vars.focus.value.length === 2, + text: vars.format.locale.value.method.focus + " x 2" + }; + }, "edges" +]; + +viz.scale = 1; + +viz.shapes = ["circle", "square", "donut"]; + +viz.tooltip = "static"; + +module.exports = viz; + + +},{"../../core/fetch/value.coffee":67,"../../network/shortestPath.coffee":167,"../../util/uniques.coffee":210}],325:[function(require,module,exports){ +var comparator, dataThreshold, groupData, pie; + +comparator = require("../../array/comparator.coffee"); + +dataThreshold = require("../../core/data/threshold.js"); + +groupData = require("../../core/data/group.coffee"); + +pie = function(vars) { + var d, groupedData, i, item, len, pieData, pieLayout, radius, returnData; + pieLayout = d3.layout.pie().value(function(d) { + return d.value; + }).sort(function(a, b) { + if (vars.order.value) { + return comparator(a.d3plus, b.d3plus, [vars.order.value], vars.order.sort.value, [], vars); + } else if (vars.id.nesting.length > 1) { + return comparator(a.d3plus, b.d3plus, vars.id.nesting.concat([vars.size.value]), void 0, [], vars); + } else { + return comparator(a.d3plus, b.d3plus, [vars.size.value], "desc", [], vars); + } + }); + groupedData = groupData(vars, vars.data.viz, []); + pieData = pieLayout(groupedData); + returnData = []; + radius = d3.min([vars.width.viz, vars.height.viz]) / 2 - vars.labels.padding * 2; + for (i = 0, len = pieData.length; i < len; i++) { + d = pieData[i]; + item = d.data.d3plus; + item.d3plus.startAngle = d.startAngle; + item.d3plus.endAngle = d.endAngle; + item.d3plus.r = radius; + item.d3plus.x = vars.width.viz / 2; + item.d3plus.y = vars.height.viz / 2; + item.d3plus.share = (d.endAngle - d.startAngle) / (Math.PI * 2); + returnData.push(item); + } + return returnData; +}; + +pie.filter = dataThreshold; + +pie.requirements = ["data", "size"]; + +pie.shapes = ["arc"]; + +pie.threshold = function(vars) { + return (40 * 40) / (vars.width.viz * vars.height.viz); +}; + +module.exports = pie; + + +},{"../../array/comparator.coffee":32,"../../core/data/group.coffee":57,"../../core/data/threshold.js":61}],326:[function(require,module,exports){ +var buckets, comparator, dataThreshold, fetchText, fetchValue, fontSizes, offset, radar, sort, textwrap, uniques; + +comparator = require("../../array/comparator.coffee"); + +sort = require("../../array/sort.coffee"); + +dataThreshold = require("../../core/data/threshold.js"); + +fetchText = require("../../core/fetch/text.js"); + +fetchValue = require("../../core/fetch/value.coffee"); + +fontSizes = require("../../font/sizes.coffee"); + +offset = require("../../geom/offset.coffee"); + +textwrap = require("../../textwrap/textwrap.coffee"); + +buckets = require("../../util/buckets.coffee"); + +uniques = require("../../util/uniques.coffee"); + +radar = function(vars) { + var a, a2, anchor, angle, buffer, c, center, children, d, data, first, grid, gridStyle, i, idIndex, ids, intervals, j, k, l, labelData, labelGroup, labelHeight, labelIndex, labelStyle, labelWidth, labels, len, len1, len2, len3, m, maxData, maxRadius, n, nextDepth, nextLevel, o, ov, radius, ref, ref1, righty, ringData, ringStyle, rings, second, sizes, text, textStyle, top, total, x, y; + data = vars.data.viz; + nextDepth = vars.depth.value + 1; + nextLevel = vars.id.nesting[nextDepth]; + children = (function() { + var j, len, results; + results = []; + for (j = 0, len = data.length; j < len; j++) { + d = data[j]; + results.push(d[nextLevel]); + } + return results; + })(); + total = (function() { + var j, len, results; + results = []; + for (j = 0, len = data.length; j < len; j++) { + d = data[j]; + results.push(uniques(data, nextLevel, fetchValue, vars, nextDepth)); + } + return results; + })(); + total = uniques(d3.merge(total)).length; + angle = Math.PI * 2 / total; + maxRadius = d3.min([vars.width.viz, vars.height.viz]) / 2; + labelHeight = 0; + labelWidth = 0; + labels = (function() { + var j, len, results; + results = []; + for (j = 0, len = children.length; j < len; j++) { + c = children[j]; + results.push(fetchText(vars, c, nextDepth)[0]); + } + return results; + })(); + labels = uniques(d3.merge(labels)); + if (vars.labels.value) { + first = offset(Math.PI / 2, maxRadius); + second = offset(angle + Math.PI / 2, maxRadius); + labelHeight = (first.x - second.x) - vars.labels.padding * 2; + textStyle = { + "fill": vars.x.ticks.font.color, + "font-family": vars.x.ticks.font.family.value, + "font-weight": vars.x.ticks.font.weight, + "font-size": vars.x.ticks.font.size + "px" + }; + sizes = fontSizes(labels, textStyle, { + mod: function(elem) { + return textwrap().container(d3.select(elem)).width(vars.height.viz / 8).height(labelHeight).draw(); + } + }); + labelWidth = d3.max(sizes, function(d) { + return d.width; + }); + maxRadius -= labelWidth; + maxRadius -= vars.labels.padding * 2; + } + maxData = (function() { + var j, len, results; + results = []; + for (j = 0, len = children.length; j < len; j++) { + c = children[j]; + results.push((function() { + var k, len1, results1; + results1 = []; + for (k = 0, len1 = c.length; k < len1; k++) { + d = c[k]; + results1.push(fetchValue(vars, d, vars.size.value)); + } + return results1; + })()); + } + return results; + })(); + maxData = d3.max(d3.merge(maxData)); + radius = d3.scale.linear().domain([0, maxData]).range([0, maxRadius]); + ids = (function() { + var j, len, results; + results = []; + for (j = 0, len = children.length; j < len; j++) { + c = children[j]; + results.push(fetchValue(vars, c, nextLevel)); + } + return results; + })(); + ids = uniques(d3.merge(ids)); + idIndex = d3.scale.ordinal().domain(ids).range(d3.range(0, ids.length)); + for (j = 0, len = data.length; j < len; j++) { + d = data[j]; + d.d3plus.x = vars.width.viz / 2 + vars.margin.top; + d.d3plus.y = vars.height.viz / 2 + vars.margin.left; + ref = d[nextLevel]; + for (i = k = 0, len1 = ref.length; k < len1; i = ++k) { + a = ref[i]; + if (!a.d3plus) { + a.d3plus = {}; + } + a.d3plus.r = radius(fetchValue(vars, a, vars.size.value)); + a.d3plus.a = idIndex(fetchValue(vars, a, nextLevel)) * angle; + } + } + intervals = 1; + ref1 = [10, 5, 4, 2]; + for (m = 0, len2 = ref1.length; m < len2; m++) { + i = ref1[m]; + if (maxRadius / i >= 20) { + intervals = i; + break; + } + } + ringData = buckets([maxRadius / intervals, maxRadius], intervals - 1).reverse(); + if (ringData.length === intervals) { + ringData.shift(); + } + rings = vars.group.selectAll(".d3plus_radar_rings").data(ringData, function(d, i) { + return i; + }); + ringStyle = function(ring) { + return ring.attr("fill", function(d, i) { + if (i === 0) { + return vars.axes.background.color; + } else { + return "transparent"; + } + }).attr("cx", vars.width.viz / 2 + vars.margin.top).attr("cy", vars.height.viz / 2 + vars.margin.left).attr("stroke", vars.x.grid.value ? vars.x.grid.color : "transparent"); + }; + rings.enter().append("circle").attr("class", "d3plus_radar_rings").call(ringStyle).attr("r", 0); + rings.transition().duration(vars.draw.timing).call(ringStyle).attr("r", function(d) { + return d; + }); + rings.exit().transition().duration(vars.draw.timing).attr("opacity", 0).remove(); + labelIndex = d3.scale.ordinal().domain(labels).range(d3.range(0, labels.length)); + labelData = []; + for (n = 0, len3 = labels.length; n < len3; n++) { + l = labels[n]; + a2 = (angle * labelIndex(l)) - Math.PI / 2; + a = a2 * (180 / Math.PI); + if (a < -90 || a > 90) { + a = a - 180; + buffer = -(maxRadius + vars.labels.padding * 2 + labelWidth); + anchor = "end"; + } else { + buffer = maxRadius + vars.labels.padding * 2; + anchor = "start"; + } + top = a2 < 0 || a2 > Math.PI; + righty = a2 < Math.PI / 2; + ov = maxRadius; + if (vars.labels.value) { + ov += vars.labels.padding; + } + o = offset(a2, ov); + x = o.x; + y = o.y; + if (!righty) { + x -= labelWidth; + } + if (top) { + y -= labelHeight; + } + center = [0, Math.PI].indexOf(angle * labelIndex(l)) >= 0; + if (center) { + x -= labelWidth / 2; + } + labelData.push({ + "text": l, + "angle": a, + "x": buffer, + "anchor": anchor, + "offset": o + }); + } + labelGroup = vars.group.selectAll("g.d3plus_radar_label_group").data([0]); + labelGroup.enter().append("g").attr("class", "d3plus_radar_label_group").attr("transform", "translate(" + vars.width.viz / 2 + "," + vars.height.viz / 2 + ")"); + labelGroup.transition().duration(vars.draw.timing).attr("transform", "translate(" + vars.width.viz / 2 + "," + vars.height.viz / 2 + ")"); + text = labelGroup.selectAll(".d3plus_radar_labels").data((vars.labels.value ? labelData : []), function(d, i) { + return i; + }); + labelStyle = function(label) { + return label.attr(textStyle).each(function(l, i) { + return textwrap().container(d3.select(this)).height(labelHeight).width(labelWidth).align(l.anchor).text(l.text).padding(0).valign("middle").x(l.x).y(-labelHeight / 2).draw(); + }).attr("transform", function(t) { + var translate; + translate = d3.select(this).attr("transform") || ""; + if (translate.length) { + translate = translate.split(")").slice(-3).join(")"); + } + return "rotate(" + t.angle + ")" + translate; + }); + }; + text.call(labelStyle); + text.enter().append("text").attr("class", "d3plus_radar_labels").attr("opacity", 0).call(labelStyle).transition().duration(vars.draw.timing).attr("opacity", 1); + text.exit().transition().duration(vars.draw.timing).attr("opacity", 0).remove(); + grid = vars.group.selectAll(".d3plus_radar_lines").data(labelData, function(d, i) { + return i; + }); + gridStyle = function(grid) { + return grid.attr("stroke", vars.x.grid.color).attr("x1", vars.width.viz / 2 + vars.margin.left).attr("y1", vars.height.viz / 2 + vars.margin.top); + }; + grid.enter().append("line").attr("class", "d3plus_radar_lines").call(gridStyle).attr("x2", vars.width.viz / 2 + vars.margin.left).attr("y2", vars.height.viz / 2 + vars.margin.top); + grid.transition().duration(vars.draw.timing).call(gridStyle).attr("x2", function(d) { + return vars.width.viz / 2 + vars.margin.left + d.offset.x; + }).attr("y2", function(d) { + return vars.height.viz / 2 + vars.margin.top + d.offset.y; + }); + grid.exit().transition().duration(vars.draw.timing).attr("opacity", 0).remove(); + vars.mouse.viz = { + click: false + }; + return data; +}; + +radar.requirements = ["data", "size"]; + +radar.shapes = ["radial"]; + +module.exports = radar; + + +},{"../../array/comparator.coffee":32,"../../array/sort.coffee":34,"../../core/data/threshold.js":61,"../../core/fetch/text.js":66,"../../core/fetch/value.coffee":67,"../../font/sizes.coffee":102,"../../geom/offset.coffee":161,"../../textwrap/textwrap.coffee":200,"../../util/buckets.coffee":204,"../../util/uniques.coffee":210}],327:[function(require,module,exports){ +var arraySort = require("../../array/sort.coffee"), + events = require("../../client/pointer.coffee"), + fetchValue = require("../../core/fetch/value.coffee"), + fetchColor = require("../../core/fetch/color.coffee"), + legible = require("../../color/legible.coffee"), + removeTooltip = require("../../tooltip/remove.coffee"), + smallestGap = require("../../network/smallestGap.coffee"), + textColor = require("../../color/text.coffee"), + uniqueValues = require("../../util/uniques.coffee") + +var rings = function(vars) { + + var radius = d3.min([vars.height.viz,vars.width.viz])/2 + , ring_width = vars.small || !vars.labels.value + ? (radius-vars.labels.padding*2)/2 : radius/3 + , primaryRing = vars.small || !vars.labels.value + ? ring_width*1.4 : ring_width + , secondaryRing = ring_width*2 + , edges = [] + , nodes = [] + + var center = vars.data.viz.filter(function(d){ + return d[vars.id.value] === vars.focus.value[0] + })[0] + + if ( !center ) { + center = { "d3plus" : {} } + center[vars.id.value] = vars.focus.value[0] + } + + center.d3plus.x = vars.width.viz/2 + center.d3plus.y = vars.height.viz/2 + center.d3plus.r = primaryRing*.65 + + var primaries = [], claimed = [vars.focus.value[0]] + vars.edges.connections(vars.focus.value[0],vars.id.value).forEach(function(edge){ + + var c = edge[vars.edges.source][vars.id.value] == vars.focus.value[0] ? edge[vars.edges.target] : edge[vars.edges.source] + var n = vars.data.viz.filter(function(d){ + return d[vars.id.value] === c[vars.id.value] + })[0] + + if ( !n ) { + n = { "d3plus" : {} } + n[vars.id.value] = c[vars.id.value] + } + + n.d3plus.edges = vars.edges.connections(n[vars.id.value],vars.id.value).filter(function(c){ + return c[vars.edges.source][vars.id.value] != vars.focus.value[0] && c[vars.edges.target][vars.id.value] != vars.focus.value[0] + }) + n.d3plus.edge = edge + claimed.push(n[vars.id.value]) + primaries.push(n) + + }) + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Sort primary nodes by children (smallest to largest) and then by sort + // order. + //-------------------------------------------------------------------------- + var sort = vars.order.value || vars.color.value + || vars.size.value || vars.id.value + + primaries.sort(function(a,b){ + + var lengthdiff = a.d3plus.edges.length - b.d3plus.edges.length + + if ( lengthdiff ) { + + return lengthdiff + + } + else { + + return arraySort( [a,b] , sort , vars.order.sort.value + , vars.color.value || [] , vars) + + } + + }) + + if (typeof vars.edges.limit.value == "number") { + primaries = primaries.slice(0,vars.edges.limit.value) + } + else if (typeof vars.edges.limit.value == "function") { + primaries = vars.edges.limit.value(primaries) + } + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Check for similar children and give preference to nodes with less + // overall children. + //---------------------------------------------------------------------------- + var secondaries = [], total = 0 + primaries.forEach(function(p){ + + var primaryId = p[vars.id.value] + + p.d3plus.edges = p.d3plus.edges.filter(function(c){ + + var source = c[vars.edges.source][vars.id.value] + , target = c[vars.edges.target][vars.id.value] + return (claimed.indexOf(source) < 0 && target == primaryId) + || (claimed.indexOf(target) < 0 && source == primaryId) + + }) + + total += p.d3plus.edges.length || 1 + + p.d3plus.edges.forEach(function(c){ + + var source = c[vars.edges.source] + , target = c[vars.edges.target] + var claim = target[vars.id.value] == primaryId ? source : target + claimed.push(claim[vars.id.value]) + + }) + }) + + arraySort( primaries , sort , vars.order.sort.value + , vars.color.value || [] , vars) + + var offset = 0, + radian = Math.PI*2, + start = 0 + + primaries.forEach(function(p,i){ + + var children = p.d3plus.edges.length || 1, + space = (radian/total)*children + + if (i == 0) { + start = angle + offset -= space/2 + } + + var angle = offset+(space/2) + angle -= radian/4 + + p.d3plus.radians = angle + p.d3plus.x = vars.width.viz/2 + (primaryRing * Math.cos(angle)) + p.d3plus.y = vars.height.viz/2 + (primaryRing * Math.sin(angle)) + + offset += space + p.d3plus.edges.sort(function(a,b){ + + var a = a[vars.edges.source][vars.id.value] == p[vars.id.value] + ? a[vars.edges.target] : a[vars.edges.source] + , b = b[vars.edges.source][vars.id.value] == p[vars.id.value] + ? b[vars.edges.target] : b[vars.edges.source] + + return arraySort( [a,b] , sort , vars.order.sort.value + , vars.color.value || [] , vars) + + }) + + p.d3plus.edges.forEach(function(edge,i){ + + var c = edge[vars.edges.source][vars.id.value] == p[vars.id.value] + ? edge[vars.edges.target] : edge[vars.edges.source] + , s = radian/total + + var d = vars.data.viz.filter(function(a){ + return a[vars.id.value] === c[vars.id.value] + })[0] + + if ( !d ) { + d = { "d3plus" : {} } + d[vars.id.value] = c[vars.id.value] + } + + a = (angle-(s*children/2)+(s/2))+((s)*i) + d.d3plus.radians = a + d.d3plus.x = vars.width.viz/2 + ((secondaryRing) * Math.cos(a)) + d.d3plus.y = vars.height.viz/2 + ((secondaryRing) * Math.sin(a)) + secondaries.push(d) + }) + + }) + + var primaryDistance = smallestGap(primaries,{"accessor": function(n){ + return [n.d3plus.x, n.d3plus.y] + }}) + , secondaryDistance = smallestGap(secondaries,{"accessor": function(n){ + return [n.d3plus.x, n.d3plus.y] + }}) + + if (!primaryDistance) { + primaryDistance = ring_width/2 + } + + if (!secondaryDistance) { + secondaryDistance = ring_width/4 + } + + if (primaryDistance/2 - 4 < 8) { + var primaryMax = d3.min([primaryDistance/2,8]) + } + else { + var primaryMax = primaryDistance/2 - 4 + } + + if (secondaryDistance/2 - 4 < 4) { + var secondaryMax = d3.min([secondaryDistance/2,4]) + } + else { + var secondaryMax = secondaryDistance/2 - 4 + } + + if (secondaryMax > ring_width/10) { + secondaryMax = ring_width/10 + } + + if (secondaryMax > primaryMax && secondaryMax > 10) { + secondaryMax = primaryMax*.75 + } + if (primaryMax > secondaryMax*1.5) { + primaryMax = secondaryMax*1.5 + } + + primaryMax = Math.floor(primaryMax) + secondaryMax = Math.floor(secondaryMax) + + var ids = uniqueValues(primaries, vars.id.value, fetchValue, vars) + ids = ids.concat(uniqueValues(secondaries, vars.id.value, fetchValue, vars)) + ids.push(vars.focus.value[0]) + + var data = vars.data.viz.filter(function(d){ + return ids.indexOf(d[vars.id.value]) >= 0 + }) + + if (vars.size.value) { + + var domain = d3.extent(data,function(d){ + return fetchValue(vars,d,vars.size.value) + }) + + if (domain[0] == domain[1]) { + domain[0] = 0 + } + + var radius = d3.scale.linear() + .domain(domain) + .rangeRound([3,d3.min([primaryMax,secondaryMax])]) + + var val = fetchValue(vars,center,vars.size.value) + center.d3plus.r = radius(val) + + } + else { + + var radius = d3.scale.linear() + .domain([1,2]) + .rangeRound([primaryMax,secondaryMax]) + + + if (vars.edges.label) { + center.d3plus.r = radius(1)*1.5 + } + + } + + secondaries.forEach(function(s){ + s.d3plus.ring = 2 + var val = vars.size.value ? fetchValue(vars,s,vars.size.value) : 2 + s.d3plus.r = radius(val) + }) + + primaries.forEach(function(p){ + p.d3plus.ring = 1 + var val = vars.size.value ? fetchValue(vars,p,vars.size.value) : 1 + p.d3plus.r = radius(val) + }) + + nodes = [center].concat(primaries).concat(secondaries) + + primaries.forEach(function(p,i){ + + var check = [vars.edges.source,vars.edges.target] + , edge = p.d3plus.edge + + check.forEach(function(node){ + + edge[node] = nodes.filter(function(n){ + return n[vars.id.value] == edge[node][vars.id.value] + })[0] + + }) + + delete edge.d3plus + edges.push(edge) + + vars.edges.connections(p[vars.id.value],vars.id.value).forEach(function(edge){ + + var c = edge[vars.edges.source][vars.id.value] == p[vars.id.value] + ? edge[vars.edges.target] : edge[vars.edges.source] + + if (c[vars.id.value] != center[vars.id.value]) { + + var target = secondaries.filter(function(s){ + return s[vars.id.value] == c[vars.id.value] + })[0] + + if (!target) { + var r = primaryRing + target = primaries.filter(function(s){ + return s[vars.id.value] == c[vars.id.value] + })[0] + } + else { + var r = secondaryRing + } + + if (target) { + + edge.d3plus = { + "spline": true, + "translate": { + "x": vars.width.viz/2, + "y": vars.height.viz/2 + } + } + + var check = [vars.edges.source,vars.edges.target] + + check.forEach(function(node,i){ + + edge[node] = nodes.filter(function(n){ + return n[vars.id.value] == edge[node][vars.id.value] + })[0] + + if (edge[node].d3plus.edges === undefined) edge[node].d3plus.edges = {} + + var oppID = i === 0 ? edge[vars.edges.target][vars.id.value] : edge[vars.edges.source][vars.id.value] + + if (edge[node][vars.id.value] == p[vars.id.value]) { + + edge[node].d3plus.edges[oppID] = { + "angle": p.d3plus.radians + Math.PI, + "radius": ring_width/2 + } + + } + else { + + edge[node].d3plus.edges[oppID] = { + "angle": target.d3plus.radians, + "radius": ring_width/2 + } + + } + }) + + edges.push(edge) + + } + + } + + }) + + }) + + var labelColor = false; + if (vars.background.value && + ["transparent", "none"].indexOf(vars.background.value) < 0 && + d3.hsl(vars.background.value).l < 0.5) { + labelColor = textColor(vars.background.value); + } + + nodes.forEach(function(n) { + + if (!vars.small && vars.labels.value) { + + if (n[vars.id.value] != vars.focus.value[0]) { + + n.d3plus.rotate = n.d3plus.radians*(180/Math.PI) + + var angle = n.d3plus.rotate, + width = ring_width-(vars.labels.padding*3)-n.d3plus.r + + if (angle < -90 || angle > 90) { + angle = angle-180 + var buffer = -(n.d3plus.r+width/2+vars.labels.padding), + anchor = "end" + } + else { + var buffer = n.d3plus.r+width/2+vars.labels.padding, + anchor = "start" + } + + var background = primaries.indexOf(n) >= 0 ? true : false + + var height = n.d3plus.ring == 1 ? primaryDistance : secondaryDistance + + n.d3plus.label = { + "x": buffer, + "y": 0, + "w": width, + "h": height, + "angle": angle, + "anchor": anchor, + "valign": "center", + "color": labelColor || legible(fetchColor(vars,n)), + "resize": [8, vars.labels.font.size], + "background": background, + "mouse": true + } + + } + else if (vars.size.value || vars.edges.label) { + + var height = primaryRing-n.d3plus.r*2-vars.labels.padding*2 + + n.d3plus.label = { + "x": 0, + "y": n.d3plus.r+height/2, + "w": primaryRing, + "h": height, + "color": labelColor || legible(fetchColor(vars,n)), + "resize": [10,40], + "background": true, + "mouse": true + } + + } + else { + delete n.d3plus.rotate + delete n.d3plus.label + } + + } + else { + delete n.d3plus.rotate + delete n.d3plus.label + } + + }) + + vars.mouse.viz = {}; + vars.mouse.viz[events.click] = function(d) { + if (d[vars.id.value] != vars.focus.value[0]) { + removeTooltip(vars.type.value); + var old_focus = vars.focus.value[0]; + vars.history.states.push(function(){ + vars.self.focus(old_focus).draw(); + }) + vars.self.focus(d[vars.id.value]).draw(); + } + } + + return {"edges": edges, "nodes": nodes, "data": data} + +}; + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Visualization Settings and Helper Functions +//------------------------------------------------------------------------------ +rings.filter = function( vars , data ) { + + var primaries = vars.edges.connections(vars.focus.value[0],vars.id.value,true) + , secondaries = [] + + primaries.forEach(function(p){ + secondaries = secondaries.concat(vars.edges.connections(p[vars.id.value],vars.id.value,true)) + }) + + var connections = primaries.concat(secondaries) + , ids = uniqueValues(connections, vars.id.value, fetchValue, vars) + , returnData = [] + + ids.forEach(function(id){ + + var d = data.filter(function(d){ + return d[vars.id.value] == id + })[0] + + if ( !d ) { + var obj = {"d3plus": {}} + obj[vars.id.value] = id + returnData.push(obj) + } + else { + returnData.push(d) + } + + }) + + return returnData + +} +rings.nesting = false +rings.scale = 1 +rings.shapes = [ "circle" , "square" , "donut" ] +rings.requirements = [ "edges" , "focus" ] +rings.tooltip = "static" + +module.exports = rings + +},{"../../array/sort.coffee":34,"../../client/pointer.coffee":38,"../../color/legible.coffee":44,"../../color/text.coffee":50,"../../core/fetch/color.coffee":63,"../../core/fetch/value.coffee":67,"../../network/smallestGap.coffee":168,"../../tooltip/remove.coffee":203,"../../util/uniques.coffee":210}],328:[function(require,module,exports){ +var d3sankey, events, removeTooltip, sankey, uniques; + +d3sankey = require("./sankey.js"); + +events = require("../../client/pointer.coffee"); + +removeTooltip = require("../../tooltip/remove.coffee"); + +uniques = require("../../util/uniques.coffee"); + +sankey = function(vars) { + var d, e, edges, focus, i, j, layout, len, len1, n, nodes, padding, placed, returnData, size; + focus = vars.focus.value[0]; + padding = vars.data.stroke.width * 2; + size = vars.size.value.constructor === Number ? vars.size.value : 20; + edges = vars.edges.connections(focus, vars.id.value).filter(function(e) { + return e[vars.edges.source][vars.id.value] !== focus || e[vars.edges.target][vars.id.value] !== focus; + }); + nodes = []; + placed = []; + edges = edges.map(function(e) { + var s, t; + if (e[vars.edges.target][vars.id.value] === focus) { + s = { + id: "left_" + e[vars.edges.source][vars.id.value], + dupe: "left", + data: e[vars.edges.source], + value: e[vars.edges.strength.value] + }; + t = e[vars.edges.target]; + } else { + s = e[vars.edges.source]; + t = { + id: "right_" + e[vars.edges.target][vars.id.value], + dupe: "right", + data: e[vars.edges.target], + value: e[vars.edges.strength.value] + }; + } + if (placed.indexOf(s.id) < 0) { + nodes.push(s); + } + if (placed.indexOf(t.id) < 0) { + nodes.push(t); + } + placed.push(s.id); + placed.push(t.id); + return { + source: s, + target: t, + value: e[vars.edges.strength.value] || 1 + }; + }); + layout = d3sankey().nodeWidth(size).nodePadding(vars.data.padding.value).size([vars.width.viz - padding * 2, vars.height.viz - padding * 2]).nodes(nodes).links(edges).layout(2); + returnData = []; + for (i = 0, len = nodes.length; i < len; i++) { + n = nodes[i]; + d = n.data || n; + d = { + id: d[vars.id.value] + }; + d.d3plus = { + x: n.x + n.dx / 2 + padding, + y: n.y + n.dy / 2 + padding, + width: n.dx, + height: n.dy, + suffix: n.dupe + }; + if (d.id !== focus) { + d[vars.edges.strength.value] = n.value; + } + returnData.push(d); + } + vars.edges.path = layout.link(); + for (j = 0, len1 = edges.length; j < len1; j++) { + e = edges[j]; + e.d3plus = { + x: padding, + y: padding + }; + } + vars.mouse.viz = {}; + vars.mouse.viz[events.click] = function(d) { + var old_focus; + if (d[vars.id.value] !== vars.focus.value[0]) { + removeTooltip(vars.type.value); + old_focus = vars.focus.value[0]; + vars.history.states.push(function() { + return vars.self.focus(old_focus).draw(); + }); + return vars.self.focus(d[vars.id.value]).draw(); + } + }; + return { + nodes: returnData, + edges: edges + }; +}; + +sankey.requirements = ["edges", "focus", "nodes"]; + +sankey.shapes = ["square"]; + +module.exports = sankey; + + +},{"../../client/pointer.coffee":38,"../../tooltip/remove.coffee":203,"../../util/uniques.coffee":210,"./sankey.js":329}],329:[function(require,module,exports){ +module.exports = function() { + var sankey = {}, + nodeWidth = 24, + nodePadding = 8, + size = [1, 1], + nodes = [], + links = []; + + sankey.nodeWidth = function(_) { + if (!arguments.length) return nodeWidth; + nodeWidth = +_; + return sankey; + }; + + sankey.nodePadding = function(_) { + if (!arguments.length) return nodePadding; + nodePadding = +_; + return sankey; + }; + + sankey.nodes = function(_) { + if (!arguments.length) return nodes; + nodes = _; + return sankey; + }; + + sankey.links = function(_) { + if (!arguments.length) return links; + links = _; + return sankey; + }; + + sankey.size = function(_) { + if (!arguments.length) return size; + size = _; + return sankey; + }; + + sankey.layout = function(iterations) { + computeNodeLinks(); + computeNodeValues(); + computeNodeBreadths(); + computeNodeDepths(iterations); + computeLinkDepths(); + return sankey; + }; + + sankey.relayout = function() { + computeLinkDepths(); + return sankey; + }; + + sankey.link = function() { + var curvature = .5; + + function link(d) { + var x0 = d.source.x + d.source.dx, + x1 = d.target.x, + xi = d3.interpolateNumber(x0, x1), + x2 = xi(curvature), + x3 = xi(1 - curvature), + y0 = d.source.y + d.sy + d.dy / 2, + y1 = d.target.y + d.ty + d.dy / 2; + return "M" + x0 + "," + y0 + + "C" + x2 + "," + y0 + + " " + x3 + "," + y1 + + " " + x1 + "," + y1; + } + + link.curvature = function(_) { + if (!arguments.length) return curvature; + curvature = +_; + return link; + }; + + return link; + }; + + // Populate the sourceLinks and targetLinks for each node. + // Also, if the source and target are not objects, assume they are indices. + function computeNodeLinks() { + nodes.forEach(function(node) { + node.sourceLinks = []; + node.targetLinks = []; + }); + links.forEach(function(link) { + var source = link.source, + target = link.target; + if (typeof source === "number") source = link.source = nodes[link.source]; + if (typeof target === "number") target = link.target = nodes[link.target]; + source.sourceLinks.push(link); + target.targetLinks.push(link); + }); + } + + // Compute the value (size) of each node by summing the associated links. + function computeNodeValues() { + nodes.forEach(function(node) { + node.value = Math.max( + d3.sum(node.sourceLinks, value), + d3.sum(node.targetLinks, value) + ); + }); + } + + // Iteratively assign the breadth (x-position) for each node. + // Nodes are assigned the maximum breadth of incoming neighbors plus one; + // nodes with no incoming links are assigned breadth zero, while + // nodes with no outgoing links are assigned the maximum breadth. + function computeNodeBreadths() { + var remainingNodes = nodes, + nextNodes, + x = 0; + + while (remainingNodes.length) { + nextNodes = []; + remainingNodes.forEach(function(node) { + node.x = x; + node.dx = nodeWidth; + node.sourceLinks.forEach(function(link) { + if (nextNodes.indexOf(link.target) < 0) { + nextNodes.push(link.target); + } + }); + }); + remainingNodes = nextNodes; + ++x; + } + + // + moveSinksRight(x); + scaleNodeBreadths((size[0] - nodeWidth) / (x - 1)); + } + + function moveSourcesRight() { + nodes.forEach(function(node) { + if (!node.targetLinks.length) { + node.x = d3.min(node.sourceLinks, function(d) { return d.target.x; }) - 1; + } + }); + } + + function moveSinksRight(x) { + nodes.forEach(function(node) { + if (!node.sourceLinks.length) { + node.x = x - 1; + } + }); + } + + function scaleNodeBreadths(kx) { + nodes.forEach(function(node) { + node.x *= kx; + }); + } + + function computeNodeDepths(iterations) { + var nodesByBreadth = d3.nest() + .key(function(d) { return d.x; }) + .sortKeys(d3.ascending) + .entries(nodes) + .map(function(d) { return d.values; }); + + // + initializeNodeDepth(); + resolveCollisions(); + for (var alpha = 1; iterations > 0; --iterations) { + relaxRightToLeft(alpha *= .99); + resolveCollisions(); + relaxLeftToRight(alpha); + resolveCollisions(); + } + + function initializeNodeDepth() { + var ky = d3.min(nodesByBreadth, function(nodes) { + return (size[1] - (nodes.length - 1) * nodePadding) / d3.sum(nodes, value); + }); + + nodesByBreadth.forEach(function(nodes) { + nodes.forEach(function(node, i) { + node.y = i; + node.dy = node.value * ky; + }); + }); + + links.forEach(function(link) { + link.dy = link.value * ky; + }); + } + + function relaxLeftToRight(alpha) { + nodesByBreadth.forEach(function(nodes, breadth) { + nodes.forEach(function(node) { + if (node.targetLinks.length) { + var y = d3.sum(node.targetLinks, weightedSource) / d3.sum(node.targetLinks, value); + node.y += (y - center(node)) * alpha; + } + }); + }); + + function weightedSource(link) { + return center(link.source) * link.value; + } + } + + function relaxRightToLeft(alpha) { + nodesByBreadth.slice().reverse().forEach(function(nodes) { + nodes.forEach(function(node) { + if (node.sourceLinks.length) { + var y = d3.sum(node.sourceLinks, weightedTarget) / d3.sum(node.sourceLinks, value); + node.y += (y - center(node)) * alpha; + } + }); + }); + + function weightedTarget(link) { + return center(link.target) * link.value; + } + } + + function resolveCollisions() { + nodesByBreadth.forEach(function(nodes) { + var node, + dy, + y0 = 0, + n = nodes.length, + i; + + // Push any overlapping nodes down. + nodes.sort(ascendingDepth); + for (i = 0; i < n; ++i) { + node = nodes[i]; + dy = y0 - node.y; + if (dy > 0) node.y += dy; + y0 = node.y + node.dy + nodePadding; + } + + // If the bottommost node goes outside the bounds, push it back up. + dy = y0 - nodePadding - size[1]; + if (dy > 0) { + y0 = node.y -= dy; + + // Push any overlapping nodes back up. + for (i = n - 2; i >= 0; --i) { + node = nodes[i]; + dy = node.y + node.dy + nodePadding - y0; + if (dy > 0) node.y -= dy; + y0 = node.y; + } + } + }); + } + + function ascendingDepth(a, b) { + return a.y - b.y; + } + } + + function computeLinkDepths() { + nodes.forEach(function(node) { + node.sourceLinks.sort(ascendingTargetDepth); + node.targetLinks.sort(ascendingSourceDepth); + }); + nodes.forEach(function(node) { + var sy = 0, ty = 0; + node.sourceLinks.forEach(function(link) { + link.sy = sy; + sy += link.dy; + }); + node.targetLinks.forEach(function(link) { + link.ty = ty; + ty += link.dy; + }); + }); + + function ascendingSourceDepth(a, b) { + return a.source.y - b.source.y; + } + + function ascendingTargetDepth(a, b) { + return a.target.y - b.target.y; + } + } + + function center(node) { + return node.y + node.dy / 2; + } + + function value(link) { + return link.value; + } + + return sankey; +}; + +},{}],330:[function(require,module,exports){ +var fetchValue, graph, print, scatter, sort, ticks; + +fetchValue = require("../../core/fetch/value.coffee"); + +graph = require("./helpers/graph/draw.coffee"); + +print = require("../../core/console/print.coffee"); + +sort = require("../../array/sort.coffee"); + +ticks = require("./helpers/graph/dataTicks.coffee"); + +scatter = function(vars) { + var d, domains, i, len, ref; + graph(vars, { + buffer: "size", + mouse: true + }); + domains = vars.x.domain.viz.concat(vars.y.domain.viz); + if (domains.indexOf(void 0) >= 0) { + return []; + } + ref = vars.data.viz; + for (i = 0, len = ref.length; i < len; i++) { + d = ref[i]; + d.d3plus.x = vars.x.scale.viz(fetchValue(vars, d, vars.x.value)); + d.d3plus.x += vars.axes.margin.viz.left; + d.d3plus.y = vars.y.scale.viz(fetchValue(vars, d, vars.y.value)); + d.d3plus.y += vars.axes.margin.viz.top; + if (typeof vars.size.value === "number" || !vars.size.value) { + d.d3plus.r = vars.axes.scale(0); + } else { + d.d3plus.r = vars.axes.scale(fetchValue(vars, d, vars.size.value)); + } + } + ticks(vars); + return sort(vars.data.viz, vars.order.value || vars.size.value || vars.id.value, vars.order.sort.value === "desc" ? "asc" : "desc", vars.color.value || [], vars); +}; + +scatter.fill = true; + +scatter.requirements = ["data", "x", "y"]; + +scatter.scale = 1.1; + +scatter.setup = function(vars) { + if (vars.time.value && !vars.axes.discrete) { + if (vars.time.value === vars.x.value) { + vars.self.x({ + scale: "discrete" + }); + } + if (vars.time.value === vars.y.value) { + return vars.self.y({ + scale: "discrete" + }); + } + } +}; + +scatter.shapes = ["circle", "square", "donut"]; + +scatter.tooltip = "static"; + +module.exports = scatter; + + +},{"../../array/sort.coffee":34,"../../core/console/print.coffee":52,"../../core/fetch/value.coffee":67,"./helpers/graph/dataTicks.coffee":313,"./helpers/graph/draw.coffee":314}],331:[function(require,module,exports){ +var fetchValue = require("../../core/fetch/value.coffee"); +var uniques = require("../../util/uniques.coffee"); +var copy = require("../../util/copy.coffee"); +var rand_col = require("../../color/random.coffee"); + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Table +//------------------------------------------------------------------------------ + +var table = function(vars) { + + // get unique IDs and columns + var ids = uniques(vars.data.viz, vars.id.value, fetchValue, vars); + var cols = uniques(vars.cols.value); + + // if user wants to show the row labels (default behavior) add this as a col + if (cols.indexOf("label") < 0 && vars.cols.index.value){ + cols.unshift("label"); + } + + // width/height are a function of number of IDs and columns + var item_height = vars.height.viz / (ids.length+1); // add 1 for header offset + var item_width = vars.width.viz / cols.length; + + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // Setup background + //---------------------------------------------------------------------------- + vars.group.selectAll("rect").data([0]).enter() + .append("rect") + .attr("class", "background") + .attr("height", vars.height.viz) + .attr("width", vars.width.viz) + .style("fill", vars.color.missing) + // draw line separater w/ enter/update/exit + var lines_horiz = vars.group.selectAll("line.horiz").data(vars.data.viz); + lines_horiz.enter().append("line").attr("class", "horiz") + lines_horiz + .attr("x1", 0) + .attr("y1", function(d, row_i){ return (item_height * row_i) + item_height }) + .attr("x2", vars.width.viz) + .attr("y2", function(d, row_i){ return (item_height * row_i) + item_height }) + .style("fill", "#fff") + .style("stroke", "#fff") + lines_horiz.exit().remove() + // draw line separater w/ enter/update/exit + var lines_vert = vars.group.selectAll("line.vert").data(cols); + lines_vert.enter().append("line").attr("class", "vert") + lines_vert + .attr("x1", function(d, col_i){ return (item_width * col_i) + item_width }) + .attr("y1", 0) + .attr("x2", function(d, col_i){ return (item_width * col_i) + item_width }) + .attr("y2", vars.height.viz) + .style("fill", "#fff") + .style("stroke", "#fff") + lines_vert.exit().remove() + + var ret = [] + var colors = {} + + // doing 2 things here, first we add our column headers to our ret array as + // items dor d3plus to draw. We also compute the color scales for each column + cols.forEach(function(col, col_i){ + // add columns + var header = {"d3plus":{ + "x": (item_width * col_i) + item_width/2, + "y": item_height/2, + "width": item_width, + "height": item_height, + "id": "d3p_header_"+col.toString().replace(/ /g,"_"), + "shape": "square", + "color": "#fff", + "text": vars.format.value(col) + }} + if(col == vars.id.value){ + header.d3plus.color = "#fff"; + } + if(col == "label"){ + header.d3plus.label = false; + header.d3plus.color = "#fff"; + header.d3plus.stroke = "#fff"; + } + ret.push(header) + + // set up color scales + if(vars.data.keys[col] == "number"){ + var domain_extent = d3.extent(vars.data.viz, function(d){ return d[col]; }) + if(domain_extent[0] == domain_extent[1]){ + domain_extent = [domain_extent[0]-1, domain_extent[1]] + } + colors[col] = d3.scale.linear().domain(domain_extent).range([vars.color.missing,rand_col(col)]) + } + else if(vars.data.keys[col] == "boolean"){ + colors[col] = function(bool){ + return bool ? rand_col(col) : vars.color.missing; + } + } + }) + + vars.data.viz.forEach(function(d, row_i){ + // offset for column headers + row_i += 1; + + // loop through each user defined column to create new "object" to draw + cols.forEach(function(col, col_i){ + + // need to clone data since we'll be dupliating it for each column + var d_clone = copy(d); + + // set unique ID otherwise it'd be the same in each column + d_clone.d3plus.id = "d3p_"+d_clone[vars.id.value].toString().replace(/ /g,"_")+"_"+col; + d_clone.d3plus.x = (item_width * col_i) + item_width/2; + d_clone.d3plus.y = (item_height * row_i) + item_height/2; + d_clone.d3plus.width = item_width; + d_clone.d3plus.height = item_height; + + if(col == "label"){ + d_clone.d3plus.shape = "square"; + d_clone.d3plus.color = "#fff"; + // special case for top left corner + ret.push(d_clone) + } + + // be sure that this column is actually in this data item + if(d3.keys(d).indexOf(col) >= 0 && col in d){ + if(colors[col]){ + d_clone.d3plus.color = colors[col](d_clone[col]); + } + d_clone.d3plus.text = vars.format.value(d_clone[col]); + if(vars.data.keys[col] == "boolean"){ + d_clone.d3plus.label = false; + } + else if(vars.data.keys[col] == "string"){ + d_clone.d3plus.color = vars.color.missing; + d_clone.d3plus.stroke = "#fff"; + d_clone.d3plus.shape = "square"; + } + ret.push(d_clone) + } + }) + + }) + + return ret + +}; + +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// Visualization Settings and Helper Functions +//------------------------------------------------------------------------------ +table.shapes = ["check", "cross", "diamond", "square", "triangle", "triangle_up", "triangle_down"] +table.requirements = ["data", "cols"] + +module.exports = table + +},{"../../color/random.coffee":47,"../../core/fetch/value.coffee":67,"../../util/copy.coffee":207,"../../util/uniques.coffee":210}],332:[function(require,module,exports){ +var dataThreshold, groupData, mergeObject, tree_map; + +dataThreshold = require("../../core/data/threshold.js"); + +groupData = require("../../core/data/group.coffee"); + +mergeObject = require("../../object/merge.coffee"); + +tree_map = function(vars) { + var d, data, groupedData, i, len, returnData, root; + groupedData = groupData(vars, vars.data.viz); + data = d3.layout.treemap().mode(vars.type.mode.value).round(true).size([vars.width.viz, vars.height.viz]).children(function(d) { + return d.values; + }).padding(vars.data.padding.value).sort(function(a, b) { + var sizeDiff; + sizeDiff = a.value - b.value; + if (sizeDiff === 0) { + return a.id < b.id; + } else { + return sizeDiff; + } + }).nodes({ + name: "root", + values: groupedData + }).filter(function(d) { + return !d.values && d.area; + }); + if (data.length) { + root = data[0]; + while (root.parent) { + root = root.parent; + } + returnData = []; + for (i = 0, len = data.length; i < len; i++) { + d = data[i]; + d.d3plus.d3plus = mergeObject(d.d3plus.d3plus, { + x: d.x + d.dx / 2, + y: d.y + d.dy / 2, + width: d.dx, + height: d.dy, + share: d.value / root.value + }); + returnData.push(d.d3plus); + } + } + return returnData; +}; + +tree_map.filter = dataThreshold; + +tree_map.modes = ["squarify", "slice", "dice", "slice-dice"]; + +tree_map.requirements = ["data", "size"]; + +tree_map.shapes = ["square"]; + +tree_map.threshold = function(vars) { + return (40 * 40) / (vars.width.viz * vars.height.viz); +}; + +module.exports = tree_map; + + +},{"../../core/data/group.coffee":57,"../../core/data/threshold.js":61,"../../object/merge.coffee":171}],333:[function(require,module,exports){ +var attach, axis, container, flash, getSteps, print, validObject; + +attach = require("../core/methods/attach.coffee"); + +axis = require("./methods/helpers/axis.coffee"); + +flash = require("./helpers/ui/message.js"); + +getSteps = require("./helpers/drawSteps.js"); + +print = require("../core/console/print.coffee"); + +container = require("./helpers/container.coffee"); + +validObject = require("../object/validate.coffee"); + +module.exports = function() { + var vars; + vars = { + g: { + apps: {} + }, + types: { + area: require("./types/area.coffee"), + bar: require("./types/bar.coffee"), + bubbles: require("./types/bubbles.coffee"), + box: require("./types/box.coffee"), + chart: require("./types/deprecated/chart.coffee"), + geo_map: require("./types/geo_map.coffee"), + line: require("./types/line.coffee"), + network: require("./types/network.js"), + paths: require("./types/paths.coffee"), + pie: require("./types/pie.coffee"), + radar: require("./types/radar.coffee"), + rings: require("./types/rings.js"), + sankey: require("./types/sankey.coffee"), + scatter: require("./types/scatter.coffee"), + stacked: require("./types/area.coffee"), + table: require("./types/table.js"), + tree_map: require("./types/tree_map.coffee") + } + }; + vars.self = function(selection) { + selection.each(function() { + var lastMessage, nextStep, runFunction, runStep, small_height, small_width, steps; + vars.draw.frozen = true; + vars.error.internal = null; + if (!("timing" in vars.draw)) { + vars.draw.timing = vars.timing.transitions; + } + if (vars.error.value) { + vars.draw.timing = 0; + } + container(vars); + small_width = vars.width.value <= vars.width.small; + small_height = vars.height.value <= vars.height.small; + vars.small = small_width || small_height; + vars.width.viz = vars.width.value; + vars.height.viz = vars.height.value; + lastMessage = false; + nextStep = function() { + if (steps.length) { + runStep(); + } else { + if (vars.dev.value) { + print.groupEnd(); + print.timeEnd("total draw time"); + print.log("\n"); + } + } + }; + runFunction = function(step, name) { + name = name || "function"; + if (step[name] instanceof Array) { + step[name].forEach(function(f) { + f(vars, nextStep); + }); + } else { + if (typeof step[name] === "function") { + step[name](vars, nextStep); + } + } + if (!step.wait) { + nextStep(); + } + }; + runStep = function() { + var message, run, same, step; + step = steps.shift(); + same = vars.g.message && lastMessage === step.message; + run = "check" in step ? step.check : true; + if (typeof run === "function") { + run = run(vars); + } + if (run) { + if (!same) { + if (vars.dev.value) { + if (lastMessage !== false) { + print.groupEnd(); + } + print.group(step.message); + } + if (typeof vars.messages.value === "string") { + lastMessage = vars.messages.value; + message = vars.messages.value; + } else { + lastMessage = step.message; + message = vars.format.value(step.message); + } + if (vars.draw.update) { + flash(vars, message); + if (vars.error.value) { + runFunction(step); + } else { + setTimeout((function() { + return runFunction(step); + }), 10); + } + } else { + runFunction(step); + } + } else { + runFunction(step); + } + } else { + if ("otherwise" in step) { + if (vars.error.value) { + runFunction(step, "otherwise"); + } else { + setTimeout((function() { + return runFunction(step, "otherwise"); + }), 10); + } + } else { + nextStep(); + } + } + }; + vars.messages.style.backup = vars.group && vars.group.attr("opacity") === "1" ? "small" : "large"; + steps = getSteps(vars); + runStep(); + }); + return vars.self; + }; + attach(vars, { + active: require("./methods/active.coffee"), + aggs: require("./methods/aggs.coffee"), + attrs: require("./methods/attrs.coffee"), + axes: require("./methods/axes.coffee"), + background: require("./methods/background.coffee"), + "class": require("./methods/class.coffee"), + color: require("./methods/color.coffee"), + cols: require("./methods/cols.js"), + config: require("./methods/config.coffee"), + container: require("./methods/container.coffee"), + coords: require("./methods/coords.coffee"), + csv: require("./methods/csv.coffee"), + data: require("./methods/data.coffee"), + depth: require("./methods/depth.coffee"), + descs: require("./methods/descs.coffee"), + dev: require("./methods/dev.coffee"), + draw: require("./methods/draw.js"), + edges: require("./methods/edges.js"), + error: require("./methods/error.coffee"), + focus: require("./methods/focus.coffee"), + font: require("./methods/font.coffee"), + footer: require("./methods/footer.coffee"), + format: require("./methods/format.coffee"), + height: require("./methods/height.coffee"), + history: require("./methods/history.coffee"), + icon: require("./methods/icon.coffee"), + id: require("./methods/id.coffee"), + labels: require("./methods/labels.coffee"), + legend: require("./methods/legend.coffee"), + links: require("./methods/links.coffee"), + margin: require("./methods/margin.coffee"), + messages: require("./methods/messages.coffee"), + mouse: require("./methods/mouse.coffee"), + nodes: require("./methods/nodes.coffee"), + order: require("./methods/order.coffee"), + resize: require("./methods/resize.coffee"), + shape: require("./methods/shape.coffee"), + size: require("./methods/size.coffee"), + style: require("./methods/style.coffee"), + temp: require("./methods/temp.coffee"), + text: require("./methods/text.coffee"), + time: require("./methods/time.coffee"), + timeline: require("./methods/timeline.coffee"), + timing: require("./methods/timing.coffee"), + title: require("./methods/title.coffee"), + tooltip: require("./methods/tooltip.coffee"), + total: require("./methods/total.coffee"), + type: require("./methods/type.coffee"), + ui: require("./methods/ui.coffee"), + width: require("./methods/width.coffee"), + x: axis("x"), + x2: axis("x2"), + y: axis("y"), + y2: axis("y2"), + zoom: require("./methods/zoom.js") + }); + return vars.self; +}; + + +},{"../core/console/print.coffee":52,"../core/methods/attach.coffee":80,"../object/validate.coffee":172,"./helpers/container.coffee":211,"./helpers/drawSteps.js":212,"./helpers/ui/message.js":246,"./methods/active.coffee":255,"./methods/aggs.coffee":256,"./methods/attrs.coffee":257,"./methods/axes.coffee":258,"./methods/background.coffee":259,"./methods/class.coffee":260,"./methods/color.coffee":261,"./methods/cols.js":262,"./methods/config.coffee":263,"./methods/container.coffee":264,"./methods/coords.coffee":265,"./methods/csv.coffee":266,"./methods/data.coffee":267,"./methods/depth.coffee":268,"./methods/descs.coffee":269,"./methods/dev.coffee":270,"./methods/draw.js":271,"./methods/edges.js":272,"./methods/error.coffee":273,"./methods/focus.coffee":274,"./methods/font.coffee":275,"./methods/footer.coffee":276,"./methods/format.coffee":277,"./methods/height.coffee":278,"./methods/helpers/axis.coffee":279,"./methods/history.coffee":280,"./methods/icon.coffee":281,"./methods/id.coffee":282,"./methods/labels.coffee":283,"./methods/legend.coffee":284,"./methods/links.coffee":285,"./methods/margin.coffee":286,"./methods/messages.coffee":287,"./methods/mouse.coffee":288,"./methods/nodes.coffee":289,"./methods/order.coffee":290,"./methods/resize.coffee":291,"./methods/shape.coffee":292,"./methods/size.coffee":293,"./methods/style.coffee":294,"./methods/temp.coffee":295,"./methods/text.coffee":296,"./methods/time.coffee":297,"./methods/timeline.coffee":298,"./methods/timing.coffee":299,"./methods/title.coffee":300,"./methods/tooltip.coffee":301,"./methods/total.coffee":302,"./methods/type.coffee":303,"./methods/ui.coffee":304,"./methods/width.coffee":305,"./methods/zoom.js":306,"./types/area.coffee":307,"./types/bar.coffee":308,"./types/box.coffee":309,"./types/bubbles.coffee":310,"./types/deprecated/chart.coffee":311,"./types/geo_map.coffee":312,"./types/line.coffee":322,"./types/network.js":323,"./types/paths.coffee":324,"./types/pie.coffee":325,"./types/radar.coffee":326,"./types/rings.js":327,"./types/sankey.coffee":328,"./types/scatter.coffee":330,"./types/table.js":331,"./types/tree_map.coffee":332}]},{},[163]); diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/libs/d3plus/d3plus.min.js b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/libs/d3plus/d3plus.min.js new file mode 100644 index 0000000..76c639c --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/libs/d3plus/d3plus.min.js @@ -0,0 +1,18 @@ +!function e(t,r,n){function a(i,s){if(!r[i]){if(!t[i]){var l="function"==typeof require&&require;if(!s&&l)return l(i,!0);if(o)return o(i,!0);var u=new Error("Cannot find module '"+i+"'");throw u.code="MODULE_NOT_FOUND",u}var c=r[i]={exports:{}};t[i][0].call(c.exports,function(e){var r=t[i][1][e];return a(r?r:e)},c,c.exports,e,t,r,n)}return r[i].exports}for(var o="function"==typeof require&&require,i=0;i0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===e[s-2]?2:"="===e[s-1]?1:0,i=new c(3*s/4-o),n=o>0?s-4:s;var l=0;for(t=0,r=0;t>16&255,i[l++]=a>>8&255,i[l++]=255&a;return 2===o?(a=u[e.charCodeAt(t)]<<2|u[e.charCodeAt(t+1)]>>4,i[l++]=255&a):1===o&&(a=u[e.charCodeAt(t)]<<10|u[e.charCodeAt(t+1)]<<4|u[e.charCodeAt(t+2)]>>2,i[l++]=a>>8&255,i[l++]=255&a),i}function o(e){return l[e>>18&63]+l[e>>12&63]+l[e>>6&63]+l[63&e]}function i(e,t,r){for(var n,a=[],i=t;ic?c:u+s));return 1===n?(t=e[r-1],a+=l[t>>2],a+=l[t<<4&63],a+="=="):2===n&&(t=(e[r-2]<<8)+e[r-1],a+=l[t>>10],a+=l[t>>4&63],a+=l[t<<2&63],a+="="),o.push(a),o.join("")}r.toByteArray=a,r.fromByteArray=s;var l=[],u=[],c="undefined"!=typeof Uint8Array?Uint8Array:Array;n()},{}],2:[function(e,t,r){(function(t){"use strict";function n(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}function a(){return i.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(e,t){if(a()=a())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a().toString(16)+" bytes");return 0|e}function g(e){return+e!=e&&(e=0),i.alloc(+e)}function m(e,t){if(i.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return H(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return J(e).length;default:if(n)return H(e).length;t=(""+t).toLowerCase(),n=!0}}function y(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if(r>>>=0,t>>>=0,r<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return B(this,t,r);case"utf8":case"utf-8":return E(this,t,r);case"ascii":return S(this,t,r);case"latin1":case"binary":return T(this,t,r);case"base64":return O(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function x(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function b(e,t,r,n,a){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=a?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(a)return-1;r=e.length-1}else if(r<0){if(!a)return-1;r=0}if("string"==typeof t&&(t=i.from(t,n)),i.isBuffer(t))return 0===t.length?-1:w(e,t,r,n,a);if("number"==typeof t)return t=255&t,i.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):w(e,[t],r,n,a);throw new TypeError("val must be string, number or Buffer")}function w(e,t,r,n,a){function o(e,t){return 1===i?e[t]:e.readUInt16BE(t*i)}var i=1,s=e.length,l=t.length;if(void 0!==n&&(n=String(n).toLowerCase(),"ucs2"===n||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;i=2,s/=2,l/=2,r/=2}var u;if(a){var c=-1;for(u=r;us&&(r=s-l),u=r;u>=0;u--){for(var f=!0,d=0;da&&(n=a)):n=a;var o=t.length;if(o%2!==0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var i=0;i239?4:o>223?3:o>191?2:1;if(a+s<=r){var l,u,c,f;switch(s){case 1:o<128&&(i=o);break;case 2:l=e[a+1],128===(192&l)&&(f=(31&o)<<6|63&l,f>127&&(i=f));break;case 3:l=e[a+1],u=e[a+2],128===(192&l)&&128===(192&u)&&(f=(15&o)<<12|(63&l)<<6|63&u,f>2047&&(f<55296||f>57343)&&(i=f));break;case 4:l=e[a+1],u=e[a+2],c=e[a+3],128===(192&l)&&128===(192&u)&&128===(192&c)&&(f=(15&o)<<18|(63&l)<<12|(63&u)<<6|63&c,f>65535&&f<1114112&&(i=f))}}null===i?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|1023&i),n.push(i),a+=s}return F(n)}function F(e){var t=e.length;if(t<=ee)return String.fromCharCode.apply(String,e);for(var r="",n=0;nn)&&(r=n);for(var a="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,r,n,a,o){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||te.length)throw new RangeError("Index out of range")}function P(e,t,r,n){t<0&&(t=65535+t+1);for(var a=0,o=Math.min(e.length-r,2);a>>8*(n?a:1-a)}function I(e,t,r,n){t<0&&(t=4294967295+t+1);for(var a=0,o=Math.min(e.length-r,4);a>>8*(n?a:3-a)&255}function D(e,t,r,n,a,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function V(e,t,r,n,a){return a||D(e,t,r,4,3.4028234663852886e38,-3.4028234663852886e38),Z.write(e,t,r,n,23,4),r+4}function R(e,t,r,n,a){return a||D(e,t,r,8,1.7976931348623157e308,-1.7976931348623157e308),Z.write(e,t,r,n,52,8),r+8}function U(e){if(e=L(e).replace(te,""),e.length<2)return"";for(;e.length%4!==0;)e+="=";return e}function L(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function Y(e){return e<16?"0"+e.toString(16):e.toString(16)}function H(e,t){t=t||1/0;for(var r,n=e.length,a=null,o=[],i=0;i55295&&r<57344){if(!a){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(i+1===n){(t-=3)>-1&&o.push(239,191,189);continue}a=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),a=r;continue}r=(a-55296<<10|r-56320)+65536}else a&&(t-=3)>-1&&o.push(239,191,189);if(a=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function X(e){for(var t=[],r=0;r>8,a=r%256,o.push(a),o.push(n);return o}function J(e){return K.toByteArray(U(e))}function W(e,t,r,n){for(var a=0;a=t.length||a>=e.length);++a)t[a+r]=e[a];return a}function Q(e){return e!==e}var K=e("base64-js"),Z=e("ieee754"),$=e("isarray");r.Buffer=i,r.SlowBuffer=g,r.INSPECT_MAX_BYTES=50,i.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:n(),r.kMaxLength=a(),i.poolSize=8192,i._augment=function(e){return e.__proto__=i.prototype,e},i.from=function(e,t,r){return s(null,e,t,r)},i.TYPED_ARRAY_SUPPORT&&(i.prototype.__proto__=Uint8Array.prototype,i.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&i[Symbol.species]===i&&Object.defineProperty(i,Symbol.species,{value:null,configurable:!0})),i.alloc=function(e,t,r){return u(null,e,t,r)},i.allocUnsafe=function(e){return c(null,e)},i.allocUnsafeSlow=function(e){return c(null,e)},i.isBuffer=function(e){return!(null==e||!e._isBuffer)},i.compare=function(e,t){if(!i.isBuffer(e)||!i.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,n=t.length,a=0,o=Math.min(r,n);a0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},i.prototype.compare=function(e,t,r,n,a){if(!i.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===a&&(a=this.length),t<0||r>e.length||n<0||a>this.length)throw new RangeError("out of range index");if(n>=a&&t>=r)return 0;if(n>=a)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,a>>>=0,this===e)return 0;for(var o=a-n,s=r-t,l=Math.min(o,s),u=this.slice(n,a),c=e.slice(t,r),f=0;fa)&&(r=a),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return _(this,e,t,r);case"utf8":case"utf-8":return k(this,e,t,r);case"ascii":return z(this,e,t,r);case"latin1":case"binary":return A(this,e,t,r);case"base64":return j(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var ee=4096;i.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,e<0?(e+=r,e<0&&(e=0)):e>r&&(e=r),t<0?(t+=r,t<0&&(t=0)):t>r&&(t=r),t0&&(a*=256);)n+=this[e+--t]*a;return n},i.prototype.readUInt8=function(e,t){return t||q(e,1,this.length),this[e]},i.prototype.readUInt16LE=function(e,t){return t||q(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUInt16BE=function(e,t){return t||q(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUInt32LE=function(e,t){return t||q(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},i.prototype.readUInt32BE=function(e,t){return t||q(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},i.prototype.readIntLE=function(e,t,r){e=0|e,t=0|t,r||q(e,t,this.length);for(var n=this[e],a=1,o=0;++o=a&&(n-=Math.pow(2,8*t)),n},i.prototype.readIntBE=function(e,t,r){e=0|e,t=0|t,r||q(e,t,this.length);for(var n=t,a=1,o=this[e+--n];n>0&&(a*=256);)o+=this[e+--n]*a;return a*=128,o>=a&&(o-=Math.pow(2,8*t)),o},i.prototype.readInt8=function(e,t){return t||q(e,1,this.length),128&this[e]?(255-this[e]+1)*-1:this[e]},i.prototype.readInt16LE=function(e,t){t||q(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},i.prototype.readInt16BE=function(e,t){t||q(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},i.prototype.readInt32LE=function(e,t){return t||q(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},i.prototype.readInt32BE=function(e,t){return t||q(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},i.prototype.readFloatLE=function(e,t){return t||q(e,4,this.length),Z.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return t||q(e,4,this.length),Z.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return t||q(e,8,this.length),Z.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return t||q(e,8,this.length),Z.read(this,e,!1,52,8)},i.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t=0|t,r=0|r,!n){var a=Math.pow(2,8*r)-1;N(this,e,t,r,a,0)}var o=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+o]=e/i&255;return t+r},i.prototype.writeUInt8=function(e,t,r){return e=+e,t=0|t,r||N(this,e,t,1,255,0),i.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},i.prototype.writeUInt16LE=function(e,t,r){return e=+e,t=0|t,r||N(this,e,t,2,65535,0),i.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):P(this,e,t,!0),t+2},i.prototype.writeUInt16BE=function(e,t,r){return e=+e,t=0|t,r||N(this,e,t,2,65535,0),i.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):P(this,e,t,!1),t+2},i.prototype.writeUInt32LE=function(e,t,r){return e=+e,t=0|t,r||N(this,e,t,4,4294967295,0),i.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):I(this,e,t,!0),t+4},i.prototype.writeUInt32BE=function(e,t,r){return e=+e,t=0|t,r||N(this,e,t,4,4294967295,0),i.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):I(this,e,t,!1),t+4},i.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t=0|t,!n){var a=Math.pow(2,8*r-1);N(this,e,t,r,a-1,-a)}var o=0,i=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+r},i.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t=0|t,!n){var a=Math.pow(2,8*r-1);N(this,e,t,r,a-1,-a)}var o=r-1,i=1,s=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/i>>0)-s&255;return t+r},i.prototype.writeInt8=function(e,t,r){return e=+e,t=0|t,r||N(this,e,t,1,127,-128),i.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},i.prototype.writeInt16LE=function(e,t,r){return e=+e,t=0|t,r||N(this,e,t,2,32767,-32768),i.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):P(this,e,t,!0),t+2},i.prototype.writeInt16BE=function(e,t,r){return e=+e,t=0|t,r||N(this,e,t,2,32767,-32768),i.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):P(this,e,t,!1),t+2},i.prototype.writeInt32LE=function(e,t,r){return e=+e,t=0|t,r||N(this,e,t,4,2147483647,-2147483648),i.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):I(this,e,t,!0),t+4},i.prototype.writeInt32BE=function(e,t,r){return e=+e,t=0|t,r||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),i.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):I(this,e,t,!1),t+4},i.prototype.writeFloatLE=function(e,t,r){return V(this,e,t,!0,r)},i.prototype.writeFloatBE=function(e,t,r){return V(this,e,t,!1,r)},i.prototype.writeDoubleLE=function(e,t,r){return R(this,e,t,!0,r)},i.prototype.writeDoubleBE=function(e,t,r){return R(this,e,t,!1,r)},i.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--a)e[a+t]=this[a+r];else if(o<1e3||!i.TYPED_ARRAY_SUPPORT)for(a=0;a>>=0,r=void 0===r?this.length:r>>>0,e||(e=0);var o;if("number"==typeof e)for(o=t;ot?1:0},c=function(e,t,r,o,i){var s;if(null==r&&(r=0),null==i&&(i=n),r<0)throw new Error("lo must be non-negative");for(null==o&&(o=e.length);rr;0<=r?t++:t--)u.push(t);return u}.apply(this).reverse(),l=[],o=0,i=s.length;og;s=0<=g?++p:--p)m.push(i(e,r));return m},v=function(e,t,r,a){var o,i,s;for(null==a&&(a=n),o=e[r];r>t&&(s=r-1>>1,i=e[s],a(o,i)<0);)e[r]=i,r=s;return e[r]=o},g=function(e,t,r){var a,o,i,s,l;for(null==r&&(r=n),o=e.length,l=t,i=e[t],a=2*t+1;a>1,c=-7,f=r?a-1:0,d=r?-1:1,p=e[t+f];for(f+=d,o=p&(1<<-c)-1,p>>=-c,c+=s;c>0;o=256*o+e[t+f],f+=d,c-=8);for(i=o&(1<<-c)-1,o>>=-c,c+=n;c>0;i=256*i+e[t+f],f+=d,c-=8);if(0===o)o=1-u;else{if(o===l)return i?NaN:(p?-1:1)*(1/0);i+=Math.pow(2,n),o-=u}return(p?-1:1)*i*Math.pow(2,o-n)},r.write=function(e,t,r,n,a,o){var i,s,l,u=8*o-a-1,c=(1<>1,d=23===a?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,h=n?1:-1,v=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,i=c):(i=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-i))<1&&(i--,l*=2),t+=i+f>=1?d/l:d*Math.pow(2,1-f),t*l>=2&&(i++,l/=2),i+f>=c?(s=0,i=c):i+f>=1?(s=(t*l-1)*Math.pow(2,a),i+=f):(s=t*Math.pow(2,f-1)*Math.pow(2,a),i=0));a>=8;e[r+p]=255&s,p+=h,s/=256,a-=8);for(i=i<0;e[r+p]=255&i,p+=h,i/=256,u-=8);e[r+p-h]|=128*v}},{}],6:[function(e,t,r){var n={}.toString;t.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},{}],7:[function(require,module,exports){(function(global){"use strict";var numeric="undefined"==typeof exports?function(){}:exports;"undefined"!=typeof global&&(global.numeric=numeric),numeric.version="1.2.6",numeric.bench=function(e,t){var r,n,a,o;for("undefined"==typeof t&&(t=15),a=.5,r=new Date;;){for(a*=2,o=a;o>3;o-=4)e(),e(),e(),e();for(;o>0;)e(),o--;if(n=new Date,n-r>t)break}for(o=a;o>3;o-=4)e(),e(),e(),e();for(;o>0;)e(),o--;return n=new Date,1e3*(3*a-1)/(n-r)},numeric._myIndexOf=function(e){var t,r=this.length;for(t=0;tnumeric.largeArray)return n.push("...Large Array..."),!0;var u=!1;for(n.push("["),a=0;a0&&(n.push(","),u&&n.push("\n ")),u=r(e[a]);return n.push("]"),!0}n.push("{");var u=!1;for(a in e)e.hasOwnProperty(a)&&(u&&n.push(",\n"),u=!0,n.push(a),n.push(": \n"),r(e[a]));return n.push("}"),!0}var n=[];return r(e),n.join("")},numeric.parseDate=function(e){function t(e){if("string"==typeof e)return Date.parse(e.replace(/-/g,"/"));if(!(e instanceof Array))throw new Error("parseDate: parameter must be arrays of strings");var r,n=[];for(r=0;r0){for(a[l]=[],t=0;t>2,i=((3&r)<<4)+(n>>4),s=((15&n)<<2)+(a>>6),l=63&a,t+1>=u?s=l=64:t+2>=u&&(l=64),f+=c.charAt(o)+c.charAt(i)+c.charAt(s)+c.charAt(l);return f}function r(e,t,r){"undefined"==typeof t&&(t=0),"undefined"==typeof r&&(r=e.length);var n,a=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117],o=-1,i=0; +e.length;for(n=t;n>>8^a[i];return o^-1}var n,a,o,i,s,l,u,c,f,d,p=e[0].length,h=e[0][0].length,v=[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,h>>24&255,h>>16&255,h>>8&255,255&h,p>>24&255,p>>16&255,p>>8&255,255&p,8,2,0,0,0,-1,-2,-3,-4,-5,-6,-7,-8,73,68,65,84,8,29];for(d=r(v,12,29),v[29]=d>>24&255,v[30]=d>>16&255,v[31]=d>>8&255,v[32]=255&d,n=1,a=0,u=0;u>8&255,v.push(s),v.push(l),v.push(255&~s),v.push(255&~l),0===u&&v.push(0),c=0;c255?255:s<0?0:Math.round(s),n=(n+s)%65521,a=(a+n)%65521,v.push(s);v.push(0)}return f=(a<<16)+n,v.push(f>>24&255),v.push(f>>16&255),v.push(f>>8&255),v.push(255&f),i=v.length-41,v[33]=i>>24&255,v[34]=i>>16&255,v[35]=i>>8&255,v[36]=255&i,d=r(v,37),v.push(d>>24&255),v.push(d>>16&255),v.push(d>>8&255),v.push(255&d),v.push(0),v.push(0),v.push(0),v.push(0),v.push(73),v.push(69),v.push(78),v.push(68),v.push(174),v.push(66),v.push(96),v.push(130),"data:image/png;base64,"+t(v)},numeric._dim=function(e){for(var t=[];"object"==typeof e;)t.push(e.length),e=e[0];return t},numeric.dim=function(e){var t,r;return"object"==typeof e?(t=e[0],"object"==typeof t?(r=t[0],"object"==typeof r?numeric._dim(e):[e.length,t.length]):[e.length]):[]},numeric.mapreduce=function(e,t){return Function("x","accum","_s","_k",'if(typeof accum === "undefined") accum = '+t+';\nif(typeof x === "number") { var xi = x; '+e+'; return accum; }\nif(typeof _s === "undefined") _s = numeric.dim(x);\nif(typeof _k === "undefined") _k = 0;\nvar _n = _s[_k];\nvar i,xi;\nif(_k < _s.length-1) {\n for(i=_n-1;i>=0;i--) {\n accum = arguments.callee(x[i],accum,_s,_k+1);\n } return accum;\n}\nfor(i=_n-1;i>=1;i-=2) { \n xi = x[i];\n '+e+";\n xi = x[i-1];\n "+e+";\n}\nif(i === 0) {\n xi = x[i];\n "+e+"\n}\nreturn accum;")},numeric.mapreduce2=function(e,t){return Function("x","var n = x.length;\nvar i,xi;\n"+t+";\nfor(i=n-1;i!==-1;--i) { \n xi = x[i];\n "+e+";\n}\nreturn accum;")},numeric.same=function e(t,r){var n,a;if(!(t instanceof Array&&r instanceof Array))return!1;if(a=t.length,a!==r.length)return!1;for(n=0;n=0;n-=2)o[n+1]=t,o[n]=t;return n===-1&&(o[0]=t),o}for(n=a-1;n>=0;n--)o[n]=numeric.rep(e,t,r+1);return o},numeric.dotMMsmall=function(e,t){var r,n,a,o,i,s,l,u,c,f,d;for(o=e.length,i=t.length,s=t[0].length,l=Array(o),r=o-1;r>=0;r--){for(u=Array(s),c=e[r],a=s-1;a>=0;a--){for(f=c[i-1]*t[i-1][a],n=i-2;n>=1;n-=2)d=n-1,f+=c[n]*t[n][a]+c[d]*t[d][a];0===n&&(f+=c[0]*t[0][a]),u[a]=f}l[r]=u}return l},numeric._getCol=function(e,t,r){var n,a=e.length;for(n=a-1;n>0;--n)r[n]=e[n][t],--n,r[n]=e[n][t];0===n&&(r[0]=e[0][t])},numeric.dotMMbig=function(e,t){var r,n,a,o,i=numeric._getCol,s=t.length,l=Array(s),u=e.length,c=t[0].length,f=new Array(u),d=numeric.dotVV;for(--s,--u,n=u;n!==-1;--n)f[n]=Array(c);for(--c,n=c;n!==-1;--n)for(i(t,n,l),a=u;a!==-1;--a)o=0,r=e[a],f[a][n]=d(r,l);return f},numeric.dotMV=function(e,t){var r,n=e.length,a=(t.length,Array(n)),o=numeric.dotVV;for(r=n-1;r>=0;r--)a[r]=o(e[r],t);return a},numeric.dotVM=function(e,t){var r,n,a,o,i,s,l;for(a=e.length,o=t[0].length,i=Array(o),n=o-1;n>=0;n--){for(s=e[a-1]*t[a-1][n],r=a-2;r>=1;r-=2)l=r-1,s+=e[r]*t[r][n]+e[l]*t[l][n];0===r&&(s+=e[0]*t[0][n]),i[n]=s}return i},numeric.dotVV=function(e,t){var r,n,a=e.length,o=e[a-1]*t[a-1];for(r=a-2;r>=1;r-=2)n=r-1,o+=e[r]*t[r]+e[n]*t[n];return 0===r&&(o+=e[0]*t[0]),o},numeric.dot=function(e,t){var r=numeric.dim;switch(1e3*r(e).length+r(t).length){case 2002:return t.length<10?numeric.dotMMsmall(e,t):numeric.dotMMbig(e,t);case 2001:return numeric.dotMV(e,t);case 1002:return numeric.dotVM(e,t);case 1001:return numeric.dotVV(e,t);case 1e3:return numeric.mulVS(e,t);case 1:return numeric.mulSV(e,t);case 0:return e*t;default:throw new Error("numeric.dot only works on vectors and matrices")}},numeric.diag=function(e){var t,r,n,a,o=e.length,i=Array(o);for(t=o-1;t>=0;t--){for(a=Array(o),r=t+2,n=o-1;n>=r;n-=2)a[n]=0,a[n-1]=0;for(n>t&&(a[n]=0),a[t]=e[t],n=t-1;n>=1;n-=2)a[n]=0,a[n-1]=0;0===n&&(a[0]=0),i[t]=a}return i},numeric.getDiag=function(e){var t,r=Math.min(e.length,e[0].length),n=Array(r);for(t=r-1;t>=1;--t)n[t]=e[t][t],--t,n[t]=e[t][t];return 0===t&&(n[0]=e[0][0]),n},numeric.identity=function(e){return numeric.diag(numeric.rep([e],1))},numeric.pointwise=function(e,t,r){"undefined"==typeof r&&(r="");var n,a,o=[],i=/\[i\]$/,s="",l=!1;for(n=0;n=0;i--) ret[i] = arguments.callee("+e.join(",")+",_s,_k+1);\n return ret;\n}\n"+r+"\nfor(i=_n-1;i!==-1;--i) {\n "+t+"\n}\nreturn ret;",Function.apply(null,o)},numeric.pointwise2=function(e,t,r){"undefined"==typeof r&&(r="");var n,a,o=[],i=/\[i\]$/,s="",l=!1;for(n=0;n=0;i--)e("object"==typeof t?t[i]:t,"object"==typeof r?r[i]:r,n,a+1,o)},numeric._biforeach2=function e(t,r,n,a,o){if(a===n.length-1)return o(t,r);var i,s=n[a],l=Array(s);for(i=s-1;i>=0;--i)l[i]=e("object"==typeof t?t[i]:t,"object"==typeof r?r[i]:r,n,a+1,o);return l},numeric._foreach=function e(t,r,n,a){if(n===r.length-1)return void a(t);var o,i=r[n];for(o=i-1;o>=0;o--)e(t[o],r,n+1,a)},numeric._foreach2=function e(t,r,n,a){if(n===r.length-1)return a(t);var o,i=r[n],s=Array(i);for(o=i-1;o>=0;o--)s[o]=e(t[o],r,n+1,a);return s},numeric.ops2={add:"+",sub:"-",mul:"*",div:"/",mod:"%",and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">=",band:"&",bor:"|",bxor:"^",lshift:"<<",rshift:">>",rrshift:">>>"},numeric.opseq={addeq:"+=",subeq:"-=",muleq:"*=",diveq:"/=",modeq:"%=",lshifteq:"<<=",rshifteq:">>=",rrshifteq:">>>=",bandeq:"&=",boreq:"|=",bxoreq:"^="},numeric.mathfuns=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan","isNaN","isFinite"],numeric.mathfuns2=["atan2","pow","max","min"],numeric.ops1={neg:"-",not:"!",bnot:"~",clone:""},numeric.mapreducers={any:["if(xi) return true;","var accum = false;"],all:["if(!xi) return false;","var accum = true;"],sum:["accum += xi;","var accum = 0;"],prod:["accum *= xi;","var accum = 1;"],norm2Squared:["accum += xi*xi;","var accum = 0;"],norminf:["accum = max(accum,abs(xi));","var accum = 0, max = Math.max, abs = Math.abs;"],norm1:["accum += abs(xi)","var accum = 0, abs = Math.abs;"],sup:["accum = max(accum,xi);","var accum = -Infinity, max = Math.max;"],inf:["accum = min(accum,xi);","var accum = Infinity, min = Math.min;"]},function(){var e,t;for(e=0;ev&&(h=o,v=s);for(r=d[h],d[h]=d[i],d[i]=r,a=p[h],p[h]=p[i],p[i]=a,e=r[i],s=i;s!==f;++s)r[s]/=e;for(s=f-1;s!==-1;--s)a[s]/=e;for(o=c-1;o!==-1;--o)if(o!==i){for(t=d[o],n=p[o],e=t[i],s=i+1;s!==f;++s)t[s]-=r[s]*e;for(s=f-1;s>0;--s)n[s]-=a[s]*e,--s,n[s]-=a[s]*e;0===s&&(n[0]-=a[0]*e)}}return p},numeric.det=function(e){var t=numeric.dim(e);if(2!==t.length||t[0]!==t[1])throw new Error("numeric: det() only works on square matrices");var r,n,a,o,i,s,l,u,c=t[0],f=1,d=numeric.clone(e);for(n=0;nMath.abs(d[a][n])&&(a=r);for(a!==n&&(l=d[a],d[a]=d[n],d[n]=l,f*=-1),o=d[n],r=n+1;r=1;t-=2){for(a=e[t],n=e[t-1],r=s-1;r>=1;--r)o=l[r],o[t]=a[r],o[t-1]=n[r],--r,o=l[r],o[t]=a[r],o[t-1]=n[r];0===r&&(o=l[0],o[t]=a[0],o[t-1]=n[0])}if(0===t){for(n=e[0],r=s-1;r>=1;--r)l[r][0]=n[r],--r,l[r][0]=n[r];0===r&&(l[0][0]=n[0])}return l},numeric.negtranspose=function(e){var t,r,n,a,o,i=e.length,s=e[0].length,l=Array(s);for(r=0;r=1;t-=2){for(a=e[t],n=e[t-1],r=s-1;r>=1;--r)o=l[r],o[t]=-a[r],o[t-1]=-n[r],--r,o=l[r],o[t]=-a[r],o[t-1]=-n[r];0===r&&(o=l[0],o[t]=-a[0],o[t-1]=-n[0])}if(0===t){for(n=e[0],r=s-1;r>=1;--r)l[r][0]=-n[r],--r,l[r][0]=-n[r];0===r&&(l[0][0]=-n[0])}return l},numeric._random=function e(t,r){var n,a,o=t[r],i=Array(o);if(r===t.length-1){for(a=Math.random,n=o-1;n>=1;n-=2)i[n]=a(),i[n-1]=a();return 0===n&&(i[0]=a()),i}for(n=o-1;n>=0;n--)i[n]=e(t,r+1);return i},numeric.random=function(e){return numeric._random(e,0)},numeric.norm2=function(e){return Math.sqrt(numeric.norm2Squared(e))},numeric.linspace=function(e,t,r){if("undefined"==typeof r&&(r=Math.max(Math.round(t-e)+1,1)),r<2)return 1===r?[e]:[];var n,a=Array(r);for(r--,n=r;n>=0;n--)a[n]=(n*t+(r-n)*e)/r;return a},numeric.getBlock=function(e,t,r){function n(e,o){var i,s=t[o],l=r[o]-s,u=Array(l);if(o===a.length-1){for(i=l;i>=0;i--)u[i]=e[i+s];return u}for(i=l;i>=0;i--)u[i]=n(e[i+s],o+1);return u}var a=numeric.dim(e);return n(e,0)},numeric.setBlock=function(e,t,r,n){function a(e,n,i){var s,l=t[i],u=r[i]-l;if(i===o.length-1)for(s=u;s>=0;s--)e[s+l]=n[s];for(s=u;s>=0;s--)a(e[s+l],n[s],i+1)}var o=numeric.dim(e);return a(e,n,0),e},numeric.getRange=function(e,t,r){var n,a,o,i,s=t.length,l=r.length,u=Array(s);for(n=s-1;n!==-1;--n)for(u[n]=Array(l),o=u[n],i=e[t[n]],a=l-1;a!==-1;--a)o[a]=i[r[a]];return u},numeric.blockMatrix=function(e){var t=numeric.dim(e);if(t.length<4)return numeric.blockMatrix([e]);var r,n,a,o,i,s=t[0],l=t[1];for(r=0,n=0,a=0;a=0;o--){for(a=Array(u),s=e[o],i=u-1;i>=3;--i)a[i]=s*t[i],--i,a[i]=s*t[i],--i,a[i]=s*t[i],--i,a[i]=s*t[i];for(;i>=0;)a[i]=s*t[i],--i;c[o]=a}return c},numeric.T=function(e,t){this.x=e,this.y=t},numeric.t=function(e,t){return new numeric.T(e,t)},numeric.Tbinop=function(e,t,r,n,a){numeric.indexOf;if("string"!=typeof a){var o;a="";for(o in numeric)numeric.hasOwnProperty(o)&&(e.indexOf(o)>=0||t.indexOf(o)>=0||r.indexOf(o)>=0||n.indexOf(o)>=0)&&o.length>1&&(a+="var "+o+" = numeric."+o+";\n")}return Function(["y"],"var x = this;\nif(!(y instanceof numeric.T)) { y = new numeric.T(y); }\n"+a+"\nif(x.y) { if(y.y) { return new numeric.T("+n+");\n }\n return new numeric.T("+r+");\n}\nif(y.y) {\n return new numeric.T("+t+");\n}\nreturn new numeric.T("+e+");\n")},numeric.T.prototype.add=numeric.Tbinop("add(x.x,y.x)","add(x.x,y.x),y.y","add(x.x,y.x),x.y","add(x.x,y.x),add(x.y,y.y)"),numeric.T.prototype.sub=numeric.Tbinop("sub(x.x,y.x)","sub(x.x,y.x),neg(y.y)","sub(x.x,y.x),x.y","sub(x.x,y.x),sub(x.y,y.y)"),numeric.T.prototype.mul=numeric.Tbinop("mul(x.x,y.x)","mul(x.x,y.x),mul(x.x,y.y)","mul(x.x,y.x),mul(x.y,y.x)","sub(mul(x.x,y.x),mul(x.y,y.y)),add(mul(x.x,y.y),mul(x.y,y.x))"),numeric.T.prototype.reciprocal=function(){var e=numeric.mul,t=numeric.div;if(this.y){var r=numeric.add(e(this.x,this.x),e(this.y,this.y));return new numeric.T(t(this.x,r),t(numeric.neg(this.y),r))}return new T(t(1,this.x))},numeric.T.prototype.div=function e(t){if(t instanceof numeric.T||(t=new numeric.T(t)),t.y)return this.mul(t.reciprocal());var e=numeric.div;return this.y?new numeric.T(e(this.x,t.x),e(this.y,t.x)):new numeric.T(e(this.x,t.x))},numeric.T.prototype.dot=numeric.Tbinop("dot(x.x,y.x)","dot(x.x,y.x),dot(x.x,y.y)","dot(x.x,y.x),dot(x.y,y.x)","sub(dot(x.x,y.x),dot(x.y,y.y)),add(dot(x.x,y.y),dot(x.y,y.x))"),numeric.T.prototype.transpose=function(){var e=numeric.transpose,t=this.x,r=this.y;return r?new numeric.T(e(t),e(r)):new numeric.T(e(t))},numeric.T.prototype.transjugate=function(){var e=numeric.transpose,t=this.x,r=this.y;return r?new numeric.T(e(t),numeric.negtranspose(r)):new numeric.T(e(t))},numeric.Tunop=function(e,t,r){return"string"!=typeof r&&(r=""),Function("var x = this;\n"+r+"\nif(x.y) { "+t+";\n}\n"+e+";\n")},numeric.T.prototype.exp=numeric.Tunop("return new numeric.T(ex)","return new numeric.T(mul(cos(x.y),ex),mul(sin(x.y),ex))","var ex = numeric.exp(x.x), cos = numeric.cos, sin = numeric.sin, mul = numeric.mul;"),numeric.T.prototype.conj=numeric.Tunop("return new numeric.T(x.x);","return new numeric.T(x.x,numeric.neg(x.y));"),numeric.T.prototype.neg=numeric.Tunop("return new numeric.T(neg(x.x));","return new numeric.T(neg(x.x),neg(x.y));","var neg = numeric.neg;"),numeric.T.prototype.sin=numeric.Tunop("return new numeric.T(numeric.sin(x.x))","return x.exp().sub(x.neg().exp()).div(new numeric.T(0,2));"),numeric.T.prototype.cos=numeric.Tunop("return new numeric.T(numeric.cos(x.x))","return x.exp().add(x.neg().exp()).div(2);"),numeric.T.prototype.abs=numeric.Tunop("return new numeric.T(numeric.abs(x.x));","return new numeric.T(numeric.sqrt(numeric.add(mul(x.x,x.x),mul(x.y,x.y))));","var mul = numeric.mul;"),numeric.T.prototype.log=numeric.Tunop("return new numeric.T(numeric.log(x.x));","var theta = new numeric.T(numeric.atan2(x.y,x.x)), r = x.abs();\nreturn new numeric.T(numeric.log(r.x),theta.x);"),numeric.T.prototype.norm2=numeric.Tunop("return numeric.norm2(x.x);","var f = numeric.norm2Squared;\nreturn Math.sqrt(f(x.x)+f(x.y));"),numeric.T.prototype.inv=function(){var e=this;if("undefined"==typeof e.y)return new numeric.T(numeric.inv(e.x));var t,r,n,a,o,i,s,l,u,c,f,t,r,n,d,p,h,v,g,m,y,x=e.x.length,b=numeric.identity(x),w=numeric.rep([x,x],0),_=numeric.clone(e.x),k=numeric.clone(e.y);for(t=0;td&&(n=r,d=p);for(n!==t&&(y=_[t],_[t]=_[n],_[n]=y,y=k[t],k[t]=k[n],k[n]=y,y=b[t],b[t]=b[n],b[n]=y,y=w[t],w[t]=w[n],w[n]=y),a=_[t],o=k[t],l=b[t],u=w[t],h=a[t],v=o[t],r=t+1;r0;t--)for(l=b[t],u=w[t],r=t-1;r>=0;r--)for(c=b[r],f=w[r],h=_[r][t],v=k[r][t],n=x-1;n>=0;n--)g=l[n],m=u[n],c[n]-=h*g-v*m,f[n]-=h*m+v*g;return new numeric.T(b,w)},numeric.T.prototype.get=function(e){var t,r=this.x,n=this.y,a=0,o=e.length;if(n){for(;a=0?1:-1,n=r*numeric.norm2(e);t[0]+=n;var a=numeric.norm2(t);if(0===a)throw new Error("eig: internal error");return numeric.div(t,a)},numeric.toUpperHessenberg=function(e){var t=numeric.dim(e);if(2!==t.length||t[0]!==t[1])throw new Error("numeric: toUpperHessenberg() only works on square matrices");var r,n,a,o,i,s,l,u,c,f,d=t[0],p=numeric.clone(e),h=numeric.identity(d);for(n=0;n0){for(i=numeric.house(o),s=numeric.getBlock(p,[n+1,n],[d-1,d-1]),l=numeric.tensor(i,numeric.dot(i,s)),r=n+1;r=4*l){var j,M;j=.5*(u+Math.sqrt(u*u-4*l)),M=.5*(u-Math.sqrt(u*u-4*l)),c=numeric.add(numeric.sub(numeric.dot(c,c),numeric.mul(c,j+M)),numeric.diag(numeric.rep([3],j*M)))}else c=numeric.add(numeric.sub(numeric.dot(c,c),numeric.mul(c,u)),numeric.diag(numeric.rep([3],l)));for(r=[c[0][0],c[1][0],c[2][0]],n=numeric.house(r),p=[e[0],e[1],e[2]],h=numeric.tensor(n,numeric.dot(n,p)),g=0;g<3;g++)for(d=e[g],v=h[g],y=0;y=0?(p=c<0?-.5*(c-M(d)):-.5*(c+M(d)),m=(i-p)*(i-p)+s*s,y=l*l+(u-p)*(u-p),m>y?(m=M(m),v=(i-p)/m,g=s/m):(y=M(y),v=l/y,g=(u-p)/y),a=new w([[g,-v],[v,g]]),A.setRows(r,o,a.dot(A.getRows(r,o)))):(p=-.5*c,h=.5*M(-d),m=(i-p)*(i-p)+s*s,y=l*l+(u-p)*(u-p),m>y?(m=M(m+h*h),v=(i-p)/m,g=s/m,p=0,h/=m):(y=M(y+h*h),v=l/y,g=(u-p)/y,p=h/y,h=0),a=new w([[g,-v],[v,g]],[[p,h],[h,-p]]),A.setRows(r,o,a.dot(A.getRows(r,o))))}var O=A.dot(e).dot(A.transjugate()),_=e.length,E=numeric.T.identity(_);for(o=0;o<_;o++)if(o>0)for(n=o-1;n>=0;n--){var F=O.get([n,n]),S=O.get([o,o]);numeric.neq(F.x,S.x)||numeric.neq(F.y,S.y)?(p=O.getRow(n).getBlock([n],[o-1]),h=E.getRow(o).getBlock([n],[o-1]),E.set([o,n],O.get([n,o]).neg().sub(p.dot(h)).div(F.sub(S)))):E.setRow(o,E.getRow(n))}for(o=0;o<_;o++)p=E.getRow(o),E.setRow(o,p.div(p.norm2()));return E=E.transpose(),E=A.transjugate().dot(E),{lambda:O.getDiag(),E:E}},numeric.ccsSparse=function(e){var t,r,n,a,o=e.length,i=[];for(n=o-1;n!==-1;--n){r=e[n];for(a in r){for(a=parseInt(a);a>=i.length;)i[i.length]=0;0!==r[a]&&i[a]++}}var t=i.length,s=Array(t+1);for(s[0]=0,n=0;n=l){if(a[c]=p[u],0===u)return;++c,--u,s=f[u],l=d[u]}else i=o[r[s]],0===n[i]?(n[i]=1,f[u]=s,++u,p[u]=i,s=t[i],d[u]=l=t[i+1]):++s},numeric.ccsLPSolve=function(e,t,r,n,a,o,i){var s,l,u,c,f,d,p,h,v,g=e[0],m=e[1],y=e[2],x=(g.length-1,t[0]),b=t[1],w=t[2];for(l=x[a],u=x[a+1],n.length=0,s=l;so&&(i=a,o=s));for(w(y[r])=u){if(a[f]=o[h[c]],0===c)return;++f,--c,l=d[c],u=p[c]}else s=r[l],0===n[s]?(n[s]=1,d[c]=l,++c,h[c]=s,s=o[s],l=t[s],p[c]=u=t[s+1]):++l}},numeric.ccsLPSolve0=function(e,t,r,n,a,o,i,s){var l,u,c,f,d,p,h,v,g,m=e[0],y=e[1],x=e[2],b=(m.length-1,t[0]),w=t[1],_=t[2];for(u=b[a],c=b[a+1],n.length=0,l=u;lo&&(i=a,o=s));for(w(y[_[r]])r[n]&&(r[n]=t.length);var a;for(a in t)t.hasOwnProperty(a)&&e(t[a],r,n+1);return r},numeric.sclone=function e(t,r,n){"undefined"==typeof r&&(r=0),"undefined"==typeof n&&(n=numeric.sdim(t).length);var a,o=Array(t.length);if(r===n-1){for(a in t)t.hasOwnProperty(a)&&(o[a]=t[a]);return o}for(a in t)t.hasOwnProperty(a)&&(o[a]=e(t[a],r+1,n));return o},numeric.sdiag=function(e){var t,r,n=e.length,a=Array(n);for(t=n-1;t>=1;t-=2)r=t-1,a[t]=[],a[t][t]=e[t],a[r]=[],a[r][r]=e[r];return 0===t&&(a[0]=[],a[0][0]=e[t]),a},numeric.sidentity=function(e){return numeric.sdiag(numeric.rep([e],1))},numeric.stranspose=function(e){var t,r,n,a=[];e.length;for(t in e)if(e.hasOwnProperty(t)){n=e[t];for(r in n)n.hasOwnProperty(r)&&("object"!=typeof a[r]&&(a[r]=[]),a[r][t]=n[r])}return a},numeric.sLUP=function(e,t){throw new Error("The function numeric.sLUP had a bug in it and has been removed. Please use the new numeric.ccsLUP function instead.")},numeric.sdotMM=function(e,t){var r,n,a,o,i,s,l,u=e.length,c=(t.length,numeric.stranspose(t)),f=c.length,d=Array(u);for(a=u-1;a>=0;a--){for(l=[],r=e[a],i=f-1;i>=0;i--){s=0,n=c[i];for(o in r)r.hasOwnProperty(o)&&o in n&&(s+=r[o]*n[o]);s&&(l[i]=s)}d[a]=l}return d},numeric.sdotMV=function(e,t){var r,n,a,o,i=e.length,s=Array(i);for(n=i-1;n>=0;n--){r=e[n],o=0;for(a in r)r.hasOwnProperty(a)&&t[a]&&(o+=r[a]*t[a]);o&&(s[n]=o)}return s},numeric.sdotVM=function(e,t){var r,n,a,o,i=[];for(r in e)if(e.hasOwnProperty(r)){a=t[r],o=e[r];for(n in a)a.hasOwnProperty(n)&&(i[n]||(i[n]=0),i[n]+=o*a[n])}return i},numeric.sdotVV=function(e,t){var r,n=0;for(r in e)e[r]&&t[r]&&(n+=e[r]*t[r]);return n},numeric.sdot=function(e,t){var r=numeric.sdim(e).length,n=numeric.sdim(t).length,a=1e3*r+n;switch(a){case 0:return e*t;case 1001:return numeric.sdotVV(e,t);case 2001:return numeric.sdotMV(e,t);case 1002:return numeric.sdotVM(e,t);case 2002:return numeric.sdotMM(e,t);default:throw new Error("numeric.sdot not implemented for tensors of order "+r+" and "+n)}},numeric.sscatter=function(e){var t,r,n,a,o=e[0].length,i=e.length,s=[];for(r=o-1;r>=0;--r)if(e[i-1][r]){for(a=s,n=0;n=0;--o)r[o]=[];for(o=a;o>=0;--o)r[o].push(n[o]);r[a+1].push(i)}}else e(i,r,n);return n.length>a&&n.pop(),r},numeric.cLU=function(e){var t,r,n,a,o,i,s=e[0],l=e[1],u=e[2],c=s.length,f=0;for(t=0;tf&&(f=s[t]);f++;var d,p,h,v=Array(f),g=Array(f),m=numeric.rep([f],1/0),y=numeric.rep([f],-(1/0));for(n=0;ny[t]&&(y[t]=r);for(t=0;ty[t+1]&&(y[t+1]=y[t]);for(t=f-1;t>=1;t--)m[t]=0;r--){for(;f[n]>r;)i[r]-=d[n]*i[f[n]],n--;i[r]/=d[n],n--}return i},numeric.cgrid=function(e,t){"number"==typeof e&&(e=[e,e]);var r,n,a,o=numeric.rep(e,-1);if("function"!=typeof t)switch(t){case"L":t=function(t,r){return t>=e[0]/2||ra&&(a=o[n]);for(a++,r=numeric.rep([a],0),n=0;n1;)n=i((t+r)/2),a[n]<=e?t=n:r=n;return this._at(e,t)}var s,o=e.length,l=Array(o);for(s=o-1;s!==-1;--s)l[s]=this.at(e[s]);return l},numeric.Spline.prototype.diff=function(){var e,t,r,n=this.x,a=this.yl,o=this.yr,i=this.kl,s=this.kr,l=a.length,u=i,c=s,f=Array(l),d=Array(l),p=numeric.add,h=numeric.mul,v=numeric.div,g=numeric.sub;for(e=l-1;e!==-1;--e)t=n[e+1]-n[e],r=g(o[e+1],a[e]),f[e]=v(p(h(r,6),h(i[e],-4*t),h(s[e+1],-2*t)),t*t),d[e+1]=v(p(h(r,-6),h(i[e],2*t),h(s[e+1],4*t)),t*t);return new numeric.Spline(n,u,c,f,d)},numeric.Spline.prototype.roots=function(){function e(e){return e*e}var t=[],r=this.x,n=this.yl,a=this.yr,o=this.kl,i=this.kr;"number"==typeof n[0]&&(n=[n],a=[a],o=[o],i=[i]);var s,l,u,c,f,d,p,h,v,g,m,y,x,b,w,_,k,z,A,j,M,O,E,F,S=n.length,T=r.length-1,t=Array(S),B=Math.sqrt;for(s=0;s!==S;++s){for(c=n[s],f=a[s],d=o[s],p=i[s],h=[],l=0;l!==T;l++){for(l>0&&f[l]*c[l]<0&&h.push(r[l]),_=r[l+1]-r[l],k=r[l],m=c[l],y=f[l+1],v=d[l]/_,g=p[l+1]/_,w=e(v-g+3*(m-y))+12*g*m,x=g+3*m+2*v-3*y,b=3*(g+v+2*(m-y)),w<=0?(A=x/b,z=A>r[l]&&Ar[l]&&Ar[l]&&j0)O=E,A=j;else{for(var C=0;;){if(F=(A*E-j*O)/(A-j),F<=O||F>=E)break;if(M=this._at(F,l),M*j>0)E=F,j=M,C===-1&&(A*=.5),C=-1;else{if(!(M*A>0))break;O=F,A=M,1===C&&(j*=.5),C=1}}h.push(F),O=z[u+1],A=this._at(O,l)}else h.push(O),O=E,A=j;0===j&&h.push(E)}t[s]=h}return"number"==typeof this.yl[0]?t[0]:t},numeric.spline=function(e,t,r,n){var a,o=e.length,i=[],s=[],l=[],u=numeric.sub,c=numeric.mul,f=numeric.add;for(a=o-2;a>=0;a--)s[a]=e[a+1]-e[a],l[a]=u(t[a+1],t[a]);"string"!=typeof r&&"string"!=typeof n||(r=n="periodic");var d=[[],[],[]];switch(typeof r){case"undefined":i[0]=c(3/(s[0]*s[0]),l[0]),d[0].push(0,0),d[1].push(0,1),d[2].push(2/s[0],1/s[0]);break;case"string":i[0]=f(c(3/(s[o-2]*s[o-2]),l[o-2]),c(3/(s[0]*s[0]),l[0])),d[0].push(0,0,0),d[1].push(o-2,0,1),d[2].push(1/s[o-2],2/s[o-2]+2/s[0],1/s[0]);break;default:i[0]=r,d[0].push(0),d[1].push(0),d[2].push(1)}for(a=1;a20)throw new Error("Numerical gradient fails");if(v[a]=t[a]+w,o=e(v),v[a]=t[a]-w,i=e(v),v[a]=t[a],isNaN(o)||isNaN(i))w/=16;else{if(g[a]=(o-i)/(2*w),l=t[a]-w,u=t[a],c=t[a]+w,f=(o-n)/w,d=(n-i)/w,p=h(y(g[a]),y(n),y(o),y(i),y(l),y(u),y(c),1e-8),s=x(h(y(f-g[a]),y(d-g[a]),y(f-d))/p,w/p),!(s>m))break;w/=16}}return g},numeric.uncmin=function(e,t,r,n,a,o,i){var s=numeric.gradient;"undefined"==typeof i&&(i={}),"undefined"==typeof r&&(r=1e-8),"undefined"==typeof n&&(n=function(t){return s(e,t)}),"undefined"==typeof a&&(a=1e3),t=numeric.clone(t);var l,u,c=t.length,f=e(t);if(isNaN(f))throw new Error("uncmin: f(x0) is a NaN!");var d=Math.max,p=numeric.norm2;r=d(r,numeric.epsilon);var h,v,g,m,y,x,b,w,_,k,z=i.Hinv||numeric.identity(c),A=numeric.dot,j=(numeric.inv,numeric.sub),M=numeric.add,O=numeric.tensor,E=numeric.div,F=numeric.mul,S=numeric.all,T=numeric.isFinite,B=numeric.neg,C=0,q="";for(v=n(t);C=.1*_*u||isNaN(l));)_*=.5,++C;if(_*k1;)n=a(.5*(t+r)),s[n]<=e?t=n:r=n;return this._at(e,t)},numeric.dopri=function(e,t,r,n,a,o,i){"undefined"==typeof a&&(a=1e-6),"undefined"==typeof o&&(o=1e3);var s,l,u,c,f,d,p,h,v,g,m,y,x,b=[e],w=[r],_=[n(e,r)],k=[],z=.2,A=[.075,.225],j=[44/45,-56/15,32/9],M=[19372/6561,-25360/2187,64448/6561,-212/729],O=[9017/3168,-355/33,46732/5247,49/176,-5103/18656],E=[35/384,0,500/1113,125/192,-2187/6784,11/84],F=[.10013431883002395,0,.3918321794184259,-.02982460176594817,.05893268337240795,-.04497888809104361,.023904308236133973],S=[.2,.3,.8,8/9,1,1],T=[-71/57600,0,71/16695,-71/1920,17253/339200,-22/525,.025],B=0,C=(t-e)/10,q=0,N=numeric.add,P=numeric.mul,I=(Math.max,Math.min),D=Math.abs,V=numeric.norminf,R=Math.pow,U=numeric.any,L=numeric.lt,Y=numeric.and,H=(numeric.sub,new numeric.Dopri(b,w,_,k,(-1),""));for("function"==typeof i&&(m=i(e,r));et&&(C=t-e),s=n(e+S[0]*C,N(r,P(z*C,_[B]))),l=n(e+S[1]*C,N(N(r,P(A[0]*C,_[B])),P(A[1]*C,s))),u=n(e+S[2]*C,N(N(N(r,P(j[0]*C,_[B])),P(j[1]*C,s)),P(j[2]*C,l))),c=n(e+S[3]*C,N(N(N(N(r,P(M[0]*C,_[B])),P(M[1]*C,s)),P(M[2]*C,l)),P(M[3]*C,u))),f=n(e+S[4]*C,N(N(N(N(N(r,P(O[0]*C,_[B])),P(O[1]*C,s)),P(O[2]*C,l)),P(O[3]*C,u)),P(O[4]*C,c))),v=N(N(N(N(N(r,P(_[B],C*E[0])),P(l,C*E[2])),P(u,C*E[3])),P(c,C*E[4])),P(f,C*E[5])),d=n(e+C,v),p=N(N(N(N(N(P(_[B],C*T[0]),P(l,C*T[2])),P(u,C*T[3])),P(c,C*T[4])),P(f,C*T[5])),P(d,C*T[6])),g="number"==typeof p?D(p):V(p),g>a){if(C=.2*C*R(a/g,.25),e+C===e){H.msg="Step size became too small";break}}else{if(k[B]=N(N(N(N(N(N(r,P(_[B],C*F[0])),P(l,C*F[2])),P(u,C*F[3])),P(c,C*F[4])),P(f,C*F[5])),P(d,C*F[6])),++B,b[B]=e+C,w[B]=v,_[B]=d,"function"==typeof i){var X,G,J=e,W=e+.5*C;if(y=i(W,k[B-1]),x=Y(L(m,0),L(0,y)),U(x)||(J=W,W=e+C,m=y,y=i(W,v),x=Y(L(m,0),L(0,y))),U(x)){for(var Q,K,Z=0,$=1,ee=1;;){if("number"==typeof m)G=(ee*y*J-$*m*W)/(ee*y-$*m);else for(G=W,h=m.length-1;h!==-1;--h)m[h]<0&&y[h]>0&&(G=I(G,(ee*y[h]*J-$*m[h]*W)/(ee*y[h]-$*m[h])));if(G<=J||G>=W)break;X=H._at(G,B-1),K=i(G,X),Q=Y(L(m,0),L(0,K)),U(Q)?(W=G,y=K,x=Q,ee=1,Z===-1?$*=.5:$=1,Z=-1):(J=G,m=K,$=1,1===Z?ee*=.5:ee=1,Z=1)}return v=H._at(.5*(e+G),B-1),H.f[B]=n(G,X),H.x[B]=G,H.y[B]=X,H.ymid[B-1]=v,H.events=x,H.iterations=q,H}}e+=C,r=v,m=y,C=I(.8*C*R(a/g,.25),4*C)}return H.iterations=q,H},numeric.LU=function(e,t){t=t||!1;var r,n,a,o,i,s,l,u,c,f=Math.abs,d=e.length,p=d-1,h=new Array(d);for(t||(e=numeric.clone(e)),a=0;a=0;--r){for(o=s[r],n=r+1;nN)&&(w=N),c=g(e,d(w,O)),l=h(q,E),B=m-1;B!==-1;--B)l[B][B]+=1;C=F(l,v(c,w),!0);var P=v(S,h(t,C)),I=1;for(B=y-1;B!==-1;--B)P[B]<0&&(I=A(I,-.999*P[B]));if(s=p(o,d(C,I)),S=p(r,h(t,s)),!j(M(S,0)))return{solution:o,message:"",iterations:u};if(o=s,w=0);if(x)return{solution:s,message:"Unbounded",iterations:u}}return{solution:o,message:"maximum iteration count exceeded",iterations:u}},numeric._solveLP=function(e,t,r,n,a){var o,i=e.length,s=r.length,l=(numeric.sum,numeric.log,numeric.mul,numeric.sub),u=numeric.dot,c=(numeric.div,numeric.add,numeric.rep([i],0).concat([1])),f=numeric.rep([s,1],-1),d=numeric.blockMatrix([[t,f]]),p=r,o=numeric.rep([i],0).concat(Math.max(0,numeric.sup(numeric.neg(r)))+1),h=numeric.__solveLP(c,d,p,n,a,o,!1),v=numeric.clone(h.solution);v.length=i;var g=numeric.inf(l(r,u(t,v)));if(g<0)return{solution:NaN,message:"Infeasible",iterations:h.iterations};var m=numeric.__solveLP(e,t,r,n,a-h.iterations,v,!0);return m.iterations+=h.iterations,m},numeric.solveLP=function(e,t,r,n,a,o,i){if("undefined"==typeof i&&(i=1e3),"undefined"==typeof o&&(o=numeric.epsilon),"undefined"==typeof n)return numeric._solveLP(e,t,r,o,i);var s,l=n.length,u=n[0].length,c=t.length,f=numeric.echelonize(n),d=numeric.rep([u],0),p=f.P,h=[];for(s=p.length-1;s!==-1;--s)d[p[s]]=1;for(s=u-1;s!==-1;--s)0===d[s]&&h.push(s);var v=numeric.getRange,g=numeric.linspace(0,l-1),m=numeric.linspace(0,c-1),y=v(n,g,h),x=v(t,m,p),b=v(t,m,h),w=numeric.dot,_=numeric.sub,k=w(x,f.I),z=_(b,w(k,y)),A=_(r,w(k,a)),j=Array(p.length),M=Array(h.length);for(s=p.length-1;s!==-1;--s)j[s]=e[p[s]];for(s=h.length-1;s!==-1;--s)M[s]=e[h[s]];var O=_(M,w(j,w(f.I,y))),E=numeric._solveLP(O,z,A,o,i),F=E.solution;if(F!==F)return E;var S=w(f.I,_(a,w(y,F))),T=Array(e.length);for(s=p.length-1;s!==-1;--s)T[p[s]]=S[s];for(s=h.length-1;s!==-1;--s)T[h[s]]=F[s];return{solution:T,message:E.message,iterations:E.iterations}},numeric.MPStoLP=function(e){function t(t){throw new Error("MPStoLP: "+t+"\nLine "+r+": "+e[r]+"\nCurrent state: "+s[i]+"\n")}e instanceof String&&e.split("\n");var r,n,a,o,i=0,s=["Initial state","NAME","ROWS","COLUMNS","RHS","BOUNDS","ENDATA"],l=e.length,u=0,c={},f=[],d=0,p={},h=0,v=[],g=[],m=[];for(r=0;r=o;)e/=2,t/=2,s>>>=1;return(e+s)/t},c},i=t.pow(r,n),a=t.pow(2,a),o=2*a,u(t.random(),e)}([],numeric.seedrandom,256,6,52),function(e){function t(e){if("object"!=typeof e)return e;var r,n=[],a=e.length;for(r=0;rp)m[j]=D;else if(m[j]=-Math.abs(D),D>0){for(A=1;A<=i;A+=1)u[A][z]=-u[A][z];c[z]=-c[z]}}for(z=1;z<=v;z+=1)m[B+h[z]]=0;for(q=0,I=0,z=1;z<=d;z+=1)m[B+z]=1;z-=1){for(D=m[z],j=T+z*(z+3)/2,M=j-z,A=z+1;A<=v;A+=1)D-=m[j]*m[S+A],j+=A;if(D/=m[M],m[S+z]=D,h[z]p)m[B+q]=D;else if(m[B+q]=-Math.abs(D),D>0){for(A=1;A<=i;A+=1)u[A][q]=-u[A][q];c[q]=-c[q]}return 700}for(v+=1,h[v]=q,j=T+(v-1)*v/2+1,z=1;z<=v-1;z+=1)m[j]=m[z],j+=1;if(v===i)m[j]=m[i];else{for(z=i;z>=v+1&&0!==m[z]&&(U=Math.max(Math.abs(m[z-1]),Math.abs(m[z])),L=Math.min(Math.abs(m[z-1]),Math.abs(m[z])),I=m[z-1]>=0?Math.abs(U*Math.sqrt(1+L*L/(U*U))):-Math.abs(U*Math.sqrt(1+L*L/(U*U))),U=m[z-1]/I,L=m[z]/I,1!==U);z-=1)if(0===U)for(m[z-1]=L*I,A=1;A<=i;A+=1)I=e[A][z-1],e[A][z-1]=e[A][z],e[A][z]=I;else for(m[z-1]=I,Y=L/(1+U),A=1;A<=i;A+=1)I=U*e[A][z-1]+L*e[A][z],e[A][z]=Y*(e[A][z-1]+I)-e[A][z],e[A][z-1]=I;m[j]=m[v]}return 0}function w(){if(j=T+E*(E+1)/2+1,M=j+E,0===m[M])return 798;if(U=Math.max(Math.abs(m[M-1]),Math.abs(m[M])),L=Math.min(Math.abs(m[M-1]),Math.abs(m[M])),I=m[M-1]>=0?Math.abs(U*Math.sqrt(1+L*L/(U*U))):-Math.abs(U*Math.sqrt(1+L*L/(U*U))),U=m[M-1]/I,L=m[M]/I,1===U)return 798;if(0===U){for(z=E+1;z<=v;z+=1)I=m[M-1],m[M-1]=m[M],m[M]=I,M+=z;for(z=1;z<=i;z+=1)I=e[z][E],e[z][E]=e[z][E+1],e[z][E+1]=I}else{for(Y=L/(1+U),z=E+1;z<=v;z+=1)I=U*m[M-1]+L*m[M],m[M]=Y*(m[M-1]+I)-m[M],m[M-1]=I,M+=z;for(z=1;z<=i;z+=1)I=U*e[z][E]+L*e[z][E+1],e[z][E+1]=Y*(e[z][E]+I)-e[z][E+1],e[z][E]=I}return 0}function _(){for(M=j-E,z=1;z<=E;z+=1)m[M]=m[j],j+=1,M+=1;return m[C+E]=m[C+E+1],h[E]=h[E+1],E+=1,Et?e*Math.sqrt(1+t*t/e/e):0==t?e:t*Math.sqrt(1+e*e/t/t)}var r,n=numeric.epsilon,a=1e-64/n,o=50,i=0,s=0,l=0,u=0,c=0,f=numeric.clone(e),d=f.length,p=f[0].length;if(d=0&&(y=-y),x=m*y-k,f[s][s]=m-y,l=c;l=0&&(y=-y),x=m*y-k,f[s][s+1]=m-y,l=c;lb&&(b=w)}for(s=p-1;s!=-1;s+=-1){if(0!=y){for(x=y*f[s][s+1],l=c;l=o-1)throw"Error: no convergence.";for(b=v[c],w=v[u-1],y=h[u-1],x=h[u],m=((w-_)*(w+_)+(y-x)*(y+x))/(2*x*w),y=t(m,1),m=m<0?((b-_)*(b+_)+x*(w/(m-y)-x))/b:((b-_)*(b+_)+x*(w/(m+y)-x))/b,i=1,k=1,s=c+1;s=0;l--)if(v[l]1?(n=r.x,a=r.y):s>0&&(n+=o*s,a+=i*s)}return o=e.x-n,i=e.y-a,o*o+i*i}function n(t,r){for(var n,a=t[0],o=[a],i=1,s=t.length;ir&&(o.push(n),a=n);return a!==n&&o.push(n),o}function a(e,t){var n,a,o,i,s=e.length,l="undefined"!=typeof Uint8Array?Uint8Array:Array,u=new l(s),c=0,f=s-1,d=[],p=[];for(u[c]=u[f]=1;f;){for(a=0,n=c+1;na&&(i=n,a=o);a>t&&(u[i]=1,d.push(c,i,i,f)),f=d.pop(),c=d.pop()}for(n=0;n1){var A,j=p.log2(m+1)%r,M=d.root(z);A=b(k,M,function(e,t){return e.get(j)-t.get(j)});for(var O=v.index(m,0),E=A.offset,h=0;h2&&w.push(k.lo(M+1))}else{for(var E=k.offset,O=v.index(m,0),h=0;h0?{p:Array.prototype.slice.call(this.points.data,0,this.length*this.dimension),i:Array.prototype.slice.call(this.ids,0,this.length)}:{d:this.dimension}},v.range=function(e,t,r){var n=this.length;if(!(n<1)){for(var a=this.dimension,o=0;o0&&!(u[0]>=v);){for(var g=l[0],m=a.index(g,0),y=0,c=0;c0&&!(m[0]>=x);){for(var b=g[0],w=i.index(b,0),_=0,y=0;y=t&&u.pop();var k=u.count;c[k]=b,d[k]=-_,u.push(),u.count>=t&&(x=-d[0])}for(var z=p.log2(b+1)%o,A=0,y=0;y=0;--y)I[y]=a[c[0]],u.pop();return u.dispose(),I},v.dispose=function(){f.free(this.points.data),f.freeInt32(this.ids),this.points=null,this.ids=null,this.length=0}},{"./lib/heap.js":10,"bit-twiddle":11,"inorder-tree-layout":12,ndarray:27,"ndarray-ops":14,"ndarray-pack":19,"ndarray-scratch":25,"ndarray-select":26,"typedarray-pool":31}],10:[function(e,t,r){"use strict";function n(e){return 1&e?e-1>>1:(e>>1)-1}function a(e,t){this.count=0,this.dataSize=t,this.index=o.mallocInt32(e),this.data=o.mallocFloat64(e*t)}t.exports=a;var o=e("typedarray-pool"),i=a.prototype;i.heapSwap=function(e,t){var r=this.data,n=this.index,a=this.dataSize,o=n[e];n[e]=n[t],n[t]=o;for(var i=a*e,s=a*t,l=0;l0;){var o=n(e);if(o>=0){var i=r[t*o];if(a0)-(e<0)},r.abs=function(e){var t=e>>a-1;return(e^t)-t},r.min=function(e,t){return t^(e^t)&-(e65535)<<4,e>>>=t,r=(e>255)<<3,e>>>=r,t|=r,r=(e>15)<<2,e>>>=r,t|=r,r=(e>3)<<1,e>>>=r,t|=r,t|e>>1},r.log10=function(e){return e>=1e9?9:e>=1e8?8:e>=1e7?7:e>=1e6?6:e>=1e5?5:e>=1e4?4:e>=1e3?3:e>=100?2:e>=10?1:0},r.popCount=function(e){return e-=e>>>1&1431655765,e=(858993459&e)+(e>>>2&858993459),16843009*(e+(e>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(e){return e+=0===e,--e,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e+1},r.prevPow2=function(e){return e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e-(e>>>1)},r.parity=function(e){return e^=e>>>16,e^=e>>>8,e^=e>>>4,e&=15,27030>>>e&1};var o=new Array(256);!function(e){for(var t=0;t<256;++t){var r=t,n=t,a=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--a;e[t]=n<>>8&255]<<16|o[e>>>16&255]<<8|o[e>>>24&255]},r.interleave2=function(e,t){return e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e|t<<1},r.deinterleave2=function(e,t){return e=e>>>t&1431655765,e=858993459&(e|e>>>1),e=252645135&(e|e>>>2),e=16711935&(e|e>>>4),e=65535&(e|e>>>16),e<<16>>16},r.interleave3=function(e,t,r){return e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e|=t<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),e|r<<2},r.deinterleave3=function(e,t){return e=e>>>t&1227133513,e=3272356035&(e|e>>>2),e=251719695&(e|e>>>4),e=4278190335&(e|e>>>8),e=1023&(e|e>>>16),e<<22>>22},r.nextCombination=function(e){var t=e|e-1;return t+1|(~t&-~t)-1>>>n(e)+1}},{}],12:[function(e,t,r){"use strict";function n(e){var t=(v.nextPow2(e+1)>>>1)-1,r=e-t;return v.nextPow2(r)-1>=t?t:(t>>>1)+r}function a(e){return 0}function o(e){return e-1}function i(e,t){if(e<=0)return 0;var r=n(e);return t>r?i(e-r-1,t-r-1):t===r?v.log2(e):i(r,t)}function s(e,t){return Math.max(t-1,0)}function l(e,t){return Math.min(t+1,e-1)}function u(e,t){if(e<=0)return-1;var r=n(e);if(t>r){var a=u(e-r-1,t-r-1);return a<0?r:a+r+1}if(t===r)return-1;var a=u(r,t);return a<0?r:a}function c(e,t){if(e<=0)return 0;var r=n(e);return t>r?c(e-r-1,t-r-1)+r+1:t===r?n(t):c(r,t)}function f(e,t){if(e<=0)return 0;var r=n(e);return t>r?f(e-r-1,t-r-1)+r+1:t===r?n(e-r-1)+r+1:f(r,t)}function d(e,t){return 0===i(e,t)}function p(e,t){e|=0,t|=0;for(var r=0;e>1;){var a=n(e);if(t>a)r+=a+1,e-=a+1,t-=a+1;else{if(t===a)break;e=a}}return r}function h(e,t){e|=0,t|=0;for(var r=0;e>1;){var a=n(e);if(t>a)r+=a+1,e-=a+1,t-=a+1;else{if(t===a){r+=e-1;break}e=a}}return r}var v=e("bit-twiddle");r.root=n,r.begin=a,r.end=o,r.height=i,r.prev=s,r.next=l,r.parent=u,r.left=c,r.right=f,r.leaf=d,r.lo=p,r.hi=h},{"bit-twiddle":13}],13:[function(e,t,r){arguments[4][11][0].apply(r,arguments)},{dup:11}],14:[function(e,t,r){"use strict";function n(e){if(!e)return s;for(var t=0;t>",rrshift:">>>"};!function(){for(var e in l){var t=l[e];r[e]=o({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+t+"c"},funcName:e}),r[e+"eq"]=o({args:["array","array"],body:{args:["a","b"],body:"a"+t+"=b"},rvalue:!0,funcName:e+"eq"}),r[e+"s"]=o({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+t+"s"},funcName:e+"s"}),r[e+"seq"]=o({args:["array","scalar"],body:{args:["a","s"],body:"a"+t+"=s"},rvalue:!0,funcName:e+"seq"})}}();var u={not:"!",bnot:"~",neg:"-",recip:"1.0/"};!function(){for(var e in u){var t=u[e];r[e]=o({args:["array","array"],body:{args:["a","b"],body:"a="+t+"b"},funcName:e}),r[e+"eq"]=o({args:["array"],body:{args:["a"],body:"a="+t+"a"},rvalue:!0,count:2,funcName:e+"eq"})}}();var c={and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">="};!function(){for(var e in c){var t=c[e];r[e]=o({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+t+"c"},funcName:e}),r[e+"s"]=o({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+t+"s"},funcName:e+"s"}),r[e+"eq"]=o({args:["array","array"],body:{args:["a","b"],body:"a=a"+t+"b"},rvalue:!0,count:2,funcName:e+"eq"}),r[e+"seq"]=o({args:["array","scalar"],body:{args:["a","s"],body:"a=a"+t+"s"},rvalue:!0,count:2,funcName:e+"seq"})}}();var f=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan"];!function(){for(var e=0;ethis_s){this_s=-a}else if(a>this_s){this_s=a}",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norminf"}),r.norm1=i({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:3}],body:"this_s+=a<0?-a:a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norm1"}),r.sup=i({args:["array"],pre:{body:"this_h=-Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),r.inf=i({args:["array"],pre:{body:"this_h=Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),r.random=o({args:["array"],pre:{args:[],body:"this_f=Math.random",thisVars:["this_f"]},body:{args:["a"],body:"a=this_f()",thisVars:["this_f"]},funcName:"random"}),r.assign=o({args:["array","array"],body:{args:["a","b"],body:"a=b"},funcName:"assign"}),r.assigns=o({args:["array","scalar"],body:{args:["a","b"],body:"a=b"},funcName:"assigns"}),r.equals=i({args:["array","array"],pre:s,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1},{name:"y",lvalue:!1,rvalue:!0,count:1}],body:"if(x!==y){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"equals"})},{"cwise-compiler":15}],15:[function(e,t,r){"use strict";function n(){this.argTypes=[],this.shimArgs=[],this.arrayArgs=[],this.arrayBlockIndices=[],this.scalarArgs=[],this.offsetArgs=[],this.offsetArgIndex=[],this.indexArgs=[],this.shapeArgs=[],this.funcName="",this.pre=null,this.body=null,this.post=null,this.debug=!1}function a(e){var t=new n;t.pre=e.pre,t.body=e.body,t.post=e.post;var r=e.args.slice(0);t.argTypes=r;for(var a=0;a0)throw new Error("cwise: pre() block may not reference array args");if(a0)throw new Error("cwise: post() block may not reference array args")}else if("scalar"===i)t.scalarArgs.push(a),t.shimArgs.push("scalar"+a);else if("index"===i){if(t.indexArgs.push(a),a0)throw new Error("cwise: pre() block may not reference array index");if(a0)throw new Error("cwise: post() block may not reference array index")}else if("shape"===i){if(t.shapeArgs.push(a),ar.length)throw new Error("cwise: Too many arguments in pre() block");if(t.body.args.length>r.length)throw new Error("cwise: Too many arguments in body() block");if(t.post.args.length>r.length)throw new Error("cwise: Too many arguments in post() block");return t.debug=!!e.printCode||!!e.debug,t.funcName=e.funcName||"cwise",t.blockSize=e.blockSize||64,o(t)}var o=e("./lib/thunk.js");t.exports=a},{"./lib/thunk.js":17}],16:[function(e,t,r){"use strict";function n(e,t,r){var n,a,o=e.length,i=t.arrayArgs.length,s=t.indexArgs.length>0,l=[],u=[],c=0,f=0;for(n=0;n=0;--n)c=e[n],l.push(["for(i",n,"=0;i",n,"0&&l.push(["index[",f,"]-=s",f].join("")),l.push(["++index[",c,"]"].join(""))),l.push("}")}return l.join("\n")}function a(e,t,r,a){for(var o=t.length,i=r.arrayArgs.length,s=r.blockSize,l=r.indexArgs.length>0,u=[],c=0;c0;){"].join("")),u.push(["if(j",c,"<",s,"){"].join("")),u.push(["s",t[c],"=j",c].join("")),u.push(["j",c,"=0"].join("")),u.push(["}else{s",t[c],"=",s].join("")),u.push(["j",c,"-=",s,"}"].join("")),l&&u.push(["index[",t[c],"]=j",c].join(""));for(var c=0;c0&&(r=r&&t[n]===t[n-1])}return r?t[0]:t.join("")}function l(e,t){for(var r=t[1].length-Math.abs(e.arrayBlockIndices[0])|0,l=new Array(e.arrayArgs.length),c=new Array(e.arrayArgs.length),f=0;f0&&w.push("shape=SS.slice(0)"),e.indexArgs.length>0){for(var _=new Array(r),f=0;f3&&b.push(i(e.pre,e,c));var j=i(e.body,e,c),M=o(g);M3&&b.push(i(e.post,e,c)),e.debug&&console.log("-----Generated cwise routine for ",t,":\n"+b.join("\n")+"\n----------");var O=[e.funcName||"unnamed","_cwise_loop_",l[0].join("s"),"m",M,s(c)].join(""),E=new Function(["function ",O,"(",x.join(","),"){",b.join("\n"),"} return ",O].join(""));return E()}var u=e("uniq");t.exports=l},{uniq:18}],17:[function(e,t,r){"use strict";function n(e){var t=["'use strict'","var CACHED={}"],r=[],n=e.funcName+"_cwise_thunk";t.push(["return function ",n,"(",e.shimArgs.join(","),"){"].join(""));for(var o=[],i=[],s=[["array",e.arrayArgs[0],".shape.slice(",Math.max(0,e.arrayBlockIndices[0]),e.arrayBlockIndices[0]<0?","+e.arrayBlockIndices[0]+")":")"].join("")],l=[],u=[],c=0;c0&&(l.push("array"+e.arrayArgs[0]+".shape.length===array"+f+".shape.length+"+(Math.abs(e.arrayBlockIndices[0])-Math.abs(e.arrayBlockIndices[c]))),u.push("array"+e.arrayArgs[0]+".shape[shapeIndex+"+Math.max(0,e.arrayBlockIndices[0])+"]===array"+f+".shape[shapeIndex+"+Math.max(0,e.arrayBlockIndices[c])+"]"))}e.arrayArgs.length>1&&(t.push("if (!("+l.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same dimensionality!')"),t.push("for(var shapeIndex=array"+e.arrayArgs[0]+".shape.length-"+Math.abs(e.arrayBlockIndices[0])+"; shapeIndex-->0;) {"),t.push("if (!("+u.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same shape!')"),t.push("}"));for(var c=0;c=0;--a)n[a]=r,r*=e[a];return u(f.malloc(r,t),e,n,0)}function o(e){"generic"!==e.dtype&&"array"!==e.dtype&&f.free(e.data)}function i(e,t){t||(t="double");for(var r=1,n=new Array(e.length),a=e.length-1;a>=0;--a)n[a]=r,r*=e[a];for(var o=f.malloc(r,t),a=0;a=0;--a)n[a]=r,r*=e[a];for(var o=f.malloc(r,t),a=0;a=0;--r)o[r]=a,a*=e[r];var i=f.malloc(a,t);for(r=0;r=0;r--)l+=o[r],s=Math.min(s,e[r]); +for(r=0,n=0;r1&&j.push("_cmp:");for(var f=p-1;f>0;--f)j.push("for(",s(f),"=0;",s(f),"<",n(f),";",s(f),"++){");z?j.push(r,"=",m,".get(",u(0),")-",m,".get(",u(1),");"):j.push(r,"=",m,"[",u(0),"]-",m,"[",u(1),"];"),p>1&&j.push("if(",r,")break _cmp;");for(var f=1;f0;--i)j.push("for(",s(e[i]),"=0;",s(e[i]),"<",n(e[i]),";",s(e[i]),"++){");z?j.push(b,"=",m,".get(",u(0),");",m,".set(",u(0),",",m,".get(",u(1),"));",m,".set(",u(1),",",b,");"):j.push(b,"=",m,"[",u(0),"];",m,"[",u(0),"]=",m,"[",u(1),"];",m,"[",u(1),"]=",b,";");for(var i=1;i1?O.push(i(E)+"=("+a(E)+"-"+n(E-1)+"*"+a(E-1)+")|0",o(e[E])+"=("+a(e[E])+"-"+n(e[E-1])+"*"+a(e[E-1])+")|0"):O.push(i(E)+"="+a(E),o(e[E])+"="+a(e[E]));if(t)for(var E=0;E<2;++E)O.push(l(E)+"="+h+".pick(0)");O.push(k+"=0",w+"=0",_+"="+n(e[0])+"-1"),j.push("while(",w,"<",_,"){",k,"=(",x,"()*(",_,"-",w,"+1)+",w,")|0;"),d(k,_),j.push(k,"=",w,";","for(",s(0),"=",w,";",s(0),"<",_,";",s(0),"++){"),f(b,s(0),_),j.push("if(",b,"<0){"),d(k,s(0)),j.push(k,"++;"),j.push("}}"),d(k,_),j.push("if(",k,"===",v,"){",w,"=",k,";","break;","}else if(",v,"<",k,"){",_,"=",k,"-1;","}else{",w,"=",k,"+1;","}","}"),t?j.push(l(0),".offset=",y,"+",w,"*",a(0),";","return ",l(0),";"):j.push("return ",h,".pick(",w,");");var F=["'use strict';function ",A,"(",M,"){","var ",O.join(),";",j.join(""),"};return ",A].join(""),S=new Function(F);return S()}function d(e,t,r){var n=e.join()+t+r,a=z[n];return a?a:z[n]=f(e,t,r)}function p(e,t,r){if(t|=0,0===e.dimension||e.shape[0]<=t||t<0)return null;var n=!!r,a=d(e.order,n,e.dtype);return n?a(e,t,r):a(e,t)}t.exports=p,t.exports.compile=d;var h="a",v="K",g="C",m="d",y="o",x="R",b="T",w="L",_="H",k="X",z={}},{}],27:[function(e,t,r){function n(e,t){return e[0]-t[0]}function a(){var e,t=this.stride,r=new Array(t.length);for(e=0;eMath.abs(this.stride[1]))?[1,0]:[0,1]}})"):3===t&&o.push("var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);if(s0>s1){if(s1>s2){return [2,1,0];}else if(s0>s2){return [1,2,0];}else{return [1,0,2];}}else if(s0>s2){return [2,0,1];}else if(s2>s1){return [0,1,2];}else{return [0,2,1];}}})")):o.push("ORDER})")),o.push("proto.set=function "+r+"_set("+u.join(",")+",v){"),n?o.push("return this.data.set("+c+",v)}"):o.push("return this.data["+c+"]=v}"),o.push("proto.get=function "+r+"_get("+u.join(",")+"){"),n?o.push("return this.data.get("+c+")}"):o.push("return this.data["+c+"]}"),o.push("proto.index=function "+r+"_index(",u.join(),"){return "+c+"}"),o.push("proto.hi=function "+r+"_hi("+u.join(",")+"){return new "+r+"(this.data,"+s.map(function(e){return["(typeof i",e,"!=='number'||i",e,"<0)?this.shape[",e,"]:i",e,"|0"].join("")}).join(",")+","+s.map(function(e){return"this.stride["+e+"]"}).join(",")+",this.offset)}");var h=s.map(function(e){return"a"+e+"=this.shape["+e+"]"}),v=s.map(function(e){return"c"+e+"=this.stride["+e+"]"});o.push("proto.lo=function "+r+"_lo("+u.join(",")+"){var b=this.offset,d=0,"+h.join(",")+","+v.join(","));for(var g=0;g=0){d=i"+g+"|0;b+=c"+g+"*d;a"+g+"-=d}");o.push("return new "+r+"(this.data,"+s.map(function(e){return"a"+e}).join(",")+","+s.map(function(e){return"c"+e}).join(",")+",b)}"),o.push("proto.step=function "+r+"_step("+u.join(",")+"){var "+s.map(function(e){return"a"+e+"=this.shape["+e+"]"}).join(",")+","+s.map(function(e){return"b"+e+"=this.stride["+e+"]"}).join(",")+",c=this.offset,d=0,ceil=Math.ceil");for(var g=0;g=0){c=(c+this.stride["+g+"]*i"+g+")|0}else{a.push(this.shape["+g+"]);b.push(this.stride["+g+"])}");o.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}"),o.push("return function construct_"+r+"(data,shape,stride,offset){return new "+r+"(data,"+s.map(function(e){return"shape["+e+"]"}).join(",")+","+s.map(function(e){return"stride["+e+"]"}).join(",")+",offset)}");var i=new Function("CTOR_LIST","ORDER",o.join("\n"));return i(f[e],a)}function i(e){if(u(e))return"buffer";if(c)switch(Object.prototype.toString.call(e)){case"[object Float64Array]":return"float64";case"[object Float32Array]":return"float32";case"[object Int8Array]":return"int8";case"[object Int16Array]":return"int16";case"[object Int32Array]":return"int32";case"[object Uint8Array]":return"uint8";case"[object Uint16Array]":return"uint16";case"[object Uint32Array]":return"uint32";case"[object Uint8ClampedArray]":return"uint8_clamped"}return Array.isArray(e)?"array":"generic"}function s(e,t,r,n){if(void 0===e){var a=f.array[0];return a([])}"number"==typeof e&&(e=[e]),void 0===t&&(t=[e.length]);var s=t.length;if(void 0===r){r=new Array(s);for(var l=s-1,u=1;l>=0;--l)r[l]=u,u*=t[l]}if(void 0===n){n=0;for(var l=0;l0)return a(0|e,t);break;case"object":if("number"==typeof e.length)return n(e,t,0)}return[]}t.exports=o},{}],31:[function(e,t,r){(function(t,n){"use strict";function a(e){if(e){var t=e.length||e.byteLength,r=y.log2(t);_[r].push(e)}}function o(e){a(e.buffer)}function i(e){var e=y.nextPow2(e),t=y.log2(e),r=_[t];return r.length>0?r.pop():new ArrayBuffer(e)}function s(e){return new Uint8Array(i(e),0,e)}function l(e){return new Uint16Array(i(2*e),0,e)}function u(e){return new Uint32Array(i(4*e),0,e)}function c(e){return new Int8Array(i(e),0,e)}function f(e){return new Int16Array(i(2*e),0,e)}function d(e){return new Int32Array(i(4*e),0,e)}function p(e){return new Float32Array(i(4*e),0,e)}function h(e){return new Float64Array(i(8*e),0,e)}function v(e){return b?new Uint8ClampedArray(i(e),0,e):s(e)}function g(e){return new DataView(i(e),0,e)}function m(e){e=y.nextPow2(e);var t=y.log2(e),r=k[t];return r.length>0?r.pop():new n(e)}var y=e("bit-twiddle"),x=e("dup");t.__TYPEDARRAY_POOL||(t.__TYPEDARRAY_POOL={UINT8:x([32,0]),UINT16:x([32,0]),UINT32:x([32,0]),INT8:x([32,0]),INT16:x([32,0]),INT32:x([32,0]),FLOAT:x([32,0]),DOUBLE:x([32,0]),DATA:x([32,0]),UINT8C:x([32,0]),BUFFER:x([32,0])});var b="undefined"!=typeof Uint8ClampedArray,w=t.__TYPEDARRAY_POOL;w.UINT8C||(w.UINT8C=x([32,0])),w.BUFFER||(w.BUFFER=x([32,0]));var _=w.DATA,k=w.BUFFER;r.free=function(e){if(n.isBuffer(e))k[y.log2(e.length)].push(e);else{if("[object ArrayBuffer]"!==Object.prototype.toString.call(e)&&(e=e.buffer),!e)return;var t=e.length||e.byteLength,r=0|y.log2(t);_[r].push(e)}},r.freeUint8=r.freeUint16=r.freeUint32=r.freeInt8=r.freeInt16=r.freeInt32=r.freeFloat32=r.freeFloat=r.freeFloat64=r.freeDouble=r.freeUint8Clamped=r.freeDataView=o,r.freeArrayBuffer=a,r.freeBuffer=function(e){k[y.log2(e.length)].push(e)},r.malloc=function(e,t){if(void 0===t||"arraybuffer"===t)return i(e);switch(t){case"uint8":return s(e);case"uint16":return l(e);case"uint32":return u(e);case"int8":return c(e);case"int16":return f(e);case"int32":return d(e);case"float":case"float32":return p(e);case"double":case"float64":return h(e);case"uint8_clamped":return v(e);case"buffer":return m(e);case"data":case"dataview":return g(e);default:return null}return null},r.mallocArrayBuffer=i,r.mallocUint8=s,r.mallocUint16=l,r.mallocUint32=u,r.mallocInt8=c,r.mallocInt16=f,r.mallocInt32=d,r.mallocFloat32=r.mallocFloat=p,r.mallocFloat64=r.mallocDouble=h,r.mallocUint8Clamped=v,r.mallocDataView=g,r.mallocBuffer=m,r.clearCache=function(){for(var e=0;e<32;++e)w.UINT8[e].length=0,w.UINT16[e].length=0,w.UINT32[e].length=0,w.INT8[e].length=0,w.INT16[e].length=0,w.INT32[e].length=0,w.FLOAT[e].length=0,w.DOUBLE[e].length=0,w.UINT8C[e].length=0,_[e].length=0,k[e].length=0}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"bit-twiddle":11,buffer:2,dup:30}],32:[function(e,t,r){var n;n=e("../color/sort.coffee"),t.exports=function(e,t,r,a,o,i,s){var l,u,c;for(a||(a="asc"),o instanceof Array||(o=[o]),r instanceof Array||(r=[r]),i&&void 0!==s&&"number"!=typeof s&&(s=i.id.nesting.indexOf(s)),c=0,l=0;l=0?n(e,t):e=0||e.indexOf(r)>=0)}},{}],34:[function(e,t,r){var n,a;n=e("./comparator.coffee"),a=e("../core/fetch/sort.coffee"),t.exports=function(e,t,r,o,i,s){var l,u,c,f;if(!e||e.length<=1)return e||[];if(i)for(t||(t=i.order.value||i.size.value||i.id.value),r||(r=i.order.sort.value),o||(o=i.color.value||[]),c=0,f=e.length;c=0?e.splice(e.indexOf(t),1):e.push(t),e)}},{}],36:[function(e,t,r){var n;n=function(e){var t,r,a,o;if(o=n.tested,e in o)return o[e];for(r=0,a=!1;r=0){a=!0;break}r++}return a},n.tested={},t.exports=n},{}],37:[function(e,t,r){t.exports=/(MSIE|Trident\/|Edge\/)/i.test(navigator.userAgent)},{}],38:[function(e,t,r){var n,a;n=e("./ie.js"),a=e("./touch.coffee"),a?t.exports={click:"click",down:"touchstart",up:"touchend",over:n?"mouseenter":"mouseover",out:n?"mouseleave":"mouseout",move:"mousemove"}:t.exports={click:"click",down:"mousedown",up:"mouseup",over:n?"mouseenter":"mouseover",out:n?"mouseleave":"mouseout",move:"mousemove"}},{"./ie.js":37,"./touch.coffee":43}],39:[function(e,t,r){var n;n=function(){var e;return e="-webkit-transform"in document.body.style?"-webkit-":"-moz-transform"in document.body.style?"-moz-":"-ms-transform"in document.body.style?"-ms-":"-o-transform"in document.body.style?"-o-":"",n=function(){return e},e},t.exports=n},{}],40:[function(e,t,r){t.exports="rtl"===d3.select("html").attr("dir")},{}],41:[function(e,t,r){t.exports={y:function(){return void 0!==window.pageYOffset?window.pageYOffset:(document.documentElement||document.body.parentNode||document.body).scrollTop},x:function(){return void 0!==window.pageXOffset?window.pageXOffset:(document.documentElement||document.body.parentNode||document.body).scrollLeft}}},{}],42:[function(e,t,r){var n;n=function(){var e,t,r,a,o;return e=document.createElement("p"),e.style.width="100%",e.style.height="200px",t=document.createElement("div"),t.style.position="absolute",t.style.top="0px",t.style.left="0px",t.style.visibility="hidden",t.style.width="200px",t.style.height="150px",t.style.overflow="hidden",t.appendChild(e),document.body.appendChild(t),a=e.offsetWidth,t.style.overflow="scroll",o=e.offsetWidth,a===o&&(o=t.clientWidth),document.body.removeChild(t),r=a-o,n=function(){return r},r},t.exports=n},{}],43:[function(e,t,r){t.exports=!!("ontouchstart"in window||window.DocumentTouch&&document instanceof DocumentTouch)},{}],44:[function(e,t,r){t.exports=function(e){var t;return t=d3.hsl(e),t.l>.45&&(t.s>.8&&(t.s=.8),t.l=.45),t.toString()}},{}],45:[function(e,t,r){t.exports=function(e,t){var r;return void 0===t&&(t=.5),r=d3.hsl(e),t=(1-r.l)*t,r.l+=t,r.s-=t,r.toString()}},{}],46:[function(e,t,r){t.exports=function(e,t,r,n){var a,o,i;return r||(r=1),n||(n=1),e=d3.rgb(e),t=d3.rgb(t),i=(r*e.r+n*t.r-r*n*t.r)/(r+n-r*n),o=(r*e.g+n*t.g-r*n*t.g)/(r+n-r*n),a=(r*e.b+n*t.b-r*n*t.b)/(r+n-r*n),d3.rgb(i,o,a).toString()}},{}],47:[function(e,t,r){var n;n=e("./scale.coffee"),t.exports=function(e,t){var r;return r=e||Math.floor(20*Math.random()),(t=t||n)(r)}},{"./scale.coffee":48}],48:[function(e,t,r){t.exports=d3.scale.ordinal().range(["#b22200","#282F6B","#EACE3F","#B35C1E","#224F20","#5F487C","#759143","#419391","#993F88","#e89c89","#ffee8d","#afd5e8","#f7ba77","#a5c697","#c5b5e5","#d1d392","#bbefd0","#e099cf"])},{}],49:[function(e,t,r){t.exports=function(e,t){var r,n;return r=d3.hsl(e),n=d3.hsl(t),e=0===r.s?361:r.h,t=0===n.s?361:n.h,e===t?r.l-n.l:e-t}},{}],50:[function(e,t,r){t.exports=function(e){var t,r,n,a,o;return a=d3.rgb(e),n=a.r,r=a.g,t=a.b,o=(299*n+587*r+114*t)/1e3,o>=128?"#444444":"#f7f7f7"}},{}],51:[function(e,t,r){t.exports=function(e){var t,r,n;return e+="",e=e.replace(RegExp(" ","g"),""),0===e.indexOf("rgb")&&(e=e.split("(")[1].split(")")[0].split(",").slice(0,3).join(",")),0===e.indexOf("hsl")&&(e=e.split(",")[2].split(")")[0]),r=d3.rgb(e).toString(),t=["black","#000","#000000","0%","0,0,0"],n=t.indexOf(e)>=0,"#000000"!==r||n}},{}],52:[function(e,t,r){var n,a,o;n=e("../../client/ie.js"),o=e("./wiki.coffee"),a=function(e,t,r){r=r||"",n||"undefined"!=typeof InstallTrigger?console.log("[ D3plus ] "+t):0===e.indexOf("group")?console[e]("%c[ D3plus ]%c "+t,"font-weight: 800;color: #b35c1e;margin-left: 0px;","font-weight:200;"+r):console[e]("%c"+t,r+"font-weight:200;")},a.comment=function(e){this("log",e,"color:#aaa;")},a.error=function(e,t){this("groupCollapsed","ERROR: "+e,"font-weight:800;color:#D74B03;"),this.stack(),this.wiki(t),this.groupEnd()},a.group=function(e){this("group",e,"color:#888;")},a.groupCollapsed=function(e){this("groupCollapsed",e,"color:#888;")},a.groupEnd=function(){n||console.groupEnd()},a.log=function(e){this("log",e,"color:#444444;")},a.stack=function(){var e,t,r,a,o,i,s;n||(e=new Error,e.stack&&(i=e.stack.split("\n"),i=i.filter(function(e){return 0!==e.indexOf("Error")&&e.indexOf("d3plus.js:")<0&&e.indexOf("d3plus.min.js:")<0}),i.length&&i[0].length&&(o=window.chrome?"at ":"@",s=i[0],s.indexOf(o)>=0&&(s=s.split(o)[1]),i=s.split(":"),3===i.length&&i.pop(),t=i.pop(),a=i.join(":").split("/"),a=a[a.length-1],r="line "+t+" of "+a+": "+s,this("log",r,"color:#D74B03;"))))},a.time=function(e){n||console.time(e)},a.timeEnd=function(e){n||console.timeEnd(e)},a.warning=function(e,t){this("groupCollapsed",e,"color:#888;"),this.stack(),this.wiki(t),this.groupEnd()},a.wiki=function(e){e&&(e in o&&(e=d3plus.repo+"wiki/"+o[e]),this("log","documentation: "+e,"color:#aaa;"))},t.exports=a},{"../../client/ie.js":37,"./wiki.coffee":53}],53:[function(e,t,r){t.exports={active:"Visualizations#active",aggs:"Visualizations#aggs",alt:"Forms#alt",attrs:"Visualizations#attrs",axes:"Visualizations#axes",background:"Visualizations#background",color:"Visualizations#color",cols:"Visualizations#cols",config:"Visualizations#config",container:"Visualizations#container",coords:"Visualizations#coords",csv:"Visualizations#csv",data:"Visualizations#data",depth:"Visualizations#depth",descs:"Visualizations#descs",dev:"Visualizations#dev",draw:"Visualizations#draw",edges:"Visualizations#edges",error:"Visualizations#error",focus:"Visualizations#focus",font:"Visualizations#font",footer:"Visualizations#footer",format:"Visualizations#format",height:"Visualizations#height",history:"Visualizations#history",hover:"Forms#hover",icon:"Visualizations#icon",id:"Visualizations#id",keywords:"Forms#keywords",labels:"Visualizations#labels",legend:"Visualizations#legend",links:"Visualizations#links",margin:"Visualizations#margin",messages:"Visualizations#messages",method:"Methods",mouse:"Visualizations#mouse",nodes:"Visualizations#nodes",open:"Forms#open",order:"Visualizations#order",remove:"Forms#remove",search:"Forms#search",select:"Forms#select",selectAll:"Forms#selectAll",shape:"Visualizations#shape",size:"Visualizations#size",temp:"Visualizations#temp",text:"Visualizations#text",time:"Visualizations#time",timeline:"Visualizations#timeline",timing:"Visualizations#timing",title:"Visualizations#title",tooltip:"Visualizations#tooltip",total:"Visualizations#total",type:"Visualizations#type",ui:"Visualizations#ui",width:"Visualizations#width",x:"Visualizations#x",y:"Visualizations#y",zoom:"Visualizations#zoom"}},{}],54:[function(e,t,r){var n=e("../../util/buckets.coffee"),a=e("../fetch/value.coffee"),o=e("../console/print.coffee");t.exports=function(e){if(e.dev.value&&o.time("getting color data range"),e.color.domain.value)var t=e.color.domain.value;else{var t=[];e.data.pool.forEach(function(r){var n=parseFloat(a(e,r,e.color.value));"number"==typeof n&&!isNaN(n)&&t.indexOf(n)<0&&t.push(n)})}if(e.dev.value&&o.timeEnd("getting color data range"),t.length>1){if(e.dev.value&&o.time("calculating color scale"),t=d3.extent(t),t[0]<0&&t[1]>0){var r=e.color.range;3==r.length&&(t.push(t[1]),t[1]=0)}else if(t[1]>0&&t[0]>=0){var r=e.color.heatmap;t=n(t,r.length)}else{var r=e.color.range.slice(0);t[0]<0?r.pop():r.shift()}e.color.valueScale=d3.scale.sqrt().domain(t).range(r).interpolate(d3.interpolateRgb),e.dev.value&&o.timeEnd("calculating color scale")}else e.color.valueScale=null}},{"../../util/buckets.coffee":204,"../console/print.coffee":52,"../fetch/value.coffee":67}],55:[function(e,t,r){var n=e("../fetch/value.coffee"),a=e("../console/print.coffee"),o=e("../../object/validate.coffee");t.exports=function(e,t){e.dev.value&&a.time("filtering data");var r=d3.keys(e.data.keys||{});"attrs"in e&&(r=r.concat(d3.keys(e.attrs.keys||{}))),t=t.filter(function(t){var r=n(e,t,e.id.value);return null!==r});var i=e.types[e.type.value].requirements||[];e.data.filters.forEach(function(a){r.indexOf(e[a].value)>=0&&i.indexOf(a)>=0&&(t=t.filter(function(t){var r=n(e,t,e[a].value);return"y"===a&&e.y2.value&&null===r?r=n(e,t,e.y2.value):"x"===a&&e.x2.value&&null===r&&(r=n(e,t,e.x2.value)),"size"===a?"number"==typeof r:null!==r}))});var s=e.data.solo.length?"solo":"mute";return e.data[s].length?e.data[s].forEach(function(r){function i(t){var n=e[r][s].value,a=!1;return n.forEach(function(e){"function"==typeof e?a=e(t):e===t&&(a=!0)}),"solo"===s?a:!a}function l(t,a){if(!a&&e[r].nesting){var s=e[r].nesting;o(s)&&(s=d3.values(s));for(var l=0;l=4||s.indexOf(t)<=3)return d.timeFormat[t+"-"+e];var n;return n="Date"===t?d.timeFormat[t]:d.timeFormat[t+"-Date"],"Hours"===e?n+" "+d.timeFormat[e]:n+" "+d.timeFormat["Hours-"+e]};if(e.data.time.getFormat=h,f)"string"==typeof f?e.data.time.format=d3.locale(d.format).timeFormat(f):"function"==typeof f?e.data.time.format=f:f instanceof Array&&(e.data.time.format=d3.locale(d.format).timeFormat.multi(f)),e.data.time.multiFormat=e.data.time.format;else{for(var v=e.data.time.stepType,g=e.data.time.totalType,m=[],y=s.indexOf(v);y<=s.indexOf(g);y++){var x=y-11?(m[m.length-1][1]=function(e){return!0},e.data.time.multiFormat=d3.locale(d.format).timeFormat.multi(m)):e.data.time.multiFormat=e.data.time.format}e.data.time.ticks=[];for(var _=d3.min(e.data.time.values),k=d3.max(e.data.time.values),z=0;z<=e.data.time.stepIntervals;z++){var A=new Date(_);A["set"+e.data.time.stepType](A["get"+e.data.time.stepType]()+z),A<=k&&e.data.time.ticks.push(A)}e.dev.value&&o.timeEnd(t)}if(e.dev.value&&(t="nesting data by time and depths",o.time(t)),e.data.nested={},0===e.data.time.values.length)e.data.nested.all={},e.id.nesting.forEach(function(t,r){var a=e.id.nesting.slice(0,r+1);e.data.nested.all[t]=n(e,e.data.value,a)});else{var j=e.data.value.reduce(function(t,r){var n=a(e,r,e.time.value).getTime();return n in t||(t[n]=[]),t[n].push(r),t},{});e.data.time.values.forEach(function(t){var r=t.getTime();e.data.nested[r]={},e.id.nesting.forEach(function(t,a){var o=e.id.nesting.slice(0,a+1);e.data.nested[r][t]=n(e,j[r],o)})})}e.dev.value&&o.timeEnd(t)}},{"../../util/uniques.coffee":210,"../console/print.coffee":52,"../fetch/value.coffee":67,"./nest.js":60}],57:[function(e,t,r){var n;n=e("../fetch/value.coffee"),t.exports=function(e,t,r){var a,o,i,s,l,u,c,f,d,p;if(o=d3.nest(),e.id.grouping.value)for(void 0===r&&(r=e.id.nesting),i=s=0,u=r.length;s0&&(delete a.d3plus.r,delete a.d3plus.x,delete a.d3plus.y,d.push({d3plus:a,id:a[e.id.value],value:p}));return o.entries(d)}},{"../fetch/value.coffee":67}],58:[function(e,t,r){var n,a,o=[].indexOf||function(e){for(var t=0,r=this.length;t=0||null===d?f.push(void 0):f.push(e[t].keys[l]=typeof d);return f}},a(e[t].value)){l=d3.keys(e[t].value).length===e.id.nesting.length,u=e[t].value;for(i in u)if(d=u[i],l&&e.id.nesting.indexOf(i)>=0&&a(d))for(s in d)p=d[s],r(p);else r(d)}else{c=e[t].value;for(i in c)d=c[i],r(d)}if(e.dev.value)return n.time(f)}},{"../../object/validate.coffee":172,"../console/print.coffee":52}],59:[function(e,t,r){var n,a;n=e("../console/print.coffee"),a=e("../../object/validate.coffee"),t.exports=function(e,t,r){var o,i,s,l;return o=e.dev.value,o&&n.time("loading "+t),l=e[t].url,e[t].filetype.value?i=e[t].filetype.value:(i=l.slice(l.length-5).split("."),i=i.length>1&&i[1],i?("txt"===i&&(i="text"),e[t].filetype.accepted.indexOf(i)<0&&(i="json")):i="json"),(s="dsv"===i?d3.dsv(e[t].delimiter.value,"text/plain"):d3[i])(l,function(s,u){var c,f;if(!s&&u){if("function"==typeof e[t].callback){if(f=e[t].callback(u))if(a(f)&&t in f)for(c in f)c in e&&(e[c].value=f[c]);else e[t].value=f}else e[t].value=u;["json"].indexOf(i)<0&&e[t].value.forEach(function(e){var t;t=[];for(c in e)isNaN(e[c])?"false"===e[c].toLowerCase()?t.push(e[c]=!1):"true"===e[c].toLowerCase()?t.push(e[c]=!0):"null"===e[c].toLowerCase()?t.push(e[c]=null):"undefined"===e[c].toLowerCase()?t.push(e[c]=void 0):t.push(void 0):t.push(e[c]=parseFloat(e[c]));return t}),e[t].changed=!0,e[t].loaded=!0}else e.error.internal='Could not load data from: "'+l+'"';return o&&n.timeEnd("loading "+t),r()})}},{"../../object/validate.coffee":172,"../console/print.coffee":52}],60:[function(e,t,r){var n=e("../fetch/value.coffee"),a=e("../../object/validate.coffee"),o=e("../../util/uniques.coffee"),i=function(e,t,r,a){void 0===a&&(a=!0);var i=d3.nest(),c=[],f="temp"in e?["active","temp","total"]:[];r.length?r.forEach(function(t,r){i.key(function(r){return n(e,r,t)})}):i.key(function(e){return!0}),a&&e.axes&&e.axes.discrete&&(!e.time||e[e.axes.discrete].value!==e.time.value)&&i.key(function(t){return n(e,t,e[e.axes.discrete].value)});var d=r.length&&e.id.nesting.indexOf(r[r.length-1])>=0,p=r.length&&d?r.length-1:0;d?e.id.nesting[p]:e.depth.value;i.rollup(function(t){if(1===t.length&&"d3plus"in t[0])return c.push(t[0]),t[0];t=t.reduce(function(e,t){return t.values instanceof Array?e.concat(t.values):(e.push(t),e)},[]);var a={d3plus:{data:{},depth:p}},i=d3.sum(t,function(e){return"d3plus"in e&&e.d3plus.merged?1:0});if(i===t.length)for(var u=0;u=0,_="time"in e&&m===e.time.value;if(m in a.d3plus.data)a[m]=a.d3plus[m];else if("function"===x)a[m]=e.aggs.value[m](t);else if(_)a[m]=l(o(t,m));else if(e.axes&&e.axes.discrete&&e[e.axes.discrete].value===m)a[m]=o(t,m);else if("number"!==b||"string"!==x||w){var k=s(t,m),z=1===k.length?k[0][m]:o(k,m);if(1===k.length)a[m]=z;else if(z&&z.length)z instanceof Array||(z=[z]),w&&e.id.nesting.indexOf(m)>p?a[m]=k:a[m]=z;else if(w){var A=e.id.nesting.indexOf(m)-1;A>=p&&(!("endPoint"in a.d3plus)||a.d3plus.endPoint>p)&&(a.d3plus.endPoint=p)}}else{var j=t.map(function(e){return e[m]});j=j.filter(function(e){return typeof e===b}),j.length&&(a[m]=d3[y](j)); +}}m in a&&a[m]instanceof Array&&1===a[m].length&&(a[m]=a[m][0])}for(var M=0;M0){var l=[],u=0===e.depth.value?0:{},c=[],f=[],d=[],p={},h=d3.nest();r&&h.key(function(t){return o(e,t,r)}),h.rollup(function(t){var n=t.length;e.aggs.value[e.size.value]?"function"==typeof e.aggs.value[e.size.value]?n=e.aggs.value[e.size.value](t):"string"==typeof e.aggs.value[e.size.value]&&(n=d3[e.aggs.value[e.size.value]](t,function(t){return o(e,t,e.size.value)})):n=d3.sum(t,function(t){return o(e,t,e.size.value)});var a=r?o(e,t[0],r):"all";return p[a]=n,n}).entries(t),t.forEach(function(t){var n=o(e,t,e.id.value),a=o(e,t,e.size.value),i=r?o(e,t,r):"all",u=a/p[i]>=s;if(u&&l.indexOf(n)<0&&(l.push(n),e.depth.value)){var c=o(e,t,e.id.nesting[e.depth.value-1]);f.indexOf(c)<0&&f.push(c)}});var v=t.filter(function(t){var r=o(e,t,e.id.value),n=l.indexOf(r)>=0,a=e.depth.value?o(e,t,e.id.nesting[e.depth.value-1]):null;if(null!==a&&f.indexOf(a)<0&&d.indexOf(a)<0&&d.push(a),!n){var i=o(e,t,e.size.value);i>0&&(0===e.depth.value?i>u&&(u=i):(a in u||(u[a]=0),i>u[a]&&(u[a]=i)),c.push(t))}return n});if(c.length>1){c=n(c,e.size.value,"desc",[],e);var g=e.id.nesting.slice(0,e.depth.value);e.types[e.type.value].requirements.indexOf(e.axes.discrete)>=0&&g.push(e[e.axes.discrete].value);var m=a(e,c,g);m.forEach(function(t){var r=e.id.nesting[e.depth.value-1],n=o(e,t,r);if(children=r?c.filter(function(t){return o(e,t,r)===n}):c,children.length>1){e.id.nesting.forEach(function(r,n){if(e.depth.value==n){var a=t[r];"string"==typeof a?t[r]="d3plus_other_"+a:t[r]="d3plus_other"}else n>e.depth.value&&delete t[r]}),e.color.value&&"string"===e.color.type&&(0===e.depth.value?t[e.color.value]=e.color.missing:t[e.color.value]=o(e,n,e.color.value,r)),e.icon.value&&(t[e.icon.value]=o(e,n,e.icon.value,r)),n&&(t.d3plus.depth=e.depth.value);var a;0===e.depth.value?(a=e.format.value(e.format.locale.value.ui.values,{key:"threshold",vars:e}),a+=" < "+e.format.value(u,{key:e.size.value,vars:e})):(a=i(e,t,e.depth.value-1),a=a.length?a[0].split(" < ")[0]:e.format.value(e.format.locale.value.ui.values,{key:"threshold",vars:e}),d.indexOf(n)<0&&(a+=" < "+e.format.value(u[n],{key:e.size.value,vars:e}))),d.indexOf(n)<0&&(a+=" ("+e.format.value(100*s,{key:"share",vars:e})+")"),t.d3plus.threshold=u,t.d3plus.merged=children,e.text.value&&(t[e.text.value]=a),t.d3plus.text=a}})}else m=c;return v.concat(m)}return t}},{"../../array/sort.coffee":34,"../fetch/color.coffee":63,"../fetch/text.js":66,"../fetch/value.coffee":67,"./nest.js":60}],62:[function(e,t,r){var n;n=e("../../font/sizes.coffee"),t.exports=function(e,t){var r,a,o,i,s,l,u,c,f,d,p,h,v,g,m,y,x,b;if(b=t.values||e.data.time.ticks,g=t.style||{},s=t.limit||e.width.value,m={},c=e.data.time.periods,v=e.data.time.stepType,y=e.data.time.totalType,o=e.data.time.functions,i=e.data.time.getFormat,l=e.format.locale.value.format,e.time.format.value)m.format=e.data.time.format,m.values=b,m.sizes=n(b.map(function(e){return m.format(e)}),g);else for(u=c.indexOf(v);u<=c.indexOf(y);){if(x=b.filter(function(e){var t,r;if(u===c.indexOf(v))return!0;if(t=!0,r=u-1,u<0)return!0;for(;r>=c.indexOf(v)&&t;)t=!o[r](e),r--;return t}),c[u]===y)a=d3.locale(l).timeFormat(i(c[u],y));else{for(f=u,a=[];f<=c.indexOf(y);)d=f-1=0;){if(l=e.id.nesting[f],p=s(t,e.color.value,n,e,l),1===p.length&&(p=p[0]),!(p instanceof Array)&&void 0!==p&&null!==p){i=a(e,t,p,r),c.indexOf(i)<0&&c.push(i);break}f--}return 1===c.length?c[0]:e.color.missing}return o(e,t,r)},a=function(e,t,r,n){return r?e.color.valueScale?e.color.valueScale(r):l(r)?r:o(e,r,n):e.color.value&&"function"==typeof e.color.valueScale?e.color.valueScale(0):o(e,t,n)},o=function(e,t,r){return u(t)&&(t=n(e,t,r)),t instanceof Array&&(t=t[0]),i(t,e.color.scale.value)}},{"../../color/random.coffee":47,"../../color/validate.coffee":51,"../../object/validate.coffee":172,"../../util/uniques.coffee":210,"./value.coffee":67}],64:[function(e,t,r){var n=e("../data/filter.js"),a=e("../data/nest.js"),o=e("../console/print.coffee"),i=e("../../string/format.js"),s=e("../../string/list.coffee");t.exports=function(e,t,r){if(!e.data.value)return[];void 0===r&&(r=e.depth.value);var l=e.id.nesting[r];if(!t||t instanceof Array||(t=[t]),!t&&"time"in e){t=[];var u=e.time.solo.value.length?"solo":"mute",c=e.time[u].value;if(c.length){t=[];for(var f=0;f=0&&e.data.time.values.length){t=e.data.time.values.slice(0);for(var g=0;g1&&(M=d3.extent(M)),M=M.map(function(t){return e.data.time.format(new Date(t))}),M=M.join(" - ");var F=e.format.locale.value.error.dataYear,S=e.format.locale.value.ui.and;M=s(M,S),e.error.internal=i(F,M),e.time.missing=!0}else{if(e.time&&(e.time.missing=!1),t.length>1){var T=!1;if(["x","y","x2","y2"].forEach(function(t){e[t].value===e.time.value&&"discrete"===e[t].scale.value&&(T=!0)}),!T){var B=e.id.nesting.slice(0,r+1);j=a(e,j,B)}}j=j?n(e,j):[],20===x.length&&(x.sort(),delete e.data.cache[x[0]]),m=(new Date).getTime()+"_"+m,e.data.cache[m]={data:j},"nodes"in e&&(e.data.cache[m].nodes=e.nodes.restricted,e.data.cache[m].edges=e.edges.restricted),"function"==typeof b&&(j=b(e,j)),e.dev.value&&o.comment("storing data in cache")}return j}},{"../../string/format.js":173,"../../string/list.coffee":174,"../console/print.coffee":52,"../data/filter.js":55,"../data/nest.js":60}],65:[function(e,t,r){var n,a,o;o=e("./value.coffee"),n=e("./color.coffee"),a=e("./text.js"),t.exports=function(e,t,r,i,s){var l,u,c,f,d,p;for(r instanceof Array||(r=[r]),i instanceof Array||(i=[i]),e&&(void 0===s?s=e.id.value:"number"!=typeof s&&(s=e.id.nesting.indexOf(s))),d={},u=0,f=r.length;u=0?n(e,t,s):c===e.text.value?a(e,t,s):3===d3.keys(t).length&&t.d3plus&&t.key&&t.values?o(e,t.values.map(function(e){return e.d3plus}),c,s):o(e,t,c,s):t[c],[e.data.keys[c],e.attrs.keys[c]].indexOf("number")>=0?(l=e.order.agg.value||e.aggs.value[c]||"sum",l.constructor===String&&(l=d3[l]),p instanceof Array||(p=[p]),p=l(p)):(p instanceof Array&&(p=p[0]),p="string"==typeof p?p.toLowerCase():p),d[c]=p;return d}},{"./color.coffee":63,"./text.js":66,"./value.coffee":67}],66:[function(e,t,r){var n=e("./value.coffee"),a=e("../../object/validate.coffee"),o=e("../../util/uniques.coffee");t.exports=function(e,t,r){"number"!=typeof r&&(r=e.depth.value);var i,s=e.id.nesting[r];e.text.nesting&&a(e.text.nesting)?i=e.text.nesting[s]?e.text.nesting[s]:e.text.value:(i=[],e.text.value&&r===e.depth.value&&i.push(e.text.value),i.push(s)),i instanceof Array||(i=[i]);var l=[];if(a(t)&&"d3plus"in t&&t.d3plus.text)l.push(t.d3plus.text.toString()),l.push(e.format.value(t.d3plus.text.toString(),{vars:e,data:t}));else{var u=a(t)?t:void 0;u&&t[e.id.value]instanceof Array?t=t[e.id.value]:t instanceof Array||(t=[t]),i.forEach(function(r){var a=o(t,r,n,e,s);a.length&&(a.length>1&&(a=a.filter(function(e){return e instanceof Array||"string"==typeof e&&e.indexOf(" < ")<0})),a=a.map(function(t){return t instanceof Array?(t=t.filter(function(e){return e}),t.map(function(t){return e.format.value(t.toString(),{vars:e,data:u,key:r})})):t?e.format.value(t.toString(),{vars:e,data:u,key:r}):void 0}),1===a.length&&(a=a[0]),l.push(a))})}return l}},{"../../object/validate.coffee":172,"../../util/uniques.coffee":210,"./value.coffee":67}],67:[function(e,t,r){var n,a,o,i,s,l,u,c,f,d;f=e("../../object/validate.coffee"),c=e("../../util/uniques.coffee"),u=function(e,t,r,i){var s,l,u,d;if(l=f(t),"function"==typeof r&&l)return r(t,e);if(l){if(r in t)return t[r];if(s=e.data.cacheID+"_"+i,n(t,s,e),r in t.d3plus.data[s])return t.d3plus.data[s][r];if(i in t)t=t[i];else{if(!(e.id.value in t))return null;if(t=t[e.id.value],i!==r&&(u=o(e,t,i,e.id.value)),null!==u&&void 0!==u||(u=a(e,t,i,e.id.value)),null===u||void 0===u)return null;if(i===r)return u;t=u}}return t instanceof Array&&!f(t[0])&&(t=c(t)),t instanceof Array&&f(t[0])&&(d=c(t,r),d.length)?d:(d=o(e,t,r,i))?d:d=a(e,t,r,i)},o=function(e,t,r,n){var a;return e.data.viz instanceof Array&&r in e.data.keys&&(a=c(l(e.data.viz,t,n),r)),a&&a.length?a:null},a=function(e,t,r,n){var a,o,i,s;if("attrs"in e&&e.attrs.value&&r in e.attrs.keys)if(a=f(e.attrs.value)&&n in e.attrs.value?e.attrs.value[n]:e.attrs.value,a instanceof Array){if(i=c(l(a,t,n),r),i.length)return i}else if(t instanceof Array){if(a=[function(){var e,r,n;if(o in a){for(n=[],e=0,r=t.length;e=0}):e.filter(function(e){return e[r]===t})},n=function(e,t,r){return"d3plus"in e||(e.d3plus={}),"data"in e.d3plus||(e.d3plus.data={}),!(r.data.changed||r.attrs&&r.attrs.changed)&&t in e.d3plus.data||(e.d3plus.data[t]={}),e},d=function(e,t,r,n,a){var o,i,s,l,u,c,d;if(null===a)return a;c="time"in e&&e.time.value===n,a instanceof Array||(a=[a]);for(s=l=0,u=a.length;l=0?(r.url=e,[]):(n=d3.selectAll(e),n.size()?n:(e.indexOf(".")>=0&&(r.url=e),[])):e}},{}],88:[function(e,t,r){var n,a;n=e("../../../util/copy.coffee"),a=e("../../../array/update.coffee"),t.exports=function(e,t,r){return t.process===Array?a(n(t.value),r):"object"==typeof t.process&&"string"==typeof r?t.process[r]:"function"==typeof t.process?t.process(r,e,t):r}},{"../../../array/update.coffee":35,"../../../util/copy.coffee":207}],89:[function(e,t,r){var n;n=e("../../../client/css.coffee"),t.exports=function(e,t,r){return e===!1||e.indexOf("fa-")<0||0===e.indexOf("fa-")&&n("font-awesome")?e:r.fallback}},{"../../../client/css.coffee":36}],90:[function(e,t,r){t.exports=function(e,t){var r,n,a,o,i,s,l,u,c,f,d,p,h;if("string"==typeof e){for(e=e.split(" "),r=n=0,i=e.length;n=0?(v=e.format.locale.value.error.accepted,f=e.format.locale.value.visualization[e.type.value]||e.type.value,i.warning(a(v,g,s,f,h),s)):(v=e.format.locale.value.dev.accepted,i.warning(a(v,g,l,h),s))}return!c}},{"../../array/contains.coffee":33,"../../string/format.js":173,"../../string/list.coffee":174,"../console/print.coffee":52}],92:[function(e,t,r){t.exports=function(e){var t;return t=["auto","optimizeSpeed","crispEdges","geometricPrecision"],t.indexOf(e)>=0||(e="crispEdges"),{accepted:t,value:e}}},{}],93:[function(e,t,r){var n,a;a=e("../../object/validate.coffee"),n=function(e,t){var r;e.changed&&(e.changed=!1),"draw"===t&&(e.frozen=!1,e.update=!0,e.first=!1);for(r in e)r.indexOf("d3plus")<0&&a(e[r])&&n(e[r],r)},t.exports=n},{"../../object/validate.coffee":172}],94:[function(e,t,r){var n,a,o,i,s,l,u,c,f;n=e("../../util/copy.coffee"),a=e("../../util/d3selection.coffee"),f=e("../../object/validate.coffee"),o=e("../../object/merge.coffee"),i=e("../console/print.coffee"),s=e("./process/detect.coffee"),l=e("./rejected.coffee"),u=e("../../string/format.js"),c=e("../../array/update.coffee"),t.exports=function(e,t,r,d,p){var h,v,g,m,y,x,b,w,_,k,z,A,j,M;if(A="value"!==d&&d&&d!==t?'"'+d+'" '+e.format.locale.value.dev.of+" ."+t+"()":"."+t+"()",h="value"===d&&"accepted"in r?r.accepted:f(r[d])&&"accepted"in r[d]?r[d].accepted:[p],!l(e,h,p,t,A)){if(f(r[d])&&"value"in r[d]&&(k=d,r=r[d],d="value"),"value"===d&&"process"in r&&(p=s(e,r,p)),r[d]instanceof Array||r[d]!==p||void 0===p){if(r.changed=!0,r.loaded&&(r.loaded=!1),"history"in e&&"draw"!==t&&(v=n(r),v.method=t,e.history.chain.push(v)),r.previous=r[d],"id"in e&&"value"===d&&"nesting"in r)if("id"!==t){if("object"!=typeof r.nesting&&(r.nesting={}),f(p)){for(x in p)"string"==typeof p[x]&&(p[x]=[p[x]]);r.nesting=o(r.nesting,p),e.id.value in r.nesting||(r.nesting[e.id.value]=p[d3.keys(p)[0]])}else p instanceof Array?r.nesting[e.id.value]=p:r.nesting[e.id.value]=[p];r[d]=r.nesting[e.id.value][0]}else p instanceof Array?(r.nesting=p,"depth"in e&&e.depth.value=e.id.nesting.length?e.depth.value=e.id.nesting.length-1:p<0?e.depth.value=0:e.depth.value=p,e.id.value=e.id.nesting[e.depth.value],"object"==typeof e.text.nesting&&(_=e.text.nesting[e.id.value],_&&(e.text.nesting[e.id.value]="string"==typeof _?[_]:_,e.text.value=_ instanceof Array?_[0]:_))):f(r[d])&&f(p)?r[d]=o(r[d],p):r[d]=p;"value"===d&&r.global&&(y=r[d].length>0,b=k||d,b in e&&(y&&e.data[b].indexOf(t)<0||!y&&e.data[b].indexOf(t)>=0)&&(e.data[b]=c(e.data[b],t))),"value"===d&&r.dataFilter&&e.data&&e.data.filters.indexOf(t)<0&&e.data.filters.push(t),e.dev.value&&r.changed&&void 0!==r[d]&&(w=r[d]instanceof Array&&r[d].length>10,m=a(r[d]),j="function"==typeof r[d],M=w||m||j?null:"string"==typeof r[d]?r[d]:JSON.stringify(r[d]),null!==M&&M.length<260?(z=e.format.locale.value.dev.setLong,i.log(u(z,A,'"'+M+'"'))):(z=e.format.locale.value.dev.set,i.log(u(z,A))))}else z=e.format.locale.value.dev.noChange,e.dev.value&&i.comment(u(z,A));"value"===d&&r.callback&&!r.url&&(g="function"==typeof r.callback?r.callback:r.callback.value,g&&g(p,e.self))}}},{"../../array/update.coffee":35,"../../object/merge.coffee":171,"../../object/validate.coffee":172,"../../string/format.js":173,"../../util/copy.coffee":207,"../../util/d3selection.coffee":208,"../console/print.coffee":52,"./process/detect.coffee":88,"./rejected.coffee":91}],95:[function(e,t,r){var n=e("../console/print.coffee"),a=e("../../string/format.js");t.exports=function(e){if(e.dev.value){var t="analyzing edges list";n.time(t)}var r=e.types[e.type.value].requirements;r instanceof Array||(r=[r]);var o=r.indexOf("nodes")>=0&&!e.nodes.value;if(o){e.nodes.value=[];var i=[];e.nodes.changed=!0}e.edges.value.forEach(function(t){["source","target"].forEach(function(r){var n=typeof t[e.edges[r]];if("object"!==n)if("number"!==n||o||"number"===e.data.keys[e.id.value])if(o&&i.indexOf(t[e.edges[r]])>=0)t[e.edges[r]]=e.nodes.value.filter(function(n){return n[e.id.value]===t[e.edges[r]]})[0];else{var a={};a[e.id.value]=t[e.edges[r]],t[e.edges[r]]=a}else t[e.edges[r]]=e.nodes.value[t[e.edges[r]]];var s=t[e.edges[r]];o&&i.indexOf(s[e.id.value])<0&&(i.push(s[e.id.value]),e.nodes.value.push(s))}),"keys"in e.data||(e.data.keys={}),e.id.value in e.data.keys||(e.data.keys[e.id.value]=typeof t[e.edges.source][e.id.value])}),e.edges.value=e.edges.value.filter(function(t){var r=t[e.edges.source][e.id.value],o=t[e.edges.target][e.id.value];if(r===o){var i=e.format.locale.value.dev.sameEdge;return n.warning(a(i,'"'+r+'"'),"edges"),!1}return!0}),e.edges.linked=!0,e.dev.value&&n.timeEnd(t)}},{"../../string/format.js":173,"../console/print.coffee":52}],96:[function(e,t,r){var n=e("./hideElement.js");t.exports=function(e){function t(e,t){[].forEach.call(t.attributes,function(t){if(/^data-/.test(t.name)){var r=t.name.substr(5).replace(/-(.)/g,function(e,t){return t.toUpperCase()});e[r]=t.value}}),r.forEach(function(r){null!==t.getAttribute(r)&&(e[r]=t.getAttribute(r))})}var r=[e.color.value,e.icon.value,e.keywords.value,e.alt.value,"style"];e.text.value||e.self.text("text"),r=r.concat(e.id.nesting),e.self.data({element:e.data.value});var a=e.data.element.value.node().tagName.toLowerCase(),o=e.data.element.value.attr("type"),i=[];if("select"===a){var s=e.data.element.value.node().id;s&&e.self.container({id:s}),e.data.element.value.selectAll("option").each(function(r,n){var a={};if(a.text=d3.select(this).text(),t(a,this),i.push(a),this.selected)for(var n=e.id.nesting.length-1;n>=0;n--){var o=e.id.nesting[n];if(o in a){e.self.focus(a[o]);break}}})}else if("input"===a&&"radio"===o){var l=e.data.element.value.node().getAttribute("name");l&&e.self.container({id:l}),e.data.element.value.each(function(r,a){var o={};t(o,this);var s=o[e.id.value]||this.id||!1;if(s&&isNaN(parseFloat(s))){var l=d3.select("label[for="+s+"]");l.empty()||(o.text=l.html(),l.call(n))}i.push(o),this.checked&&e.self.focus(o[e.id.value])})}!e.focus.value.length&&i.length&&(e.data.element.value.node().selectedIndex=0,e.self.focus(i[0][e.id.value]));var u=d3.select("legend[for="+e.container.id+"]");u.empty()||(e.self.title(u.html()),u.call(n));var c=!!e.container.value&&e.container.value.node().tagName.toLowerCase();return e.container.value!==!1&&"body"!==c||(e.container.value=d3.select(e.data.element.value.node().parentNode)),e.data.element.value.call(n),i}},{"./hideElement.js":97}],97:[function(e,t,r){t.exports=function(e){e.style("position","absolute","important").style("clip","rect(1px 1px 1px 1px)","important").style("clip","rect(1px, 1px, 1px, 1px)","important").style("width","1px","important").style("height","1px","important").style("margin","-1px","important").style("padding","0","important").style("border","0","important").style("overflow","hidden","important")}},{}],98:[function(e,t,r){var n=e("../console/print.coffee");t.exports=function(e){if("network"===e.type.value){if(e.dev.value){var t="analyzing node positions";n.time(t)}var r=e.nodes.value.filter(function(e){return"number"==typeof e.x&&"number"==typeof e.y}).length;if(r===e.nodes.value.length)e.nodes.positions=!0;else{var a=d3.layout.force().size([e.width.viz,e.height.viz]).nodes(e.nodes.value).links(e.edges.value),o=e.edges.strength.value;o&&("string"==typeof o?a.linkStrength(function(e){return e[o]}):a.linkStrength(o));var i=50,s=.01;a.start();for(var l=i;l>0&&(a.tick(),!(a.alpha()n;c=1<=n?++r:--r)a.push(function(){var t,r,n;for(n=[],r=0,t=e.length;rw;d=0<=w?++v:--v){for(i=[function(){var e,t,n;for(n=[],b=e=0,t=r;0<=t?et;b=0<=t?++e:--e)n.push(1);return n}()],f=[0],p=m=0,_=t.maxDegree;0<=_?m<_:m>_;p=0<=_?++m:--m)(d&1<0&&(i.push(o[p]),f.push(p+1));a=n.transpose(i),h=f.length,l=n.dot(n.dot(n.inv(n.dot(i,a)),i),j),M=n.dot(a,l),k=n.sub(j,M),A=n.dot(k,k),z=A/(r-h),g=-.5*r*Math.log(2*Math.PI)-.5*r*Math.log(z)-A/(2*z),u=-2*g+h*(Math.log(r)-Math.log(2*Math.PI)),ul;t=0<=l?++s:--s)o=n[t]-a[t],i+=o*o;return i},i=function(){var r,n,o;for(o=[],a=r=0,n=e.length;0<=n?rn;a=0<=n?++r:--r)o.push(p(a,u[a][t-1]));return o}(),f=function(e,t){return Math.max(p(e,t),i[t])},s=function(e){var r,n,a,o,i;for(o=0,i=u[e],n=0,a=i.length;nr;a=0<=r?++t:--t)n.push(s(a));return n}(),d=function(){var n,i,s,c,f,d;for(d=[],a=n=0,c=e.length;0<=c?nc;a=0<=c?++n:--n){for(r=0,f=u[a],i=0,s=f.length;it.data.large;if(t.draw.timing=t.draw.first||r||u?0:t.timing.ui,t.data.value instanceof Array){if(t.dev.value&&f.group('drawing "'+t.type.value+'"'),t.data.changed&&(t.data.cache={},i(t,"data"),o(t)),t.data.viz=l(t),t.data.sort.value&&(t.data.changed||t.order.changed||t.order.sort.changed)&&n(t.data.viz,t.order.value||t.text.value,t.order.sort.value,t.color.value,t),t.focus.value===!1&&["auto","button"].indexOf(t.type.value)<0){var a=t.data.element.value;if(a&&"select"===a.node().tagName.toLowerCase()){var d=a.property("selectedIndex");d=d<0?0:d;var p=a.selectAll("option")[0][d],h=p.getAttribute("data-"+t.id.value)||p.getAttribute(t.id.value);h&&(t.focus.value=h)}t.focus.value===!1&&t.data.viz.length&&(t.focus.value=t.data.viz[0][t.id.value]),t.dev.value&&t.focus.value!==!1&&f.log('"value" set to "'+t.focus.value+'"')}var v=function(e,r){r="number"!=typeof r?1===t.id.nesting.length?0:t.id.nesting.length-1:r;var n=t.id.nesting[r];return r>0&&(!(n in e)||e[n]instanceof Array)?v(e,r-1):n};if(t.data.changed){"auto"===t.search.value?t.data.viz.length>10?(t.search.enabled=!0,t.dev.value&&f.log("Search enabled.")):(t.search.enabled=!1,t.dev.value&&f.log("Search disabled.")):t.search.enabled=t.search.value;var g=t.data.element.value?t.data.element.value.node().tagName.toLowerCase():"";if(t.data.element.value&&"select"===g){var m=[];for(var y in t.data.nested.all)m=m.concat(t.data.nested.all[y]);options=t.data.element.value.selectAll("option").data(m,function(e){var t=!!e&&v(e);return!!(e&&t in e)&&e[t]}),options.exit().remove(),options.enter().append("option"),options.each(function(e){var r=v(e),n=r===t.id.value?t.text.value||t.id.value:t.text.nesting!==!0&&r in t.text.nesting?t.text.nesting[r]:r;for(var a in e)"object"!=typeof e[a]&&(a===n&&d3.select(this).html(e[a]),["alt","value"].indexOf(a)>=0?d3.select(this).attr(a,e[a]):d3.select(this).attr("data-"+a,e[a]));e[r]===t.focus.value?this.selected=!0:this.selected=!1})}}else if(t.focus.changed&&t.data.element.value){var x=t.data.element.value.node().tagName.toLowerCase();if("select"===x)t.data.element.value.selectAll("option").each(function(e){e[v(e)]===t.focus.value?this.selected=!0:this.selected=!1});else{var x=t.data.element.value.attr("type").toLowerCase();"radio"===x&&t.data.element.value.each(function(e){ +this.value===t.focus.value?this.checked=!0:this.checked=!1})}}if("auto"!==t.type.value){if(!t.container.ui){t.container.ui=t.container.value.selectAll("div#d3plus_"+t.type.value+"_"+t.container.id).data(["container"]);var b=t.data.element.value?t.data.element.value[0][0]:null;if(b)if(b.id)b="#"+b.id;else{var w=b.getAttribute(t.id.value)?t.id.value:"data-"+t.id.value;b=b.getAttribute(w)?"["+w+"="+b.getAttribute(w)+"]":null}t.container.ui.enter().insert("div",b).attr("id","d3plus_"+t.type.value+"_"+t.container.id).style("position","relative").style("overflow","visible").style("vertical-align","top")}t.container.ui.style("display",t.ui.display.value),t.container.ui.transition().duration(t.draw.timing).style("margin",t.ui.margin.css);var _=t.container.ui.selectAll("div.d3plus_title").data(t.title.value?[t.title.value]:[]);_.enter().insert("div","#d3plus_"+t.type.value+"_"+t.container.id).attr("class","d3plus_title").style("display","inline-block"),_.style("color",t.font.color).style("font-family",t.font.family.value).style("font-size",t.font.size+"px").style("font-weight",t.font.weight).style("padding",t.ui.padding.css).style("border-color","transparent").style("border-style","solid").style("border-width",t.ui.border+"px").text(String).each(function(e){t.margin.left=this.offsetWidth})}if(t.data.value.length){var k=t.format.locale.value.visualization[t.type.value];t.dev.value&&f.time("drawing "+k),t.types[t.type.value](t),t.dev.value&&f.timeEnd("drawing "+k)}else!t.data.url||t.data.loaded&&!t.data.stream||s(t,"data",t.self.draw);t.dev.value&&f.timeEnd("total draw time"),c(t)}},a(t,{active:e("./methods/active.coffee"),alt:e("./methods/alt.coffee"),color:e("./methods/color.coffee"),config:e("./methods/config.coffee"),container:e("./methods/container.coffee"),data:e("./methods/data.js"),depth:e("./methods/depth.coffee"),dev:e("./methods/dev.coffee"),draw:e("./methods/draw.js"),focus:e("./methods/focus.coffee"),font:e("./methods/font.coffee"),format:e("./methods/format.coffee"),height:e("./methods/height.coffee"),history:e("./methods/history.coffee"),hover:e("./methods/hover.coffee"),icon:e("./methods/icon.coffee"),id:e("./methods/id.coffee"),keywords:e("./methods/keywords.coffee"),margin:e("./methods/margin.coffee"),open:e("./methods/open.coffee"),order:e("./methods/order.coffee"),remove:e("./methods/remove.coffee"),search:e("./methods/search.coffee"),select:e("./methods/select.coffee"),selectAll:e("./methods/selectAll.coffee"),text:e("./methods/text.coffee"),timing:e("./methods/timing.coffee"),title:e("./methods/title.coffee"),type:e("./methods/type.coffee"),ui:e("./methods/ui.coffee"),width:e("./methods/width.coffee")}),t.self}},{"../array/sort.coffee":34,"../client/ie.js":37,"../core/console/print.coffee":52,"../core/data/format.js":56,"../core/data/keys.coffee":58,"../core/data/load.coffee":59,"../core/fetch/data.js":64,"../core/methods/attach.coffee":80,"../core/methods/reset.coffee":93,"./methods/active.coffee":105,"./methods/alt.coffee":106,"./methods/color.coffee":107,"./methods/config.coffee":108,"./methods/container.coffee":109,"./methods/data.js":110,"./methods/depth.coffee":111,"./methods/dev.coffee":112,"./methods/draw.js":113,"./methods/focus.coffee":114,"./methods/font.coffee":115,"./methods/format.coffee":116,"./methods/height.coffee":117,"./methods/history.coffee":118,"./methods/hover.coffee":119,"./methods/icon.coffee":120,"./methods/id.coffee":121,"./methods/keywords.coffee":122,"./methods/margin.coffee":123,"./methods/open.coffee":124,"./methods/order.coffee":125,"./methods/remove.coffee":126,"./methods/search.coffee":127,"./methods/select.coffee":128,"./methods/selectAll.coffee":129,"./methods/text.coffee":130,"./methods/timing.coffee":131,"./methods/title.coffee":132,"./methods/type.coffee":133,"./methods/ui.coffee":134,"./methods/width.coffee":135,"./types/auto.js":136,"./types/button/button.coffee":137,"./types/drop/drop.coffee":142,"./types/toggle.js":159}],105:[function(e,t,r){var n;n=e("../../core/methods/filter.coffee"),t.exports={accepted:[!1,Array,Function,Number,String],value:!1}},{"../../core/methods/filter.coffee":81}],106:[function(e,t,r){var n;n=e("../../core/methods/filter.coffee"),t.exports={accepted:[!1,Array,Function,Object,String],mute:n(!0),solo:n(!0),value:"alt"}},{"../../core/methods/filter.coffee":81}],107:[function(e,t,r){t.exports={accepted:[String],value:"color"}},{}],108:[function(e,t,r){t.exports={accepted:[Object],objectAccess:!1,process:function(e,t){var r,n;for(r in e)n=e[r],r in t.self&&t.self[r](n);return e},value:{}}},{}],109:[function(e,t,r){var n;n=e("../../util/d3selection.coffee"),t.exports={accepted:[!1,Array,Object,String],element:!1,id:"default",process:function(e){return e===!1?d3.select("body"):n(e)?e:e instanceof Array?d3.select(e[0][0]):(this.selector=e,d3.select(e))},value:d3.select("body")}},{"../../util/d3selection.coffee":208}],110:[function(e,t,r){var n=e("../../util/d3selection.coffee"),a=e("../../core/methods/process/data.coffee");t.exports={accepted:[!1,Array,Function,String],delimiter:{accepted:[String],value:"|"},element:{process:function(e,t){var r=!1;return n(e)?r=e:"string"!=typeof e||d3.select(e).empty()||(r=d3.select(e)),r&&t.self.container(d3.select(r.node().parentNode)),r},value:!1},filetype:{accepted:[!1,"json","xml","html","csv","dsv","tsv","txt"],value:!1},filters:[],large:400,mute:[],process:function(e,t){return"default"===t.container.id&&e.length&&t.self.container({id:"default"+e.length}),a(e,t,this)},solo:[],sort:{accepted:[Boolean],value:!1},value:!1}},{"../../core/methods/process/data.coffee":87,"../../util/d3selection.coffee":208}],111:[function(e,t,r){t.exports={accepted:[Number],value:0}},{}],112:[function(e,t,r){t.exports={accepted:[Boolean],value:!1}},{}],113:[function(e,t,r){var n=e("../../util/d3selection.coffee"),a=e("../../core/parse/hideElement.js"),o=e("../../core/parse/element.js"),i=e("../../core/console/print.coffee"),s=e("../../string/format.js");t.exports={accepted:[void 0,Function],first:!0,frozen:!1,process:function(e,t){if(this.initialized===!1)return this.initialized=!0,e;if(!t.data.value||t.data.value instanceof Array&&!n(t.data.value)?t.data.element.value&&t.data.element.value.call(a):t.data.value=o(t),void 0===e&&"function"==typeof this.value&&(e=this.value),t.container.value===!1){var r=t.format.locale.value.dev.setContainer;i.warning(r,"container")}else if(t.container.value.empty()){var r=t.format.locale.value.dev.noContainer,l=t.container.selector||"";i.warning(s(r,'"'+l+'"'),"container")}else t.dev.value&&i.time("total draw time"),t.container.value.call(t.self);if("function"==typeof e&&t.history.chain.length){var u={};t.history.chain.forEach(function(e){var t=e.method;delete e.method,u[t]=e}),e(u),t.history.chain=[]}return e},update:!0,value:void 0}},{"../../core/console/print.coffee":52,"../../core/parse/element.js":96,"../../core/parse/hideElement.js":97,"../../string/format.js":173,"../../util/d3selection.coffee":208}],114:[function(e,t,r){t.exports={accepted:[!1,Number,String],deprecates:"highlight",process:function(e,t){var r,n,a,o,i,s,l,u,c,f;if(n=t.data.element.value,n&&["string","number"].indexOf(typeof e)>=0)if(a=n.node().tagName.toLowerCase(),o=n.attr("type"),"select"===a)for(f=n.selectAll("option"),i=s=0,u=f.length;s=0})),t.dev.value&&s.time("update"),u.classed("d3plus_button_active",function(e){return t.focus.value===e[t.id.value]}),t.draw.timing?u.transition().duration(t.draw.timing).call(a,t).call(l,t):u.call(a,t).call(l,t),u.call(o,t).call(i,t),t.dev.value&&s.timeEnd("update"),r.exit().remove()}},{"../../../core/console/print.coffee":52,"./functions/color.coffee":138,"./functions/icons.js":139,"./functions/mouseevents.coffee":140,"./functions/style.js":141}],138:[function(e,t,r){t.exports=function(t,r){var n,a,o;return n=e("../../../../color/legible.coffee"),a=e("../../../../color/lighter.coffee"),o=e("../../../../color/text.coffee"),t.style("background-color",function(e){var t;return t=r.focus.value===e[r.id.value]?r.ui.color.secondary.value:r.ui.color.primary.value,r.hover.value===e[r.id.value]&&(t=d3.rgb(t).darker(.15).toString()),t}).style("color",function(e){var t,a,i,s;return s=r.focus.value===e[r.id.value]?.75:1,i=e[r.icon.value]&&r.data.viz.length0){var f=t.ui.padding;f=3===i.length?f.top+"px "+(2*f.right+l)+"px "+f.bottom+"px "+(2*f.left+l)+"px":i.indexOf("icon")>=0&&!a||i.indexOf("selected")>=0&&a?f.top+"px "+f.right+"px "+f.bottom+"px "+(2*f.left+l)+"px":f.top+"px "+(2*f.right+l)+"px "+f.bottom+"px "+f.left+"px",c.style("padding",f)}else c.style("padding",t.ui.padding.css);if("number"==typeof t.width.value){var d=t.width.value;d-=parseFloat(c.style("padding-left"),10),d-=parseFloat(c.style("padding-right"),10),d-=2*t.ui.border,d+="px"}else var d="auto";c.style("width",d)})}},{"../../../../client/prefix.coffee":39,"../../../../client/rtl.coffee":40}],140:[function(e,t,r){t.exports=function(t,r,n){var a,o;return n=e("./color.coffee"),a=e("../../../../client/pointer.coffee"),o=e("../../../../client/ie.js"),t.on(a.over,function(e,t){return r.self.hover(e[r.id.value]),o||!r.draw.timing?d3.select(this).style("cursor","pointer").call(n,r):d3.select(this).style("cursor","pointer").transition().duration(r.timing.mouseevents).call(n,r)}).on(a.out,function(e){return r.self.hover(!1),o||!r.draw.timing?d3.select(this).style("cursor","auto").call(n,r):d3.select(this).style("cursor","auto").transition().duration(r.timing.mouseevents).call(n,r)}).on(a.click,function(e){return r.focus.value!==!1?r.self.focus(e[r.id.value]).draw():r.focus.callback?r.focus.callback(e,r.self):void 0})}},{"../../../../client/ie.js":37,"../../../../client/pointer.coffee":38,"./color.coffee":138}],141:[function(e,t,r){t.exports=function(e,t){e.style("position","relative").style("margin",t.ui.margin.css).style("display",t.ui.display.value).style("border-style","solid").style("border-width",t.ui.border+"px").style("font-family",t.font.family.value).style("font-size",t.font.size+"px").style("font-weight",t.font.weight).style("letter-spacing",t.font.spacing+"px")}},{}],142:[function(e,t,r){t.exports=function(t){var r,n,a,o,i,s,l,u,c,f,d;return a=e("./functions/element.coffee"),o=e("./functions/keyboard.coffee"),d=e("./functions/window.js"),f=e("./functions/width.js"),r=e("./functions/button.js"),l=e("./functions/selector.js"),u=e("./functions/title.js"),s=e("./functions/search.js"),i=e("./functions/list.js"),n=e("./functions/data.js"),c=e("./functions/update.js"),t.margin.top=0,t.margin.title=0,a(t),o(t),d(t),f(t),r(t),l(t),u(t),s(t),i(t),n(t),c(t)}},{"./functions/button.js":145,"./functions/data.js":146,"./functions/element.coffee":147,"./functions/keyboard.coffee":150,"./functions/list.js":151,"./functions/search.js":153,"./functions/selector.js":154,"./functions/title.js":155,"./functions/update.js":156,"./functions/width.js":157,"./functions/window.js":158}],143:[function(e,t,r){t.exports=function(e,t,r){var n=[],r=r||e.active.value;if(r instanceof Array)for(var a=0;a=0}},{}],144:[function(e,t,r){var n=e("../../../../core/console/print.coffee");t.exports=function(e){e.dev.value&&n.time("rotating arrow");var t="❯"===e.icon.drop.value?90:0;if(e.open.value!=e.open.flipped.value)var r=180+t;else var r=t;e.container.button.icon({select:{opacity:e.open.value?.5:1,rotate:r}}).draw(),e.dev.value&&n.timeEnd("rotating arrow")}},{"../../../../core/console/print.coffee":52}],145:[function(e,t,r){var n=e("../../../../util/copy.coffee"),a=e("../../../../client/pointer.coffee"),o=e("../../../form.js"),i=e("../../../../core/console/print.coffee");t.exports=function(e){if("button"in e.container||(e.dev.value&&i.time("creating main button"),e.container.button=o().container(e.container.ui).type("button").ui({margin:0}),e.dev.value&&i.timeEnd("creating main button")),e.focus.changed||e.data.changed||e.depth.changed){var t=e.depth.value,r=n(e.data.value.filter(function(r){for(var n=!1,a=0;a=0&&0===u.indexOf(e.search.term))i.push(t),n=!0;else if(u.indexOf(e.search.term)>=0)s.push(t),n=!0;else{var c=a(u).split("_");for(var f in c){if(n)break;for(var d in r)if(0===c[f].indexOf(r[d])){l.push(t),n=!0;break}}}}})}),e.data.filtered=d3.merge([i,s,l]),e.data.filtered.forEach(function(e,t){e.d3plus_order=t}),e.data.changed=!0,e.data.lastFilter="search",0===e.data.filtered.length){var c={},f=e.format.value(e.format.locale.value.ui.noResults);c[e.text.value||e.id.value]=n(f,'"'+e.search.term+'"'),e.data.filtered=[c]}}else e.data.filtered=e.data.viz,e.data.changed="viz"!==e.data.lastFilter,e.data.lastFilter="viz",e.id.nesting.length>1&&e.depth.valuee.height.max&&(t=e.height.max),e.self.height({secondary:t})}},{}],149:[function(e,t,r){var n,a,o,i;n=e("./active.js"),a=e("../../../../util/copy.coffee"),o=e("../../../form.js"),i=e("../../../../core/console/print.coffee"),t.exports=function(e){var t,r,s;e.open.value&&(e.dev.value&&i.time("updating list items"),"items"in e.container||(e.container.items=o().container(e.container.list).type("button").ui({border:0,display:"block",margin:0}).width(!1)),r=e.draw.timing?e.data.large:1,s=a(e.order),s.value=e.search.term.length?"d3plus_order":e.order.value,t=e.depth.value===e.id.nesting.length-1,(e.focus.changed||e.container.items.focus()===!1)&&e.container.items.focus(e.focus.value,function(t){var r,a,o,i;a=e.data.filtered.filter(function(r){return r[e.id.value]===t})[0],e.depth.value=0)return s===!1?s=0:38===u?e.open.value&&(s<=0?s=e.data.filtered.length-1:s-=1):40===u&&e.open.value&&(s>=e.data.filtered.length-1?s=0:s+=1),o="boolean"!=typeof e.hover.value?e.data.filtered[s][e.id.value]:e.focus.value,e.self.hover(o).open(!0).draw();if(13===u)return"boolean"!=typeof e.hover.value?(r=e.data.filtered.filter(function(t){return t[e.id.value]===e.hover.value})[0],n=e.depth.value,ne.height.secondary&&(e.container.listHeight=e.height.secondary,s=!0),t&&e.container.selector.style("display","none"),e.dev.value&&n.timeEnd("calculating height"),s){e.dev.value&&n.time("calculating scroll position");var l=e.container.list.select("div").selectAll("div.d3plus_node"),u=l[0][0],c="boolean"!=typeof e.hover.value?e.hover.value:e.focus.value;l.each(function(t,r){t[e.id.value]===c&&(u=this)});var t=!1;"none"===e.container.selector.style("display")&&(t=!0,e.container.selector.style("display","block"));var f=u.offsetTop,d=u.offsetHeight||u.getBoundingClientRect().height,p=e.container.list.property("scrollTop");t&&e.container.selector.style("display","none"),t||e.data.changed||e.depth.changed?e.container.listScroll=f:(e.container.listScroll=p,fp+e.height.secondary-e.search.height&&(e.container.listScroll=f-(e.height.secondary-d-e.search.height))),e.dev.value&&n.timeEnd("calculating scroll position")}else e.container.listScroll=0}else e.container.listScroll=e.container.list.property("scrollTop"),e.container.listHeight=0}},{"../../../../core/console/print.coffee":52}],153:[function(e,t,r){var n=e("../../../../client/prefix.coffee"),a=e("../../../../core/console/print.coffee");t.exports=function(t){function r(e){e.style("padding",t.ui.padding.css).style("display","block").style("background-color",d3.rgb(t.ui.color.primary.value).darker(.15).toString()); +}function o(e){var r=t.width.secondary-2*t.ui.padding.left-2*t.ui.padding.right+2*t.ui.border;e.style("padding",t.ui.padding.left/2+t.ui.padding.right/2+"px").style("width",r+"px").style("border-width","0px").style("font-family",t.font.secondary.family.value).style("font-size",t.font.secondary.size+"px").style("font-weight",t.font.secondary.weight).style("text-align",t.font.secondary.align).style("outline","none").style(n()+"border-radius","0").attr("placeholder",t.format.value(t.format.locale.value.method.search))}t.dev.value&&a.time("creating search");var i=e("./data.js"),s=e("./items.coffee"),l=e("./update.js");t.container.search=t.container.selector.selectAll("div.d3plus_drop_search").data(t.search.enabled?["search"]:[]),t.draw.timing?(t.container.search.transition().duration(t.draw.timing).call(r),t.container.search.select("input").transition().duration(t.draw.timing).call(o)):(t.container.search.call(r),t.container.search.select("input").call(o)),t.container.search.enter().insert("div","#d3plus_drop_list_"+t.container.id).attr("class","d3plus_drop_search").attr("id","d3plus_drop_search_"+t.container.id).call(r).append("input").attr("id","d3plus_drop_input_"+t.container.id).style("-webkit-appearance","none").call(o),t.container.search.select("input").on("keyup."+t.container.id,function(e){var r=this.value;t.search.term!==r&&(t.search.term=r,i(t),s(t),l(t))}),t.container.search.exit().remove();var u=t.container.selector.style("display");t.container.selector.style("display","block"),t.search.height=t.search.enabled?t.container.search.node().offsetHeight||t.container.search.node().getBoundingClientRect().height:0,t.container.selector.style("display",u),t.search.enabled&&(t.margin.title+=t.search.height),t.dev.value&&a.timeEnd("creating search")}},{"../../../../client/prefix.coffee":39,"../../../../core/console/print.coffee":52,"./data.js":146,"./items.coffee":149,"./update.js":156}],154:[function(e,t,r){t.exports=function(e){e.container.selector=e.container.ui.selectAll("div.d3plus_drop_selector").data(["selector"]),e.container.selector.enter().append("div").attr("class","d3plus_drop_selector").style("position","absolute").style("top","0px").style("z-index","-1").style("overflow","hidden"),e.container.selector.style("padding",e.ui.border+"px")}},{}],155:[function(e,t,r){var n=e("../../../../client/pointer.coffee"),a=e("../../../../color/lighter.coffee"),o=e("../../../../core/console/print.coffee"),i=e("../../../../color/text.coffee");t.exports=function(e){function t(t){t.style("padding",e.ui.padding.css).style("display","block").style("background-color",e.ui.color.secondary.value).style("font-family",e.font.secondary.family.value).style("font-size",e.font.secondary.size+"px").style("font-weight",e.font.secondary.weight).style("text-align",e.font.secondary.align).style("color",i(e.ui.color.secondary.value))}function r(t){if(!t.empty()){var r=0===e.icon.back.value.indexOf("fa-")?" fa "+e.icon.back.value:"";r="d3plus_drop_back"+r;var n=0===e.icon.back.value.indexOf("fa-")?"":e.icon.back.value;t.style("position","absolute").attr("class",r).style("top",e.ui.padding.top+e.font.secondary.size/2/2.5+"px").html(n)}}function s(t){var r=u?e.focus.value:e.format.locale.value.ui.back;t.text(e.format.value(r)).style("padding","0px "+(e.ui.padding.left+e.ui.padding.right)+"px")}if(e.open.value){e.dev.value&&o.time("creating title and back button");var l=1===e.id.solo.value.length&&e.depth.value>0,u=l,c=e.container.button.data(Object).viz[0];u=!0;for(var f=0;f=0&&(t=r.parentNode),t&&r&&!n(e.container.ui,t)&&(e.open.value||e.hover.value)&&e.self.open(!1).hover(!1).draw()});try{var r=window.parent.location.host===window.location.host}catch(e){var r=!1}r&&t.self!==window.top&&a(e,t.parent)};t.exports=a},{"../../../../util/child.coffee":205}],159:[function(e,t,r){var n=e("../form.js");t.exports=function(e){"buttons"in e.container||(e.container.buttons=n().container(e.container.ui).type("button"));var t=e.data.viz.length,r=!!e.width.value&&e.width.value/t,a=e.container.ui.selectAll("div.d3plus_toggle").data(e.data.viz,function(t){return t[e.id.value]});a.exit().remove(),a.enter().append("div").attr("class","d3plus_toggle").style("display","inline-block").style("vertical-align","top"),a.order().each(function(t){"form"in t.d3plus||(t.d3plus.form=n().container(d3.select(this)));var a=e.id.nesting.length>e.depth.value?e.id.nesting[e.depth.value+1]:e.id.value;t[a]instanceof Array?t.d3plus.form.container({id:e.container.id+"_"+t[e.id.value]}).data(t[a]).id(e.id.nesting.slice(1)).type("drop"):t.d3plus.form.data([t]).id(e.id.value).type("button"),t.d3plus.form.color(e.color).focus(e.focus.value,function(t){t!==e.focus.value&&e.self.focus(t).draw()}).hover(e.hover.value).icon({select:!1,value:e.icon.value}).font(e.font).format(e.format).order(e.order).text(e.text.value).ui({border:e.ui.border,color:e.ui.color,display:"inline-block",margin:0,padding:e.ui.padding.css}).width(r).draw()}),e.data.element.value&&e.data.element.value.on("focus."+e.container.id,function(){e.self.focus(this.value).hover(this.value).draw()}).on("blur."+e.container.id,function(){e.self.hover(!1).draw()})}},{"../form.js":104}],160:[function(e,t,r){var n,a,o,i,s,l,u,c,f,d,p;d=e("simplify-js"),t.exports=function(e,t){var r,a,i,l,u,f,h,v,g,m,y,x,b,w,_,k,z,A,j,M,O,E,F,S,T,B,C,q,N,P,I,D,V,R,U,L,Y,H,X,G,J,W,Q,K,Z,$,ee,te,re,ne,ae,oe,ie,se,le,ue,ce,fe,de,pe,he,ve,ge,me,ye,xe,be;if(e.length<3)return null;if(w=[],v=.5,u=5,null==t&&(t={}),null==t.maxAspectRatio&&(t.maxAspectRatio=15),null==t.minWidth&&(t.minWidth=0),null==t.minHeight&&(t.minHeight=0),null==t.tolerance&&(t.tolerance=.02),null==t.nTries&&(t.nTries=20),null!=t.angle&&(t.angle instanceof Array?f=t.angle:"number"==typeof t.angle?f=[t.angle]:"string"!=typeof t.angle||isNaN(t.angle)||(f=[Number(t.angle)])),null==f&&(f=d3.range(-90,90+u,u)),null!=t.aspectRatio&&(t.aspectRatio instanceof Array?g=t.aspectRatio:"number"==typeof t.aspectRatio?g=[t.aspectRatio]:"string"!=typeof t.aspectRatio||isNaN(t.aspectRatio)||(g=[Number(t.aspectRatio)])),null!=t.origin&&t.origin instanceof Array&&(W=t.origin[0]instanceof Array?t.origin:[t.origin]),h=Math.abs(d3.geom.polygon(e).area()),0===h)return null;if(re=d3.extent(e,function(e){return e[0]}),Y=re[0],D=re[1],ne=d3.extent(e,function(e){return e[1]}),H=ne[0],V=ne[1],ge=Math.min(D-Y,V-H)*t.tolerance,ve=function(){var t,r,n;for(n=[],t=0,r=e.length;t0&&(ve=d(ve,ge),e=function(){var e,t,r;for(r=[],e=0,t=ve.length;e=ye&&t.vdebug&&w.push({type:"aRatio",aRatio:r});fe-O>=ye;)me=(O+fe)/2,_=me/r,xe=J[0],be=J[1],te=[[xe-me/2,be-_/2],[xe+me/2,be-_/2],[xe+me/2,be+_/2],[xe-me/2,be+_/2]],te=c(te,l,J),s(te,e)?(z=!0,C=me*_,P={cx:xe,cy:be,width:me,height:_,angle:i},O=me):(z=!1,fe=me),t.vdebug&&w.push({type:"rectangle",cx:xe,cy:be,width:me,height:_,areaFraction:me*_/h,angle:i,insidePoly:z});return[P,C,w]},p=function(e,t){var r,n;return r=t[0]-e[0],n=t[1]-e[1],r*r+n*n},l=function(e,t,r){var n,a,o,i,s;return s=t[1]a[1]||e[1]n[0]&&e[0]>a[0])&&(e[0]o)))},o=function(e,t){var r,n,a,o,i;for(o=-1,i=t.length,n=t[i-1],a=0;++oMath.max(t[0],r[0])+n||oMath.max(t[1],r[1])+n)},a=function(e,t,r,n){var a,o,i,s,l,u,c,f,d,p;return f=1e-9,s=e[0]-t[0],u=e[1]-t[1],l=r[0]-n[0],c=r[1]-n[1],i=s*c-u*l,Math.abs(i)t[f]&&yf&&(f=k[a][o],A=a,j=o);if(f<0)break;for(b in k[A])b!==j&&(b in k[j]?k[j][b]+=k[A][b]:k[j][b]=k[A][b]-2*u[j].score*u[b].score,k[b][j]=k[j][b]),delete k[b][A];for(b in k[j])b in k[A]||b===j||(k[j][b]-=2*u[A].score*u[b].score,k[b][j]=k[j][b]);for(T=u[A].nodes,x=0,_=T.length;x<_;x++)M=T[x],u[j].nodes.push(M);u[j].score+=u[A].score,t.vdebug&&v.push({type:"merge",father:j,child:A,nodes:u[j].nodes}),delete u[A],delete k[A],r+=f,y++}return l=function(){var e;e=[];for(i in u)c=u[i],e.push([i,c.nodes.length]);return e}(),l.sort(function(e,t){return t[1]-e[1]}),B=function(){var e,t,r;for(r=[],e=0,t=l.length;e=0?u=e:"share"===o?(u=0===e?0:e>=100?a.numberFormat(",f")(e):e>99?a.numberFormat(".3g")(e):a.numberFormat(".2g")(e),u+="%"):e<10&&e>-10?(s=e.toString().split("."),c=1,s.length>1&&(c=d3.min([parseFloat(s[1]).toString().length,2]),-13?(f=d3.formatPrefix(e).symbol,f=f.replace("G","B"),e=d3.formatPrefix(e).scale(e),e=a.numberFormat(".3g")(e),e=e.replace(l.format.decimal,"."),e=parseFloat(e)+"",e=e.replace(".",l.format.decimal),u=e+f):u=3===s?a.numberFormat(",f")(e):0===e?0:e===parseInt(e,10)?a.numberFormat(".2")(e):a.numberFormat(".3g")(e),u.length>2&&""+u.indexOf(".0")===u.length-2&&(u=u.slice(0,u.length-2)),i&&o&&"format"in p&&o in p.format.affixes.value?(r=p.format.affixes.value[o],r[0]+u+r[1]):u)}},{"../core/locale/languages/en_US.coffee":70}],171:[function(e,t,r){var n,a;n=e("../util/d3selection.coffee"),a=e("./validate.coffee"),t.exports=function(e,t){var r,o;return r=function(e,t,o){var i,s,l;s=[];for(i in e)l=e[i],"undefined"!=typeof l?!o&&a(l)?("object"!=typeof t[i]&&(t[i]={}),s.push(r(l,t[i],0===i.indexOf("d3plus")))):!n(l)&&l instanceof Array?s.push(t[i]=l.slice(0)):s.push(t[i]=l):s.push(void 0);return s},o={},e&&r(e,o),t&&r(t,o),o}},{"../util/d3selection.coffee":208,"./validate.coffee":172}],172:[function(e,t,r){t.exports=function(e){return e&&e.constructor===Object}},{}],173:[function(e,t,r){t.exports=function(){var e=Array.prototype.slice.call(arguments),t=e.shift();return t.unkeyed_index=0,t.replace(/\{(\w*)\}/g,function(r,n){if(""===n&&(n=t.unkeyed_index,t.unkeyed_index++),n==+n)return"undefined"!==e[n]?e[n]:r;for(var a=0;ar&&(i=e.length-r+1,e=e.slice(0,r-1),e[r-1]=n(o,i)),e.length>1&&(e[e.length-1]=t+" "+e[e.length-1]),e.join(", "))):e}},{"../core/locale/languages/en_US.coffee":70,"./format.js":173}],175:[function(e,t,r){t.exports=function(e){var t=["!","@","#","$","%","^","&","*","(",")","[","]","{","}",".",",","/","\\","|","'",'"',";",":","<",">","?","=","+"],r=[[/[\300-\306]/g,"A"],[/[\340-\346]/g,"a"],[/[\310-\313]/g,"E"],[/[\350-\353]/g,"e"],[/[\314-\317]/g,"I"],[/[\354-\357]/g,"i"],[/[\322-\330]/g,"O"],[/[\362-\370]/g,"o"],[/[\331-\334]/g,"U"],[/[\371-\374]/g,"u"],[/[\321]/g,"N"],[/[\361]/g,"n"],[/[\307]/g,"C"],[/[\347]/g,"c"]];return e+="",""+e.replace(/[^A-Za-z0-9\-_]/g,function(e){if(" "===e)return"_";if(t.indexOf(e)>=0)return"";for(var n=e,a=0;a=0?a[o]:s.indexOf(t.toLowerCase())>=0&&0!==n&&n!==e.length-1?t.toLowerCase():t.charAt(0).toUpperCase()+t.substr(1).toLowerCase()):""}))):""}},{"../core/locale/languages/en_US.coffee":70}],177:[function(e,t,r){var n,a;n=e("./foreign.coffee"),a=e("./tspan.coffee"),t.exports=function(e){e.text.html.value?n(e):a(e)}},{"./foreign.coffee":178,"./tspan.coffee":181}],178:[function(e,t,r){t.exports=function(e){var t,r,n,a,o;o=e.container.value,n=o.attr("font-family")||o.style("font-family"),t=e.align.value||o.attr("text-anchor")||o.style("text-anchor"),r=o.attr("fill")||o.style("fill"),a=o.attr("opacity")||o.style("opacity"),t="end"===t?"right":"middle"===t?"center":"left",d3.select(o.node().parentNode).append("foreignObject").attr("width",e.width.value+"px").attr("height",e.height.value+"px").attr("x","0px").attr("y","0px").append("xhtml:div").style("font-family",n).style("font-size",e.size.value[1]+"px").style("color",r).style("text-align",t).style("opacity",a).text(e.text.current)}},{}],179:[function(e,t,r){t.exports=function(e){var t,r,n,a,o,i,s,l,u,c;if(r=e.container.value,a=r.node().previousElementSibling,i=a?a.tagName.toLowerCase():"",a&&(a=d3.select(a)),e.container.x=e.x.value||parseFloat(r.attr("x"),10),e.container.y=e.y.value||parseFloat(r.attr("y"),10),a&&(e.shape.accepted.indexOf(i)>=0&&e.self.shape(i),"rect"===i?(u=parseFloat(a.attr("x"),10)||0,c=parseFloat(a.attr("y"),10)||0,e.padding.value===!1&&(t=Math.abs(u-e.container.x),t&&e.self.padding(t)),e.container.x||(e.container.x=u+e.padding.value),e.container.y||(e.container.y=c+e.padding.value),e.width.value||(l=parseFloat(a.attr("width")),e.self.width(l)),e.height.value||(n=parseFloat(a.attr("height")),e.self.height(n))):"circle"===i?(o=parseFloat(a.attr("r"),10),u=parseFloat(a.attr("cx"),10)||0,u-=o,c=parseFloat(a.attr("cy"),10)||0,c-=o,e.padding.value===!1&&(t=Math.abs(u-e.container.x),t&&e.self.padding(t)),e.container.x||(e.container.x=u+e.padding.value),e.container.y||(e.container.y=c+e.padding.value),e.width.value||e.self.width(2*o,10),e.height.value||e.self.height(2*o,10)):(e.width.value||e.self.width(500),e.height.value||e.self.height(500))),e.container.x||(e.container.x=0),e.container.y||(e.container.y=0),e.width.inner=e.width.value-2*e.padding.value,e.height.inner=e.height.value-2*e.padding.value,s=r.attr("font-size")||r.style("font-size"),s=parseFloat(s,10),e.container.fontSize=s,e.container.dy=parseFloat(r.attr("dy"),10),!e.size.value)return e.resize.value?e.self.size([4,80]):e.self.size([s/2,s])}},{}],180:[function(e,t,r){t.exports=function(e){var t;if(e.text.value||(t=e.container.value.text(),t&&(t.indexOf("tspan")>=0&&(t.replace(/\<\/tspan\>\/g," "),t.replace(/\<\/tspan\>/g,""),t.replace(/\/g,"")),t=t.replace(/(\r\n|\n|\r)/gm,""),t=t.replace(/^\s+|\s+$/g,""),e.self.text(t))),e.text.value instanceof Array?e.text.phrases=e.text.value.filter(function(e){return["string","number"].indexOf(typeof e)>=0}):e.text.phrases=[e.text.value+""],!e.align.value)return e.container.align=e.container.value.style("text-anchor")||e.container.value.attr("text-anchor")}},{}],181:[function(e,t,r){var n;n=e("../../client/rtl.coffee"),t.exports=function(e){var t,r,a,o,i,s,l,u,c,f,d,p,h,v,g,m,y,x,b,w,_,k,z,A,j,M,O,E,F,S,T;return d=function(t){var n;return n=!v||t?e.container.value.append("tspan"):e.container.value.insert("tspan","tspan"),n.attr("x",E+"px").attr("dy",r+"px").style("baseline-shift","0%").attr("dominant-baseline","alphabetic")},f=e.rotate.value===-90||90===e.rotate.value,j=f?e.height.inner:e.width.inner,s=f?e.width.inner:e.height.inner,t="circle"===e.shape.value?"middle":e.align.value||e.container.align||"start",F="end"===t||"start"===t&&n?j:"middle"===t?j/2:0,A=e.valign.value||"top",E=e.container.x+F,o=e.resize.value?e.size.value[1]:e.container.fontSize||e.size.value[0],r=e.container.dy||1.1*o,_=null,h=null,M=null,v=!1,T=0,"circle"===e.shape.value&&("middle"===A?T=s/r%1*r/2:"end"===A&&(T=s/r%1*r)),e.container.value.attr("text-anchor",t).attr("font-size",o+"px").style("font-size",o+"px").attr("x",e.container.x).attr("y",e.container.y),z=function(){if(_.remove(),v?(l++,_=e.container.value.select("tspan")):(l--,_=d3.select(e.container.value.node().lastChild)),!_.empty())return M=_.text().match(/[^\s-]+-?/g),a()},u=function(){var t;return"circle"===e.shape.value?(t=(l-1)*r+T,t>s/2&&(t+=r),2*Math.sqrt(t*(2*(j/2)-t))):j},a=function(){var t,r;return M&&M.length?(r=M.pop(),t=r.charAt(r.length-1),1===r.length&&e.text.split.value.indexOf(r)>=0?a():(e.text.split.value.indexOf(t)>=0&&(r=r.substr(0,r.length-1)),_.text(M.join(" ")+" "+r+"..."),_.node().getComputedTextLength()>u()?a():void 0)):z()},p=function(t){var r,n,a,o;if(r=_.text(),o="",v){if(o=e.text.current.charAt(e.text.current.length-h.length-1)," "===o)for(a="",n=2;" "===o;)a+=" ",o=e.text.current.charAt(e.text.current.length-h.length-n),n++;else a="";h=t+a+h,_.text(t+a+r)}else{if(o=e.text.current.charAt(h.length)," "===o)for(a="",n=1;" "===o;)a+=" ",o=e.text.current.charAt(h.length+n),n++;else a="";h+=a+t,_.text(r+a+t)}if(Math.floor(_.node().getComputedTextLength())>u()||"\n"===o)return _.text(r),r.length&&(_=d()),_.text(t),v?l--:l++},w=1,l=null,c=null,O=function(){var t,n,a,o,i,u;for(e.container.value.text("").html(""),M=e.text.words.slice(),v&&M.reverse(),h="",_=d(!0),l=w,n=0,a=M.length;ns){z();break}for(p(u),i=!0;i;){for(o=e.text.current.charAt(h.length),t=1;" "===o;)o=e.text.current.charAt(h.length+t),t++;i=e.text.split.value.indexOf(o)>=0,i&&p(o)}}return l*r>s&&z(),c=Math.abs(l-w)+1},O(),c=0,e.container.value.selectAll("tspan").each(function(){if(d3.select(this).text().length)return c++}),"circle"===e.shape.value&&(b=s-c*r,b>r&&("middle"===A?(w=(b/r/2>>0)+1,O()):"bottom"===A&&(v=!0,w=s/r>>0,O()))),c=0,e.container.value.selectAll("tspan").each(function(){if(d3.select(this).text().length)return c++}),"top"===A?S=0:(i=c*r,S="middle"===A?s/2-i/2:s-i),S-=.2*r,k="translate(0,"+S+")",180===e.rotate.value||e.rotate.value===-180?(y=e.container.x+j/2,x=e.container.y+s/2):(g=e.rotate.value<0?j:s,y=e.container.x+g/2,x=e.container.y+g/2),m="rotate("+e.rotate.value+", "+y+", "+x+")",e.container.value.attr("transform",m+k)}},{"../../client/rtl.coffee":40}],182:[function(e,t,r){var n,a,o,i;n=e("./flow.coffee"),a=e("../../font/sizes.coffee"),i=function(e){var t;e.text.phrases.length&&(e.text.current=e.text.phrases.shift()+"",e.text.words=e.text.current.match(e.text.split.break),t=e.text.current.charAt(0),t!==e.text.words[0].charAt(0)&&(e.text.words[0]=t+e.text.words[0]),e.container.value.html(""),e.resize.value?o(e):n(e))},t.exports=i,o=function(e){var t,r,o,s,l,u,c,f,d,p,h,v,g,m,y,x,b;for(b=[],c=0;cf||m>s)&&(o=Math.sqrt(s/m),x=f/d,v=d3.min([o,x]),h=d3.max([e.size.value[0],Math.floor(h*v)])),u=Math.floor(.8*l),h>u&&(h=u),d*(h/e.size.value[1])<=f?(h!==e.size.value[1]&&e.self.size([e.size.value[0],h]),n(e)):i(e)}},{"../../font/sizes.coffee":102,"./flow.coffee":177}],183:[function(e,t,r){t.exports={accepted:[!1,"start","middle","end","left","center","right"],process:function(e){var t;return t=["left","center","right"].indexOf(e),t>=0&&(e=this.accepted[t+1]),e},value:!1}},{}],184:[function(e,t,r){arguments[4][108][0].apply(r,arguments)},{dup:108}],185:[function(e,t,r){var n;n=e("../../util/d3selection.coffee"),t.exports={accepted:[!1,Array,Object,String],element:!1,id:"default",process:function(e){return e!==!1&&(n(e)?e:e instanceof Array?d3.select(e[0][0]):(this.selector=e,d3.select(e)))},value:!1}},{"../../util/d3selection.coffee":208}],186:[function(e,t,r){arguments[4][112][0].apply(r,arguments)},{dup:112}],187:[function(e,t,r){var n,a;n=e("../../core/console/print.coffee"),a=e("../../string/format.js"),t.exports={accepted:[void 0],process:function(e,t){var r,o;return this.initialized===!1?e:(t.container.value===!1?(o=t.format.locale.value.dev.setContainer,n.warning(o,"container")):t.container.value.empty()?(o=t.format.locale.value.dev.noContainer,r=t.container.selector||"",n.warning(a(o,'"'+r+'"'),"container")):(t.dev.value&&n.time("total draw time"),t.container.value.call(t.self)),e)},value:void 0}},{"../../core/console/print.coffee":52,"../../string/format.js":173}],188:[function(e,t,r){var n,a;n=e("../../core/locale/locale.coffee"),a=e("../../object/merge.coffee"),t.exports={accepted:[Function,String],locale:{accepted:function(){return d3.keys(n)},process:function(e){var t,r;return t="en_US",r=n[t],e!==t&&(r=a(r,n[e])),this.language=e,r},value:"en_US"},process:function(e,t){if(this.initialized&&"string"==typeof e)t.self.format({locale:e});else if("function"==typeof e)return e;return this.value},value:"en_US"}},{"../../core/locale/locale.coffee":79,"../../object/merge.coffee":171}],189:[function(e,t,r){t.exports={accepted:[!1,Number],value:!1}},{}],190:[function(e,t,r){arguments[4][189][0].apply(r,arguments)},{dup:189}],191:[function(e,t,r){arguments[4][112][0].apply(r,arguments)},{dup:112}],192:[function(e,t,r){t.exports={accepted:[-180,-90,0,90,180],value:0}},{}],193:[function(e,t,r){t.exports={accepted:["circle","square"],value:!1}},{}],194:[function(e,t,r){t.exports={accepted:[Array,!1],value:!1}},{}],195:[function(e,t,r){t.exports={accepted:[!1,Array,Number,String],html:{accepted:[Boolean],value:!1},init:function(e){var t;return t=this.split.value,this.split.break=new RegExp("[^\\s\\"+t.join("\\")+"]+\\"+t.join("?\\")+"?","g"),!1},split:{accepted:[Array],process:function(e){return this.break=new RegExp("[^\\s\\"+e.join("\\")+"]+\\"+e.join("?\\")+"?","g"),e},value:["-","/",";",":","&"]}}},{}],196:[function(e,t,r){t.exports={accepted:[!1,"top","middle","bottom"],value:!1}},{}],197:[function(e,t,r){arguments[4][189][0].apply(r,arguments)},{dup:189}],198:[function(e,t,r){arguments[4][189][0].apply(r,arguments)},{dup:189}],199:[function(e,t,r){arguments[4][189][0].apply(r,arguments)},{dup:189}],200:[function(e,t,r){var n,a,o,i,s;n=e("../core/methods/attach.coffee"),o=e("./helpers/parseSize.coffee"),a=e("../core/console/print.coffee"),i=e("./helpers/parseText.coffee"),s=e("./helpers/wrap.coffee"),t.exports=function(){var t;return t={self:function(e){return e.each(function(){o(t),t.size.value[0]<=t.height.inner?(i(t),s(t)):t.container.value.html(""),t.dev.value&&a.timeEnd("total draw time")}),t.self}},n(t,{align:e("./methods/align.coffee"),config:e("./methods/config.coffee"),container:e("./methods/container.coffee"),dev:e("./methods/dev.coffee"),draw:e("./methods/draw.coffee"),format:e("./methods/format.coffee"),height:e("./methods/height.coffee"),padding:e("./methods/padding.coffee"),resize:e("./methods/resize.coffee"),rotate:e("./methods/rotate.coffee"),text:e("./methods/text.coffee"),shape:e("./methods/shape.coffee"),size:e("./methods/size.coffee"),valign:e("./methods/valign.coffee"),width:e("./methods/width.coffee"),x:e("./methods/x.coffee"),y:e("./methods/y.coffee")}),t.self}},{"../core/console/print.coffee":52,"../core/methods/attach.coffee":80,"./helpers/parseSize.coffee":179,"./helpers/parseText.coffee":180,"./helpers/wrap.coffee":182,"./methods/align.coffee":183,"./methods/config.coffee":184,"./methods/container.coffee":185,"./methods/dev.coffee":186,"./methods/draw.coffee":187,"./methods/format.coffee":188,"./methods/height.coffee":189,"./methods/padding.coffee":190,"./methods/resize.coffee":191,"./methods/rotate.coffee":192,"./methods/shape.coffee":193,"./methods/size.coffee":194,"./methods/text.coffee":195,"./methods/valign.coffee":196,"./methods/width.coffee":197,"./methods/x.coffee":198,"./methods/y.coffee":199}],201:[function(e,t,r){function n(){d3.selectAll("div.d3plus_tooltip_data_desc").style("height","0px"),d3.selectAll("div.d3plus_tooltip_data_help").style("background-color","#ccc")}var a=e("../core/locale/languages/en_US.coffee"),o=e("../client/pointer.coffee"),i=e("../color/legible.coffee"),s=e("./move.coffee"),l=e("../client/prefix.coffee"),u=e("../client/rtl.coffee"),c=e("./remove.coffee"),f=e("../client/scroll.js"),d=e("../client/scrollbar.coffee"),p=e("../string/list.coffee"),h=e("../color/text.coffee");t.exports=function(e){var t=e.fullscreen?250:200,r=l();e.width=e.width||t,e.max_width=e.max_width||386,e.id=e.id||"default",e.size=e.fullscreen||e.html?"large":"small",e.offset=e.offset||0,e.arrow_offset=e.arrow?8:0,e.x=e.x||0,e.y=e.y||0,e.parent=e.parent||d3.select("body"),e.curtain=e.curtain||"#fff",e.curtainopacity=e.curtainopacity||.8,e.background=e.background||"#fff",e.fontcolor=e.fontcolor||"#444",e.fontfamily=e.fontfamily||"sans-serif",e.fontweight=e.fontweight||"normal",e.fontsize=e.fontsize||"12px",e.style=e.style||"default",e.zindex="small"==e.size?2e3:500,e.locale=e.locale||a,e.stacked=e.stacked||!1;var v=e.parent?e.parent.node().offsetHeight||e.parent.node().getBoundingClientRect().height:0;if(e.iconsize||(e.iconsize="small"==e.size?22:50),e.parent.node()===document.body){e.limit=[window.innerWidth+f.x(),window.innerHeight+f.y()];var g=d();document.body.scrollHeight>window.innerHeight&&(e.limit[0]-=g)}else e.limit=[parseFloat(e.parent.style("width"),10),parseFloat(e.parent.style("height"),10)];if(e.title instanceof Array){var m=e.locale.ui.and,y=e.locale.ui.more;e.title=p(e.title,m,3,y)}if(c(e.id),e.anchor={},e.fullscreen)e.anchor.x="center",e.anchor.y="center",e.x=e.parent?e.parent.node().offsetWidth/2:window.innerWidth/2,e.y=e.parent?v/2:window.innerHeight/2;else if(e.align){var x=e.align.split(" ");e.anchor.y=x[0],x[1]?e.anchor.x=x[1]:e.anchor.x="center"}else e.anchor.x="center",e.anchor.y="top";var b=e.width-30;if(e.fullscreen){e.parent.append("div").attr("id","d3plus_tooltip_curtain_"+e.id).attr("class","d3plus_tooltip_curtain").style("background-color",e.curtain).style("opacity",e.curtainopacity).style("position","absolute").style("z-index",499).style("top","0px").style("right","0px").style("bottom","0px").style("left","0px").on(o.click,function(){c(e.id)})}var w=e.parent.append("div").datum(e).attr("id","d3plus_tooltip_id_"+e.id).attr("class","d3plus_tooltip d3plus_tooltip_"+e.size).style("color",e.fontcolor).style("font-family",e.fontfamily).style("font-weight",e.fontweight).style("font-size",e.fontsize+"px").style(r+"box-shadow","0px 1px 3px rgba(0, 0, 0, 0.25)").style("position","absolute").on(o.out,n);e.max_height&&w.style("max-height",e.max_height+"px"),e.fixed?(w.style("z-index",500),e.mouseevents=!0):w.style("z-index",2e3);var _=w.append("div").datum(e).attr("class","d3plus_tooltip_container").style("background-color",e.background).style("padding","6px");if(e.fullscreen&&e.html&&!e.stacked){z=e.parent?.75*e.parent.node().offsetWidth:.75*window.innerWidth,P=e.parent?.75*v:.75*window.innerHeight,_.style("width",z+"px").style("height",P+"px");var k=_.append("div").attr("class","d3plus_tooltip_body").style("padding-right","6px").style("display","inline-block").style("z-index",1).style("width",e.width+"px")}else{if("auto"==e.width){var z="auto";_.style("max-width",e.max_width+"px")}else var z=e.width-14+"px";var k=_.style("width",z)}if(e.title||e.icon)var A=k.append("div").attr("class","d3plus_tooltip_header").style("position","relative").style("z-index",1);if(e.fullscreen){w.append("div").attr("class","d3plus_tooltip_close").style("background-color",e.color).style("color",h(e.color)).style("position","absolute").style(r+"box-shadow","0 1px 3px rgba(0, 0, 0, 0.25)").style("font-size","20px").style("height","18px").style("line-height","14px").style("text-align","center").style("right","16px").style("top","-10px").style("width","18px").style("z-index",10).html("×").on(o.over,function(){d3.select(this).style("cursor","pointer").style(r+"box-shadow","0 1px 3px rgba(0, 0, 0, 0.5)")}).on(o.out,function(){d3.select(this).style("cursor","auto").style(r+"box-shadow","0 1px 3px rgba(0, 0, 0, 0.25)")}).on(o.click,function(){c(e.id)});d3.select("body").on("keydown.esc_"+e.id,function(){27===d3.event.keyCode&&(c(e.id),d3.select("body").on("keydown.esc_"+e.id,null))})}if(e.mouseevents){if(e.mouseevents!==!0){var j=d3.select(e.mouseevents).on(o.out),M=function(){var t=d3.event.toElement||d3.event.relatedTarget;if(t)var r="string"==typeof t.className?t.className:t.className.baseVal,a=0==r.indexOf("d3plus_tooltip");else var a=!1;t&&(O(w.node(),t)||O(e.mouseevents,t)||a)||(j(d3.select(e.mouseevents).datum()),n(),d3.select(e.mouseevents).on(o.out,j))},O=function(e,t){for(var r=t.parentNode;null!==r;){if(r==e)return!0;r=r.parentNode}return!1};d3.select(e.mouseevents).on(o.out,M),w.on(o.out,M);var E=d3.select(e.mouseevents).on(o.move);E&&w.on(o.move,E)}}else w.style("pointer-events","none");if(e.arrow){w.append("div").attr("class","d3plus_tooltip_arrow").style("background-color",e.background).style(r+"box-shadow","0px 1px 3px rgba(0, 0, 0, 0.25)").style("position","absolute").style("bottom","-5px").style("height","10px").style("left","50%").style("margin-left","-5px").style("width","10px").style(r+"transform","rotate(45deg)").style("z-index",-1)}if(e.icon){var F=A.append("div").attr("class","d3plus_tooltip_icon").style("width",e.iconsize+"px").style("height",e.iconsize+"px").style("z-index",1).style("background-position","50%").style("background-size","100%").style("background-image","url("+e.icon+")").style("display","inline-block").style("margin","0px 3px 3px 0px");"knockout"==e.style&&F.style("background-color",e.color),b-=F.node().offsetWidth}if(e.title){var S=e.max_width-6;e.icon&&(S-=e.iconsize+6),S+="px";A.append("div").attr("class","d3plus_tooltip_title").style("max-width",S).style("color",e.icon?e.fontcolor:i(e.color)).style("vertical-align","top").style("width",b+"px").style("display","inline-block").style("overflow","hidden").style("text-overflow","ellipsis").style("word-wrap","break-word").style("z-index",1).style("font-size","large"===e.size?"18px":"16px").style("line-height","large"===e.size?"20px":"17px").style("padding","large"===e.size?"3px 6px":"3px").text(e.title)}if(e.description){k.append("div").attr("class","d3plus_tooltip_description").style("font-size","12px").style("padding","6px").text(e.description)}if(e.data||e.html&&!e.fullscreen)var T=k.append("div").attr("class","d3plus_tooltip_data_container").style("overflow-y","auto").style("z-index",-1);if(e.data){var B=0,C={},q=null;e.data.forEach(function(t,a){t.group&&q!=t.group&&(q=t.group,T.append("div").attr("class","d3plus_tooltip_data_title").style("font-size","12px").style("font-weight","bold").style("padding","6px 3px 0px 3px").text(t.group));var s=T.append("div").attr("class","d3plus_tooltip_data_block").style("font-size","12px").style("padding","3px 6px").style("position","relative").datum(t);t.highlight===!0?s.style("color",i(e.color)):(t.allColors||t.highlight!==e.color)&&s.style("color",i(t.highlight));var c=s.append("div").attr("class","d3plus_tooltip_data_name").style("display","inline-block").html(t.name).on(o.out,function(){d3.event.stopPropagation()});if(t.link&&c.style("cursor","pointer").on(o.click,t.link),t.value instanceof Array){var f=e.locale.ui.and,d=e.locale.ui.more;t.value=list(t.value,f,3,d)}var p=s.append("div").attr("class","d3plus_tooltip_data_value").style("display","block").style("position","absolute").style("text-align","right").style("top","3px").html(t.value).on(o.out,function(){d3.event.stopPropagation()});if(u?p.style("left","6px"):p.style("right","6px"),e.mouseevents&&t.desc){var h=s.append("div").attr("class","d3plus_tooltip_data_desc").style("color","#888").style("overflow","hidden").style(r+"transition","height 0.5s").style("width","85%").text(t.desc).on(o.out,function(){d3.event.stopPropagation()}),v=h.node().offsetHeight||h.node().getBoundingClientRect().height;h.style("height","0px");var g=c.append("div").attr("class","d3plus_tooltip_data_help").style("background-color","#ccc").style(r+"border-radius","5px").style("color","#fff").style("cursor","pointer").style("display","inline-block").style("font-size","8px").style("font-weight","bold").style("height","10px").style("margin","3px 0px 0px 3px").style("padding-right","1px").style("text-align","center").style("width","10px").style("vertical-align","top").style(l+"transition","background-color 0.5s").text("?").on(o.over,function(){var e=d3.select(this.parentNode.parentNode).style("color");d3.select(this).style("background-color",e),h.style("height",v+"px")}).on(o.out,function(){d3.event.stopPropagation()});c.style("cursor","pointer").on(o.over,function(){n();var e=d3.select(this.parentNode).style("color");g.style("background-color",e),h.style("height",v+"px")}),s.on(o.out,function(){d3.event.stopPropagation(),n()})}var m=parseFloat(p.style("width"),10);m>e.width/2&&(m=e.width/2),m>B&&(B=m),a!=e.data.length-1&&(t.group&&t.group==e.data[a+1].group||!t.group&&!e.data[a+1].group)&&T.append("div").attr("class","d3plus_tooltip_data_seperator").style("background-color","#ddd").style("display","block").style("height","1px").style("margin","0px 3px")}),T.selectAll(".d3plus_tooltip_data_name").style("width",function(){var e=parseFloat(d3.select(this.parentNode).style("width"),10);return e-B-30+"px"}),T.selectAll(".d3plus_tooltip_data_value").style("width",B+"px").each(function(e){var t=parseFloat(d3.select(this).style("height"),10);C[e.name]=t}),T.selectAll(".d3plus_tooltip_data_name").style("min-height",function(e){return C[e.name]+"px"})}!e.html||e.fullscreen&&!e.stacked||(T.append("div").html(e.html),e.js&&e.js(_));var N=k.append("div").attr("class","d3plus_tooltip_footer").style("font-size","10px").style("position","relative").style("text-align","center");if(e.footer&&N.html(e.footer),e.height=w.node().offsetHeight||w.node().getBoundingClientRect().height,e.html&&e.fullscreen&&!e.stacked){var P=e.height-12,z=w.node().offsetWidth-e.width-44;_.append("div").attr("class","d3plus_tooltip_html").style("width",z+"px").style("height",P+"px").style("display","inline-block").style("vertical-align","top").style("overflow-y","auto").style("padding","0px 12px").style("position","absolute").html(e.html),e.js&&e.js(_)}if(e.width=w.node().offsetWidth,"center"!=e.anchor.y?e.height+=e.arrow_offset:e.width+=e.arrow_offset,e.data||(!e.fullscreen||e.stacked)&&e.html){if(!e.fullscreen||e.stacked)var I=e.fixed?v-e.y-10:v-10,P=e.heighto.limit[0]&&(o.x=o.limit[0]-o.width),o.yo.limit[1]&&(o.y=o.limit[1]-o.height)),s.style("top",o.y+"px").style("left",o.x+"px"),o.arrow&&s.selectAll(".d3plus_tooltip_arrow").call(n)),s},n=function(e){return e.style("bottom",function(e){return"center"===e.anchor.y||e.flip?"auto":"-5px"}).style("right",function(e){return"center"!==e.anchor.y||e.flip?"auto":"-5px"}).style("top",function(e){return"center"!==e.anchor.y&&e.flip?"-5px":"center"===e.anchor.y?"50%":"auto"}).style("left",function(e){return"center"===e.anchor.y&&e.flip?"-5px":"center"!==e.anchor.y?"50%":"auto"}).style("margin-left",function(e){var t;return"center"===e.anchor.y?"auto":(t="right"===e.anchor.x?-e.width/2+e.arrow_offset/2:"left"===e.anchor.x?e.width/2-2*e.arrow_offset-5:-5,e.cx-e.width/2-5t&&(t=-(e.limit[0]-e.cx-e.width/2+5),t>e.width/2-11&&(t=e.width/2-11)),t+"px")}).style("margin-top",function(e){var t;return"center"!==e.anchor.y?"auto":(t="bottom"===e.anchor.y?-e.height/2+e.arrow_offset/2-1:"top"===e.anchor.y?e.height/2-2*e.arrow_offset-2:-9,e.cy-e.height/2-e.arrow_offsett&&(t=-(e.limit[1]-e.cy-e.height/2+e.arrow_offset),t>e.height/2-22&&(t=e.height/2-22)),t+"px")})}},{"../client/scroll.js":41}],203:[function(e,t,r){t.exports=function(e){return e?(d3.selectAll("div#d3plus_tooltip_curtain_"+e).remove(),d3.selectAll("div#d3plus_tooltip_id_"+e).remove()):(d3.selectAll("div.d3plus_tooltip_curtain").remove(),d3.selectAll("div.d3plus_tooltip").remove())}},{}],204:[function(e,t,r){t.exports=function(e,t){var r,n;return r=[],n=1/(t-1)*(e[1]-e[0]),d3.range(e[0],e[1]+n,n)}},{}],205:[function(e,t,r){var n;n=e("./d3selection.coffee"),t.exports=function(e,t){var r;if(!e||!t)return!1;for(n(e)&&(e=e.node()),n(e)&&(t=t.node()),r=t.parentNode;null!==r;){if(r===e)return!0;r=r.parentNode}return!1}},{"./d3selection.coffee":208}],206:[function(e,t,r){t.exports=function(e,t){var r,n;return t.constructor===String?(n=e.indexOf(t),n>-1?e[n]:e[0]):(r=e[0],e.forEach(function(e){if(Math.abs(t-e)=0,t?e:"relative"}),e.container.changed&&e.container.value.html(""),a=["width","height"],r=0,n=a.length;r=0?(a=window["inner"+o.charAt(0).toUpperCase()+o.slice(1)],n=document!==r&&d3.select(r),n&&("width"===o?(a-=parseFloat(n.style("margin-left"),10),a-=parseFloat(n.style("margin-right"),10),a-=parseFloat(n.style("padding-left"),10),a-=parseFloat(n.style("padding-right"),10)):(a-=parseFloat(n.style("margin-top"),10),a-=parseFloat(n.style("margin-bottom"),10),a-=parseFloat(n.style("padding-top"),10),a-=parseFloat(n.style("padding-bottom"),10))),e[o].value=a<=20?e[o].small:a):(a=parseFloat(d3.select(r).style(o),10),"number"==typeof a&&a>0?e[o].value=a:"BODY"!==r.tagName?t(r.parentNode):void 0)},t(e.container.value.node()),1===d3.selectAll("body > *:not(script)").size()&&d3.select("body").style("overflow","hidden"));e.container.value.style("width",e.width.value+"px").style("height",e.height.value+"px")}},{}],212:[function(e,t,r){var n=e("../../core/data/format.js"),a=e("../../core/data/color.js"),o=e("../../core/data/keys.coffee"),i=e("../../core/data/load.coffee"),s=e("./ui/drawer.js"),l=e("./ui/legend.js"),u=e("./ui/timeline.coffee"),c=e("./errorCheck.js"),f=e("../../core/fetch/data.js"),d=e("./finish.js"),p=e("./focus/tooltip.coffee"),h=e("./ui/history.coffee"),v=e("../../core/parse/edges.js"),g=e("../../core/parse/nodes.js"),m=e("../../core/console/print.coffee"),y=e("../../tooltip/remove.coffee"),x=e("./types/run.coffee"),b=e("./shapes/draw.js"),w=e("../../string/format.js"),_=e("./svg/enter.js"),k=e("./svg/update.js"),z=e("./ui/titles.js"),A=e("../../object/validate.coffee");t.exports=function(e){var t=[],r=e.type.value,j=e.format.locale.value,M=j.message.ui,O=j.message.draw,E=["data","attrs","coords","nodes","edges"];if(E.forEach(function(r){e.error.value||e[r].loaded||!e[r].url||t.push({function:function(e,t){i(e,r,t)},message:j.message.loading,wait:!0})}),e.draw.update){var F=j.visualization[r]||r,S=e.types[r].setup||!1,T=e.types[r].requirements||[],B=w(j.message.initializing,F),C=j.message.data;T instanceof Array||(T=[T]),F=F.toLowerCase(),e.error.value||"function"!=typeof S||t.push({function:function(e){if(e.dev.value){var t="running "+F+" setup";m.time(t)}S(e),e.dev.value&&m.timeEnd(t)},message:B}),e.container.changed&&t.push({function:_,message:B}),r in e.g.apps||t.push({function:function(e){if(e.dev.value){var t="creating "+F+" group";m.time(t)}e.g.apps[r]=e.g.app.append("g").attr("id",r).attr("opacity",0),e.dev.value&&m.timeEnd(t)},message:B}),e.data.changed&&t.push({function:function(e){e.data.cache={},delete e.nodes.restricted,delete e.edges.restricted,o(e,"data")},message:C}),e.attrs.changed&&t.push({function:function(e){o(e,"attrs")},message:C}),t.push({function:function(e){if(!e.color.type||e.color.changed||e.data.changed||e.attrs.changed||e.id.changed||e.depth.changed||e.id.solo.changed||!e.time.fixed.value&&(e.time.solo.changed||e.time.mute.changed)){if(e.color.valueScale=!1,e.dev.value){var t="checking color type";m.time(t)}if(e.color.type=!1,e.color.value){var r=e.color.value;A(r)&&(r=r[e.id.value]?r[e.id.value]:r[d3.keys(r)[0]]),e.data.keys&&r in e.data.keys?e.color.type=e.data.keys[r]:e.attrs.keys&&r in e.attrs.keys&&(e.color.type=e.attrs.keys[r])}else e.data.keys&&(e.color.type=e.data.keys[e.id.value]);e.dev.value&&m.timeEnd(t)}},message:C}),T.indexOf("edges")>=0&&e.edges.value&&(!e.edges.linked||e.edges.changed)&&t.push({function:v,message:C}),T.indexOf("nodes")>=0&&e.edges.value&&(!e.nodes.positions||e.nodes.changed||e.type.changed)&&t.push({ +function:g,message:C}),(e.data.changed||e.time.changed||e.time.format.changed||e.type.changed||e.id.changed||e.x.scale.changed&&[e.x.scale.value,e.x.scale.previous].indexOf("discrete")>=0||e.y.scale.changed&&[e.y.scale.value,e.y.scale.previous].indexOf("discrete")>=0)&&t.push({function:n,message:C}),e.error.value||t.push({function:function(e){var t=e.time.fixed.value?["all"]:null;if(e.dev.value){var r=t?"fetching pool data":"fetching data";m.time(r)}e.data.pool=f(e,t),e.dev.value&&m.timeEnd(r),t?(e.dev.value&&m.time("fetching data for current year"),e.data.viz=f(e),e.dev.value&&m.timeEnd("fetching data for current year")):e.data.viz=e.data.pool,e.draw.timing=e.data.viz.length1){var u=e.format.locale.value.error.methods,c=e.format.locale.value.visualization[e.type.value]||e.type.value,f=e.format.locale.value.ui.and;l=s(l,f),e.error.internal=i(u,c,l)}else if(1===l.length){var u=e.format.locale.value.error.method,c=e.format.locale.value.visualization[e.type.value]||e.type.value;e.error.internal=i(u,c,l[0])}if(!e.error.internal&&t.indexOf("edges")>=0&&t.indexOf("focus")>=0){var d=e.edges.connections(e.focus.value[0],e.id.value);if(0==d.length){var p=n(e,e.focus.value[0],e.depth.value),u=e.format.locale.value.error.connections;e.error.internal=i(u,'"'+p+'"')}}var t=["d3"];e.types[e.type.value].libs&&(t=t.concat(e.types[e.type.value].libs));var l=[];if(t.forEach(function(e){window[e]||l.push('"'+e+'"')}),l.length>1){var u=e.format.locale.value.error.libs,c=e.format.locale.value.visualization[e.type.value],f=e.format.locale.value.ui.and;l=s(l,f),e.error.internal=i(u,c,l)}else if(1===l.length){var u=e.format.locale.value.error.lib,c=e.format.locale.value.visualization[e.type.value];e.error.internal=i(u,c,l[0])}var h=e.shape.accepted(e);h instanceof Array||(h=[h]);var v=e.shape.value;if(v&&!o(e,h,v,"shape")||e.self.shape(h[0]),"modes"in e.types[e.type.value]){var g=e.types[e.type.value].modes;g instanceof Array||(g=[g]);var m=e.type.mode.value;m&&!o(e,g,m,"mode")||e.self.type({mode:g[0]})}e.dev.value&&a.timeEnd("checking for errors")}},{"../../core/console/print.coffee":52,"../../core/fetch/text.js":66,"../../core/methods/rejected.coffee":91,"../../string/format.js":173,"../../string/list.coffee":174}],214:[function(e,t,r){var n=e("./shapes/edges.js"),a=e("./shapes/paths.js"),o=e("./ui/message.js"),i=e("./focus/viz.js"),s=e("../../core/methods/reset.coffee"),l=e("../../core/console/print.coffee"),u=e("./shapes/labels.js"),c=e("../../string/title.coffee"),f=e("./zoom/bounds.coffee"),d=e("./zoom/labels.coffee"),p=e("./zoom/mouse.coffee");t.exports=function(e){if(e.draw.first?setTimeout(function(){i(e)},e.draw.timing):i(e),!e.error.value){var t=e.zoom.viewport||e.zoom.bounds;e.types[e.type.value].zoom&&e.zoom.value&&t?(e.dev.value&&l.time("calculating zoom"),e.draw.first||e.zoom.reset?f(e,t,0):(e.type.changed||e.focus.changed||e.height.changed||e.width.changed||e.nodes.changed||e.legend.changed||e.timeline.changed||e.ui.changed)&&f(e,t),e.dev.value&&l.timeEnd("calculating zoom")):(e.zoom.bounds=[[0,0],[e.width.viz,e.height.viz]],e.zoom.scale=1,f(e))}var r=e.zoom.size?e.zoom.size.width:e.width.viz,h=e.zoom.size?e.zoom.size.height:e.height.viz,v=e.zoom.bounds?e.zoom.bounds[0][0]:0,g=e.zoom.bounds?e.zoom.bounds[0][1]:0;if(e.g.overlay.attr("width",r).attr("height",h).attr("x",v).attr("y",g),e.error.value||(e.draw.update?(e.edges.path?a(e):n(e),u(e,"data"),e.edges.label&&!e.edges.path&&setTimeout(function(){u(e,"edges")},e.draw.timing+200)):(e.labels.value||e.labels.changed)&&e.types[e.type.value].zoom&&e.zoom.value&&e.draw.timing&&setTimeout(function(){d(e)},e.draw.timing)),!e.error.value){var m=e.types[e.type.value].requirements||[];m instanceof Array||(m=[m]);var y=m.indexOf("data")>=0;e.error.internal||e.data.viz&&e.returned.nodes.length||!y||(e.error.internal=e.format.locale.value.error.data)}var x=e.type.previous;if(x&&e.type.value!=x&&e.g.apps[x]&&(e.dev.value&&l.time('hiding "'+x+'"'),e.draw.timing?e.g.apps[x].transition().duration(e.draw.timing).attr("opacity",0):e.g.apps[x].attr("opacity",0),e.dev.value&&l.timeEnd()),!e.error.value){var b=y&&0===e.data.viz.length||e.error.internal||e.error.value?0:e.focus.value.length&&e.types[e.type.value].zoom&&e.zoom.value?1-e.tooltip.curtain.opacity:1,w=e.draw.timing;e.group.transition().duration(w).attr("opacity",b),e.g.data.transition().duration(w).attr("opacity",b),e.g.edges.transition().duration(w).attr("opacity",b)}e.error.value?o(e,e.error.value):e.error.internal?(e.error.internal=c(e.error.internal),l.warning(e.error.internal),o(e,e.error.internal),e.error.internal=null):o(e),setTimeout(function(){s(e),e.types[e.type.value].zoom&&e.zoom.value?(e.g.zoom.datum(e).call(e.zoom.behavior.on("zoom",p)),e.zoom.scroll.value||e.g.zoom.on("mousewheel.zoom",null).on("MozMousePixelScroll.zoom",null).on("wheel.zoom",null),e.zoom.click.value||e.g.zoom.on("dblclick.zoom",null),e.zoom.pan.value||e.g.zoom.on("mousedown.zoom",null).on("mousemove.zoom",null)):e.g.zoom.call(e.zoom.behavior.on("zoom",null)).on("dblclick.zoom",null).on("mousedown.zoom",null).on("mousemove.zoom",null).on("mousewheel.zoom",null).on("MozMousePixelScroll.zoom",null).on("touchstart.zoom",null).on("wheel.zoom",null)},e.draw.timing)}},{"../../core/console/print.coffee":52,"../../core/methods/reset.coffee":93,"../../string/title.coffee":176,"./focus/viz.js":216,"./shapes/edges.js":226,"./shapes/labels.js":228,"./shapes/paths.js":230,"./ui/message.js":246,"./zoom/bounds.coffee":249,"./zoom/labels.coffee":251,"./zoom/mouse.coffee":252}],215:[function(e,t,r){var n,a,o,i;n=e("../tooltip/create.js"),a=e("../../../core/fetch/value.coffee"),o=e("../../../core/console/print.coffee"),i=e("../../../tooltip/remove.coffee"),t.exports=function(e){var t,r,s;r=e.focus,!e.error.internal&&1===r.value.length&&r.value.length&&!e.small&&r.tooltip.value?(e.dev.value&&o.time("drawing focus tooltip"),t=e.data.pool.filter(function(t){return a(e,t,e.id.value)===r.value[0]}),t.length>=1?t=t[0]:(t={},t[e.id.value]=r.value[0]),s=e.labels.padding,n({anchor:"top left",arrow:!1,data:t,fullscreen:!1,id:"visualization_focus",length:"long",maxheight:e.height.viz-2*s,mouseevents:!0,offset:0,vars:e,width:e.tooltip.large,x:e.width.value-e.margin.right-s,y:e.margin.top+s}),e.width.viz-=e.tooltip.large+2*s,e.dev.value&&o.timeEnd("drawing focus tooltip")):i("visualization_focus")}},{"../../../core/console/print.coffee":52,"../../../core/fetch/value.coffee":67,"../../../tooltip/remove.coffee":203,"../tooltip/create.js":240}],216:[function(t,r,n){var a=t("../../../client/pointer.coffee"),o=t("../../../client/ie.js"),i=t("../../../core/fetch/value.coffee"),s=t("../../../core/console/print.coffee"),l=t("../../../util/uniques.coffee");r.exports=function(t){if(t.g.edge_focus.selectAll("g").remove(),t.g.data_focus.selectAll("g").remove(),t.focus.value.length&&t.types[t.type.value].zoom&&t.zoom.value){t.dev.value&&s.time("drawing focus elements");var r=t.g.edges.selectAll("g");if(r.size()>0){r.each(function(e){var r=e[t.edges.source][t.id.value],n=e[t.edges.target][t.id.value];if(r==t.focus.value[0]||n==t.focus.value[0]){var a=t.g.edge_focus.node().appendChild(this.cloneNode(!0));d3.select(a).datum(e).attr("opacity",1).selectAll("line, path").datum(e)}});var n=t.edges.arrows.value;t.g.edge_focus.selectAll("line, path").attr("vector-effect","non-scaling-stroke").style("stroke",t.color.focus).style("stroke-width",function(){return o&&t.types[t.type.value].zoom?0:t.edges.size.value?d3.select(this).style("stroke-width"):2*t.data.stroke.width}).attr("marker-start",function(e){var r=t.edges.arrows.direction.value;if("bucket"in e.d3plus)var a="_"+e.d3plus.bucket;else var a="";return"source"==r&&n?"url(#d3plus_edge_marker_focus"+a+")":"none"}).attr("marker-end",function(e){var r=t.edges.arrows.direction.value;if("bucket"in e.d3plus)var a="_"+e.d3plus.bucket;else var a="";return"target"==r&&n?"url(#d3plus_edge_marker_focus"+a+")":"none"}),t.g.edge_focus.selectAll("text").style("fill",t.color.focus)}var u=l(t.edges.connections(t.focus.value[0],t.id.value,!0),t.id.value,i,t);u.push(t.focus.value[0]);var c=[],f=[],d=[0],p=[0];t.g.data.selectAll("g").each(function(r){if(u.indexOf(r[t.id.value])>=0){var n=t.g.data_focus.node().appendChild(this.cloneNode(!0)),n=d3.select(n).datum(r).attr("opacity",1);"coordinates"==t.shape.value?t.zoom.viewport=t.path.bounds(t.zoom.coords[r.d3plus.id]):"d3plus"in r&&("x"in r.d3plus&&c.push(r.d3plus.x),"y"in r.d3plus&&f.push(r.d3plus.y),"r"in r.d3plus?(d.push(r.d3plus.r),p.push(r.d3plus.r)):("width"in r.d3plus&&d.push(r.d3plus.width/2),"height"in r.d3plus&&p.push(r.d3plus.height/2)));for(e in a){var o=d3.select(this).on(a[e]);o&&n.on(a[e],o)}}});if(c.length&&f.length){var h=d3.extent(c),v=d3.extent(f),g=d3.max(d),m=d3.max(p);t.zoom.viewport=[[h[0]-g,v[0]-m],[h[1]+g,v[1]+m]]}t.g.data_focus.selectAll("path").style("stroke-width",o&&t.types[t.type.value].zoom?0:2*t.data.stroke.width),t.dev.value&&s.timeEnd("drawing focus elements")}else t.zoom.viewport=!1}},{"../../../client/ie.js":37,"../../../client/pointer.coffee":38,"../../../core/console/print.coffee":52,"../../../core/fetch/value.coffee":67,"../../../util/uniques.coffee":210}],217:[function(e,t,r){var n,a,o,i;i=e("./style.coffee"),a=e("../../../geom/largestRect.coffee"),o=e("../../../geom/path2poly.coffee"),n={start:{},end:{}},t.exports=function(e,t,r,s){var l,u,c,f;l=d3.svg.arc().innerRadius(0).outerRadius(function(e){return e.d3plus.r}).startAngle(function(e){return e.d3plus.startAngle}).endAngle(function(e){return e.d3plus.endAngle}),c=function(t){var r,n;return e.labels.value&&(t.d3plus.label?t.d3plus_label=t.d3plus.label:(r=o(l(t)),n=a(r,{angle:0}),n[0]?t.d3plus_label={w:n[0].width,h:n[0].height,x:n[0].cx,y:n[0].cy}:delete t.d3plus_label)),[t]},e.draw.timing?(f=d3.svg.arc().innerRadius(0).outerRadius(function(e){return e.d3plus.r}).startAngle(function(e){return void 0===n.start[e.d3plus.id]&&(n.start[e.d3plus.id]=0),isNaN(n.start[e.d3plus.id])&&(n.start[e.d3plus.id]=e.d3plus.startAngle),n.start[e.d3plus.id]}).endAngle(function(e){return void 0===n.end[e.d3plus.id]&&(n.end[e.d3plus.id]=0),isNaN(n.end[e.d3plus.id])&&(n.end[e.d3plus.id]=e.d3plus.endAngle),n.end[e.d3plus.id]}),u=function(e,t){return e.attrTween("d",function(e){var r,a,o,i;return void 0===t?(i=e.d3plus.startAngle,r=e.d3plus.endAngle):0===t&&(i=0,r=0),o=d3.interpolate(n.start[e.d3plus.id],i),a=d3.interpolate(n.end[e.d3plus.id],r),function(t){return n.start[e.d3plus.id]=o(t),n.end[e.d3plus.id]=a(t),f(e)}})},r.append("path").attr("class","d3plus_data").call(i,e).attr("d",f),t.selectAll("path.d3plus_data").data(c).transition().duration(e.draw.timing).call(i,e).call(u),s.selectAll("path.d3plus_data").transition().duration(e.draw.timing).call(u,0)):(r.append("path").attr("class","d3plus_data"),t.selectAll("path.d3plus_data").data(c).call(i,e).attr("d",l))}},{"../../../geom/largestRect.coffee":160,"../../../geom/path2poly.coffee":162,"./style.coffee":234}],218:[function(e,t,r){var n=e("../../../core/fetch/text.js"),a=e("../../../font/sizes.coffee"),o=e("../../../geom/largestRect.coffee"),i=e("./style.coffee");t.exports=function(e,t,r,s){var l=d3.svg.area().x(function(e){return e.d3plus.x}).y0(function(e){return e.d3plus.y0}).y1(function(e){return e.d3plus.y}).interpolate(e.shape.interpolate.value),u=d3.svg.area().x(function(e){return e.d3plus.x}).y0(function(e){return e.d3plus.y0}).y1(function(e){return e.d3plus.y0}).interpolate(e.shape.interpolate.value);r.append("path").attr("class","d3plus_data").attr("d",function(e){return u(e.values)}).call(i,e);var c={"font-weight":e.labels.font.weight,"font-family":e.labels.font.family.value};t.selectAll("path.d3plus_data").data(function(t){if(e.labels.value&&t.values.length>1){var r=d3.max(t.values,function(e){return e.d3plus.y0-e.d3plus.y}),i=!1;if(r>e.labels.font.size){var s=[],l=[],u=n(e,t);t.values.forEach(function(e){s.push([e.d3plus.x,e.d3plus.y]),l.push([e.d3plus.x,e.d3plus.y0])}),s=s.concat(l.reverse());var f=null;if(u.length){var d=a(u[0],c);f=d[0].width/d[0].height}i=o(s,{angle:d3.range(-70,71,1),aspectRatio:f,tolerance:0})}if(i&&i[0]){var p={w:~~i[0].width,h:~~i[0].height,x:~~i[0].cx,y:~~i[0].cy,angle:i[0].angle*-1,padding:2,names:u};0!==i[0].angle?p.translate={x:p.x,y:p.y}:p.translate=!1,p.w>=10&&p.h>=10&&(t.d3plus_label=p)}}return[t]}),e.draw.timing?t.selectAll("path.d3plus_data").transition().duration(e.draw.timing).attr("d",function(e){return l(e.values)}).call(i,e):t.selectAll("path.d3plus_data").attr("d",function(e){return l(e.values)}).call(i,e)}},{"../../../core/fetch/text.js":66,"../../../font/sizes.coffee":102,"../../../geom/largestRect.coffee":160,"./style.coffee":234}],219:[function(e,t,r){var n=(e("../../../core/fetch/text.js"),e("../../../geom/largestRect.coffee"),e("./style.coffee"));t.exports=function(e,t,r,a){function o(e){e.attr("transform","scale(1)")}function i(e){e.attr("transform",function(e){var t=Math.min(e.d3plus.width,e.d3plus.height),r=Math.floor(t/16);return"scale("+r+")"})}r.append("path").attr("class","d3plus_data").attr("d","M5-6.844L3.594-5.407L-2,0.188l-1.594-1.594L-5-2.844L-7.844,0l1.438,1.406l3,3L-2,5.843l1.406-1.438l7-7L7.844-4L5-6.844z").call(o).call(n,e),t.selectAll("path.d3plus_data").data(function(e){return[e]}),e.draw.timing?t.selectAll("path.d3plus_data").transition().duration(e.draw.timing).call(i).call(n,e):t.selectAll("path.d3plus_data").call(i).call(n,e)}},{"../../../core/fetch/text.js":66,"../../../geom/largestRect.coffee":160,"./style.coffee":234}],220:[function(e,t,r){var n,a,o,i;a=e("../../../core/fetch/value.coffee"),n=e("../../../core/fetch/color.coffee"),o=e("../../../color/lighter.coffee"),i=e("./segments.coffee"),t.exports=function(e,t,r){var a,s,l,u;return s=e.d3plus.shape||t.shape.value,"line"===t.shape.value&&"circle"!==s?"none":"area"===t.shape.value||"active"===s||"line"===t.shape.value?n(t,e):"temp"===s?r?n(t,e):"url(#d3plus_hatch_"+e.d3plus.id+")":e.d3plus.static?o(n(t,e),.75):(a=i(t,e,"active"),l=i(t,e,"temp"),u=i(t,e,"total"),!t.active.value&&!t.temp.value||a===!0||a&&u&&a>=u&&!l||a&&!u?n(t,e):t.active.spotlight.value?t.color.missing:o(n(t,e),.75))}},{"../../../color/lighter.coffee":45,"../../../core/fetch/color.coffee":63,"../../../core/fetch/value.coffee":67,"./segments.coffee":233}],221:[function(e,t,r){var n,a,o,i,s,l,u,c;n=e("../../../util/copy.coffee"),a=e("../../../network/distance.coffee"),o=e("../../../core/fetch/text.js"),i=e("../../../font/sizes.coffee"),l=e("../../../geom/largestRect.coffee"),u=e("../../../geom/path2poly.coffee"),c=e("./style.coffee"),s={},t.exports=function(e,t,r,f){var d,p;return d=d3.geo[e.coords.projection.value](),d.center&&d.center(e.coords.center),e.zoom.scale||(e.zoom.scale=1),e.zoom.area=1/e.zoom.scale/e.zoom.scale,e.path=d3.geo.path().projection(d),e.draw.timing?t.selectAll("path.d3plus_data").attr("d",e.path).transition().duration(e.draw.timing).call(c,e):t.selectAll("path.d3plus_data").attr("d",e.path).call(c,e),r.append("path").attr("id",function(e){return e.id}).attr("class","d3plus_data").attr("d",e.path).call(c,e),p=e.old_height!==e.height.viz||e.height.changed||e.old_width!==e.width.viz||e.width.changed,e.old_height=e.height.viz,e.old_width=e.width.viz,e.coords.changed||p||e.coords.mute.changed||e.coords.solo.changed||e.type.changed||e.text.changed||e.coords.projection.changed||e.labels.changed?(e.zoom.bounds=null,e.zoom.reset=!0,e.zoom.coords={},t.each(function(t){var r,c,f,d,p,h,v,g,m,y,x,b,w,_,k,z,A,j,M,O,E;if(e.coords.simplify.value&&t.geometry.coordinates.length>1){for(m=[],c=[],r=0,b=n(t),j=n(t),t.geometry.coordinates=t.geometry.coordinates.filter(function(t,n){var a;return j.geometry.coordinates=[t],a=e.path.area(j),a>0&&(c.push(a),a>r&&(b.geometry.coordinates=[t],r=a),!0)}),p=e.path.centroid(b),M=t.geometry.coordinates,y=x=0,w=M.length;x=v}),h=b.geometry.coordinates[0],h&&"MultiPolygon"===b.geometry.type&&(h=h[0],b.geometry.coordinates[0]=h,b.geometry.type="Polygon")}else j=t,b=t,h=t.geometry.coordinates[0];return e.zoom.coords[t.d3plus.id]=j,delete t.d3plus_label,e.labels.value&&(_=o(e,t),h&&_.length&&(k=u(e.path(b)),E={"font-weight":e.labels.font.weight,"font-family":e.labels.font.family.value},z=null,1===_[0].split(" ").length&&(O=i(_[0],E)[0],z=O.width/O.height),A=l(k,{angle:0,aspectRatio:z}),A&&(A=A[0],t.d3plus_label={anchor:"middle",valign:"center",h:A.height,w:A.width,x:A.cx,y:A.cy,names:_}))),s[t.id]=t.d3plus_label,f=e.path.bounds(j),e.zoom.bounds?(e.zoom.bounds[0][0]>f[0][0]&&(e.zoom.bounds[0][0]=f[0][0]),e.zoom.bounds[0][1]>f[0][1]&&(e.zoom.bounds[0][1]=f[0][1]),e.zoom.bounds[1][0]2*Math.PI?2*Math.PI:r}).innerRadius(function(t){if(t.d3plus.static)return 0;var r=e.arcs[t.d3plus.shape][t.d3plus.id].r;return r*e.data.donut.size}).outerRadius(function(t){return e.arcs[t.d3plus.shape][t.d3plus.id].r});e.draw.timing?(a.selectAll("path.d3plus_data").transition().duration(e.draw.timing).call(o,0,0).each("end",function(t){delete e.arcs[t.d3plus.shape][t.d3plus.id]}),t.selectAll("path.d3plus_data").data(i).transition().duration(e.draw.timing).call(o).call(n,e),r.append("path").attr("class","d3plus_data").transition().duration(0).call(o,0,0).call(n,e).transition().duration(e.draw.timing).call(o).call(n,e)):(a.selectAll("path.d3plus_data").each(function(t){delete e.arcs[t.d3plus.shape][t.d3plus.id]}),r.append("path").attr("class","d3plus_data"),t.selectAll("path.d3plus_data").data(i).call(o).call(n,e))}},{"./style.coffee":234}],225:[function(e,t,r){var n=e("../../../util/child.coffee"),a=e("../../../util/closest.coffee"),o=e("../tooltip/create.js"),i=e("../../../client/pointer.coffee"),s=e("../../../core/fetch/value.coffee"),l=e("../../../core/fetch/color.coffee"),u=e("../../../core/fetch/text.js"),c=e("../../../color/legible.coffee"),f=e("../../../core/console/print.coffee"),d=e("../../../tooltip/remove.coffee"),p=e("./segments.coffee"),h=e("./fill.js"),v=e("../../../string/strip.js"),g=e("../../../client/touch.coffee"),m=e("../zoom/propagation.coffee"),y=e("../../../util/uniques.coffee"),x=e("../../../object/validate.coffee"),b=e("../zoom/direction.coffee"),w={arc:e("./arc.coffee"),area:e("./area.js"),check:e("./check.js"),coordinates:e("./coordinates.coffee"),cross:e("./cross.js"),diamond:e("./diamond.js"),donut:e("./donut.js"),line:e("./line.js"),radial:e("./radial.coffee"),rect:e("./rect.coffee"),triangle_down:e("./triangle_down.js"),triangle_up:e("./triangle_up.js"),whisker:e("./whisker.coffee")};t.exports=function(e){function t(t){if(!t.d3plus.id){t.d3plus.id="";for(var r=0;r<=e.depth.value;r++)t.d3plus.id+=s(e,t,e.id.nesting[r])+"_";t.d3plus.id+=F,["x","y","x2","y2"].forEach(function(r){if("discrete"==e[r].scale.value){var n=s(e,t,e[r].value);n.constructor===Date&&(n=n.getTime()),t.d3plus.id+="_"+n}}),t.d3plus.suffix&&(t.d3plus.id+="_"+t.d3plus.suffix),t.d3plus.id=v(t.d3plus.id)}return t}function r(t,r){var n=e.types[e.type.value].scale,a=1;n&&(x[n]&&e.shape.value in n?a=n[e.shape.value]:"function"==typeof n?a=n(e,e.shape.value):"number"==typeof n&&(a=n)),a=r?a:1,t.attr("transform",function(e){if(["line","area","coordinates"].indexOf(F)<0){var t=e.d3plus.x||0,r=e.d3plus.y||0;return"translate("+t+","+r+")scale("+a+")"}return"scale("+a+")"})}function _(t){t.attr("id",function(e){return"d3plus_group_"+e.d3plus.id}).attr("class",function(t){var r=e.class.value?" "+s(e,t,e.class.value):"";return"d3plus_"+F+r})}function k(t){if(t&&e.g.edges.selectAll("g").size()>0){e.g.edge_hover.selectAll("*").remove(),e.g.edges.selectAll("g").each(function(r){var n=t[e.id.value],a=r[e.edges.source][e.id.value],o=r[e.edges.target][e.id.value];if(a==n||a=="left_"+n||a=="right_"+n||o==n||o=="left_"+n||o=="right_"+n){var i=e.g.edge_hover.node().appendChild(this.cloneNode(!0));d3.select(i).datum(r).attr("opacity",1).selectAll("line, path").datum(r)}});var r=e.edges.arrows.value;e.g.edge_hover.attr("opacity",0).selectAll("line, path").style("stroke",e.color.primary).style("stroke-width",function(t){return e.edges.path&&t.dy?Math.max(1,t.dy):e.edges.size.value?d3.select(this).style("stroke-width"):2*e.data.stroke.width}).attr("marker-start",function(t){var n=e.edges.arrows.direction.value;if("bucket"in t.d3plus)var a="_"+t.d3plus.bucket;else var a="";return"source"==n&&r?"url(#d3plus_edge_marker_highlight"+a+")":"none"}).attr("marker-end",function(t){var n=e.edges.arrows.direction.value;if("bucket"in t.d3plus)var a="_"+t.d3plus.bucket;else var a="";return"target"==n&&r?"url(#d3plus_edge_marker_highlight"+a+")":"none"}),e.g.edge_hover.selectAll("text").style("fill",e.color.primary),e.draw.timing?(e.g.edge_hover.transition().duration(e.timing.mouseevents).attr("opacity",1),e.g.edges.transition().duration(e.timing.mouseevents).attr("opacity",.5)):e.g.edge_hover.attr("opacity",1)}else e.draw.timing?(e.g.edge_hover.transition().duration(e.timing.mouseevents).attr("opacity",0).transition().selectAll("*").remove(),e.g.edges.transition().duration(e.timing.mouseevents).attr("opacity",1)):e.g.edge_hover.selectAll("*").remove()}var z=e.returned.nodes||[],A=e.returned.edges||[];e.draw.timing=z.length=0&&e.types[e.type.value].fill&&(e.dev.value&&f.time('filling "'+F+'" shapes'),h(e,S,C,T,r),e.dev.value&&f.timeEnd('filling "'+F+'" shapes'))}if(k(),e.tooltip.value)e.g.data.selectAll("g").on(i.over,function(t){if(g&&m(e,d3.event),d3.event.buttons||!e.mouse.value||!e.mouse.over.value||e.draw.frozen||t.d3plus&&t.d3plus.static)d(e.type.value);else{var n="function"!=typeof e.mouse.over.value;if("function"==typeof e.mouse.over.value&&(n=e.mouse.over.value(t,e.self)),n){var s=b(t.d3plus_data||t,e),l="function"==typeof e.mouse.viz||"function"==typeof e.mouse.viz[i.click]||e.zoom.value&&(e.types[e.type.value].zoom||t.d3plus.threshold&&t.d3plus.merged||1===s||s===-1&&e.history.states.length&&!e.tooltip.value.long);if(d3.select(this).style("cursor",l?"pointer":"auto").transition().duration(e.timing.mouseevents).call(r,!0),d3.select(this).selectAll(".d3plus_data").transition().duration(e.timing.mouseevents).attr("opacity",1),e.covered=!1,t.values&&e.axes.discrete){var u="x"===e.axes.discrete?0:1,c=d3.mouse(e.container.value.node())[u],f=y(t.values,function(t){return t.d3plus[e.axes.discrete]}),p=a(f,c);t.d3plus_data=t.values[f.indexOf(p)],t.d3plus=t.values[f.indexOf(p)].d3plus}var h=t.d3plus_data?t.d3plus_data:t;o({vars:e,data:h}),"function"==typeof e.mouse.viz?e.mouse.viz(t.d3plus_data||t,e):e.mouse.viz[i.over]&&e.mouse.viz[i.over](t.d3plus_data||t,e),k(t)}}}).on(i.move,function(t){if(g&&m(e,d3.event),d3.event.buttons||!e.mouse.value||!e.mouse.move.value||e.draw.frozen||t.d3plus&&t.d3plus.static)d(e.type.value);else{var r="function"!=typeof e.mouse.move.value;if("function"==typeof e.mouse.move.value&&(r=e.mouse.move.value(t,e.self)),r){var n=b(t.d3plus_data||t,e),s="function"==typeof e.mouse.viz||"function"==typeof e.mouse.viz[i.click]||e.zoom.value&&(e.types[e.type.value].zoom||t.d3plus.threshold&&t.d3plus.merged||1===n||n===-1&&e.history.states.length&&!e.tooltip.value.long);d3.select(this).style("cursor",s?"pointer":"auto");e.types[e.type.value].tooltip||"follow";if(t.values&&e.axes.discrete){var l="x"===e.axes.discrete?0:1,u=d3.mouse(e.container.value.node())[l],c=y(t.values,function(t){return t.d3plus[e.axes.discrete]}),f=a(c,u);t.d3plus_data=t.values[c.indexOf(f)],t.d3plus=t.values[c.indexOf(f)].d3plus}var p=t.d3plus_data?t.d3plus_data:t;o({vars:e,data:p}),"function"==typeof e.mouse.viz?e.mouse.viz(t.d3plus_data||t,e):e.mouse.viz[i.move]&&e.mouse.viz[i.move](t.d3plus_data||t,e)}}}).on(i.out,function(t){if(g&&m(e,d3.event),!d3.event.buttons&&e.mouse.value&&e.mouse.out.value){var a="function"!=typeof e.mouse.out.value;if("function"==typeof e.mouse.out.value&&(a=e.mouse.out.value(t,e.self)),a){var o=n(this,d3.event.toElement);o||e.draw.frozen||t.d3plus&&t.d3plus.static||(d3.select(this).transition().duration(e.timing.mouseevents).call(r),d3.select(this).selectAll(".d3plus_data").transition().duration(e.timing.mouseevents).attr("opacity",e.data.opacity),e.covered||d(e.type.value),"function"==typeof e.mouse.viz?e.mouse.viz(t.d3plus_data||t,e):e.mouse.viz[i.out]&&e.mouse.viz[i.out](t.d3plus_data||t,e),k())}}else d(e.type.value)});else{var q=function(){m(e,d3.event)};e.g.data.selectAll("g").on(i.over,q).on(i.move,q).on(i.out,q)}d3.select(window).on("scroll.d3plus",function(){d(e.type.value)}),e.g.data.selectAll("g").on(i.click,function(t){if((!e.mouse.viz||e.mouse.viz.click!==!1)&&e.mouse.value&&e.mouse.click.value&&!d3.event.defaultPrevented&&!e.draw.frozen&&(!t.d3plus||!t.d3plus.static)){var n="function"!=typeof e.mouse.click.value;if("function"==typeof e.mouse.click.value&&(n=e.mouse.click.value(t,e.self)),n){if(t.values&&e.axes.discrete){var f="x"===e.axes.discrete?0:1,p=d3.mouse(e.container.value.node())[f],h=y(t.values,function(t){return t.d3plus[e.axes.discrete]}),v=a(h,p);t.d3plus_data=t.values[h.indexOf(v)],t.d3plus=t.values[h.indexOf(v)].d3plus; +}"function"==typeof e.mouse.viz?e.mouse.viz(t.d3plus_data||t,e):e.mouse.viz[i.out]?e.mouse.viz[i.out](t.d3plus_data||t,e):e.mouse.viz[i.click]&&e.mouse.viz[i.click](t.d3plus_data||t,e);var g=b(t.d3plus_data||t,e),m=e.id.solo.value,x=u(e,t)[0],w=c(l(e,t)),_=e.title.sub.value||!1,z=e.title.sub.font.color,A=e.title.total.font.color;if(t.d3plus.threshold&&t.d3plus.merged&&e.zoom.value)e.history.states.push(function(){e.self.id({solo:m}).title({sub:{font:{color:z},value:_},total:{font:{color:A}}}).draw()}),e.self.id({solo:m.concat(y(t.d3plus.merged,e.id.value,s,e))}).title({sub:{font:{color:w},value:x},total:{font:{color:w}}}).draw();else if(1===g&&e.zoom.value){var j=s(e,t.d3plus_data||t,e.id.value);e.history.states.push(function(){e.self.depth(e.depth.value-1).id({solo:m}).title({sub:{font:{color:z},value:_},total:{font:{color:A}}}).draw()}),e.self.depth(e.depth.value+1).id({solo:m.concat(j)}).title({sub:{font:{color:w},value:x},total:{font:{color:w}}}).draw()}else if(g===-1&&e.zoom.value&&e.history.states.length&&!e.tooltip.value.long)e.history.back();else if(e.types[e.type.value].zoom&&e.zoom.value)k(),d3.select(this).transition().duration(e.timing.mouseevents).call(r),d3.select(this).selectAll(".d3plus_data").transition().duration(e.timing.mouseevents).attr("opacity",e.data.opacity),d(e.type.value),e.draw.update=!1,t&&t[e.id.value]!=e.focus.value[0]?e.self.focus(t[e.id.value]).draw():e.self.focus(!1).draw();else if(e.types[e.type.value].requirements.indexOf("focus")<0){k();var M=t.d3plus_data?t.d3plus_data:t;o({vars:e,data:M})}}}})}},{"../../../client/pointer.coffee":38,"../../../client/touch.coffee":43,"../../../color/legible.coffee":44,"../../../core/console/print.coffee":52,"../../../core/fetch/color.coffee":63,"../../../core/fetch/text.js":66,"../../../core/fetch/value.coffee":67,"../../../object/validate.coffee":172,"../../../string/strip.js":175,"../../../tooltip/remove.coffee":203,"../../../util/child.coffee":205,"../../../util/closest.coffee":206,"../../../util/uniques.coffee":210,"../tooltip/create.js":240,"../zoom/direction.coffee":250,"../zoom/propagation.coffee":253,"./arc.coffee":217,"./area.js":218,"./check.js":219,"./coordinates.coffee":221,"./cross.js":222,"./diamond.js":223,"./donut.js":224,"./fill.js":227,"./line.js":229,"./radial.coffee":231,"./rect.coffee":232,"./segments.coffee":233,"./triangle_down.js":235,"./triangle_up.js":236,"./whisker.coffee":237}],226:[function(e,t,r){var n=e("../../../util/buckets.coffee"),a=e("../../../geom/offset.coffee");t.exports=function(e){function t(t){t.attr("opacity",0).style("stroke-width",0).style("stroke",e.background.value).style("fill","none")}function r(t){var r=e.edges.arrows.value;t.attr("opacity",function(t){return"number"===h?p:"function"===h?p(t,e):e.edges.opacity.scale.value(t[p])}).style("stroke-width",function(t){return e.edges.scale(t[e.edges.size.value])}).style("stroke",e.edges.color).attr("marker-start",function(t){var n=e.edges.arrows.direction.value;if("bucket"in t.d3plus)var a="_"+t.d3plus.bucket;else var a="";return"source"==n&&r?"url(#d3plus_edge_marker_default"+a+")":"none"}).attr("marker-end",function(t){var n=e.edges.arrows.direction.value;if("bucket"in t.d3plus)var a="_"+t.d3plus.bucket;else var a="";return"target"==n&&r?"url(#d3plus_edge_marker_default"+a+")":"none"}).attr("vector-effect","non-scaling-stroke").attr("pointer-events","none")}function o(t){t.attr("x1",function(t){return t[e.edges.source].d3plus.edges[t[e.edges.target][e.id.value]].x}).attr("y1",function(t){return t[e.edges.source].d3plus.edges[t[e.edges.target][e.id.value]].y}).attr("x2",function(t){return t[e.edges.target].d3plus.edges[t[e.edges.source][e.id.value]].x}).attr("y2",function(t){return t[e.edges.target].d3plus.edges[t[e.edges.source][e.id.value]].y})}function i(e){e.attr("d",function(e){return v(e.d3plus.spline)})}function s(t){if(delete t.d3plus_label,e.g.edges.selectAll("line, path").size()90)&&(s-=180),l*e.zoom.behavior.scaleExtent()[0]>20&&(t.d3plus_label={x:u,y:c,translate:{x:u,y:c},w:l,h:15+2*e.labels.padding,angle:s,anchor:"middle",valign:"center",color:e.edges.color,resize:!1,names:[e.format.value(t[e.edges.label])],background:1})}}var l=e.returned.edges||[],u=e.zoom.behavior.scaleExtent()[0];if("string"==typeof e.edges.size.value){var c=d3.extent(l,function(t){return t[e.edges.size.value]}),f=d3.min(e.returned.nodes||[],function(e){return e.d3plus.r})*(2*e.edges.size.scale);e.edges.scale=d3.scale.sqrt().domain(c).range([e.edges.size.min,f*u])}else{var d="number"==typeof e.edges.size.value?e.edges.size.value:e.edges.size.min;e.edges.scale=function(){return d}}var p=e.edges.opacity.value,h=typeof p;e.edges.opacity.changed&&"string"===h&&e.edges.opacity.scale.value.domain(d3.extent(l,function(e){return e[p]})).range([e.edges.opacity.min.value,1]);var v=d3.svg.line().interpolate(e.edges.interpolate.value),g=e.edges.arrows.value?"string"==typeof e.edges.size.value?["default_0","default_1","default_2","highlight_0","highlight_1","highlight_2","focus_0","focus_1","focus_2"]:["default","highlight","focus"]:[];if("string"==typeof e.edges.size.value)for(var m=n(e.edges.scale.range(),4),y=[],x=0;x<3;x++)y.push(m[x+1]+(m[1]-m[0])*(x+2)*2);else var b="number"==typeof e.edges.arrows.value?e.edges.arrows.value:8,y="number"==typeof e.edges.size.value?e.edges.size.value/b:b;var w=e.defs.selectAll(".d3plus_edge_marker").data(g,String),_=function(t){t.attr("d",function(t){var r=t.split("_");if(2==r.length&&e.edges.scale){r=parseInt(r[1]);var n=y[r]}else var n=y;return"target"==e.edges.arrows.direction.value?"M 0,-"+n/2+" L "+.85*n+",0 L 0,"+n/2+" L 0,-"+n/2:"M 0,-"+n/2+" L -"+.85*n+",0 L 0,"+n/2+" L 0,-"+n/2}).attr("fill",function(t){var r=t.split("_")[0];return"default"==r?e.edges.color:"focus"==r?e.color.focus:e.color.primary}).attr("transform","scale("+1/u+")")};e.draw.timing?(w.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),w.select("path").transition().duration(e.draw.timing).attr("opacity",1).call(_)):(w.exit().remove(),w.select("path").attr("opacity",1).call(_));var k=e.draw.timing?0:1,z=w.enter().append("marker").attr("id",function(e){return"d3plus_edge_marker_"+e}).attr("class","d3plus_edge_marker").attr("orient","auto").attr("markerUnits","userSpaceOnUse").style("overflow","visible").append("path").attr("opacity",k).attr("vector-effect","non-scaling-stroke").call(_);e.draw.timing&&z.transition().duration(e.draw.timing).attr("opacity",1);var A="string"==typeof e.edges.size.value?n(e.edges.scale.domain(),4):null,j=e.edges.arrows.direction.value,M=l.filter(function(t){if(t.d3plus||(t.d3plus={}),t.d3plus.id="edge_"+t[e.edges.source][e.id.value]+"_"+t[e.edges.target][e.id.value],t.d3plus.spline!==!0){if(A){var r=t[e.edges.size.value];t.d3plus.bucket=ri.d3plus.x?1-d:1+d,h=o.d3plus.x>i.d3plus.x?1+d:1-d,v="number"==typeof s.angle?s.angle:Math.atan2(o.d3plus.y-i.d3plus.y,o.d3plus.x-i.d3plus.x)*p,g=a(v,o.d3plus.r+c,e.shape.value),m="number"==typeof l.angle?l.angle:Math.atan2(i.d3plus.y-o.d3plus.y,i.d3plus.x-o.d3plus.x)*h,x=a(m,i.d3plus.r+f,e.shape.value),b=[o.d3plus.x-g.x,o.d3plus.y-g.y],w=!!s.offset&&a(v,s.offset),_=w?[b[0]-w.x,b[1]-w.y]:b,k=[i.d3plus.x-x.x,i.d3plus.y-x.y],z=!!l.offset&&a(m,l.offset),M=z?[k[0]-z.x,k[1]-z.y]:k,O=M[0]-_[0],E=M[1]-_[1],F="number"==typeof s.radius?s.radius:Math.sqrt(O*O+E*E)/4,S="number"==typeof l.radius?l.radius:Math.sqrt(O*O+E*E)/4,T=a(v,F-o.d3plus.r-2*c),B=a(m,S-i.d3plus.r-2*f);t.d3plus.spline=[b,k];var C=Math.abs(Math.atan2(o.d3plus.y-i.d3plus.y,o.d3plus.x-i.d3plus.x)).toFixed(5),q=Math.abs(v).toFixed(5),N=Math.abs(m-Math.PI).toFixed(5);return(q!==N||[q,N].indexOf(C)<0)&&(t.d3plus.spline.splice(1,0,[_[0]-T.x,_[1]-T.y],[M[0]-B.x,M[1]-B.y]),w&&t.d3plus.spline.splice(1,0,_),z&&t.d3plus.spline.splice(t.d3plus.spline.length-1,0,M)),!0}return!1}),F=e.g.edges.selectAll("g.d3plus_edge_path").data(E,function(e){return e.d3plus.id});e.draw.timing?(O.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),F.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),O.selectAll("text.d3plus_label, rect.d3plus_label_bg").transition().duration(e.draw.timing/2).attr("opacity",0).remove(),F.selectAll("text.d3plus_label, rect.d3plus_label_bg").transition().duration(e.draw.timing/2).attr("opacity",0).remove(),O.selectAll("line").data(function(e){return[e]}).transition().duration(e.draw.timing).call(o).call(r).each("end",s),F.selectAll("path").data(function(e){return[e]}).transition().duration(e.draw.timing).call(i).call(r).each("end",s),O.enter().append("g").attr("class","d3plus_edge_line").append("line").call(o).call(t).transition().duration(e.draw.timing).call(r).each("end",s),F.enter().append("g").attr("class","d3plus_edge_path").append("path").call(i).call(t).transition().duration(e.draw.timing).call(r).each("end",s)):(O.exit().remove(),F.exit().remove(),O.selectAll("text.d3plus_label, rect.d3plus_label_bg").remove(),F.selectAll("text.d3plus_label, rect.d3plus_label_bg").remove(),O.selectAll("line").data(function(e){return[e]}).call(o).call(r).call(s),F.selectAll("path").data(function(e){return[e]}).call(i).call(r).call(s),O.enter().append("g").attr("class","d3plus_edge_line").append("line").call(o).call(t).call(r).call(s),F.enter().append("g").attr("class","d3plus_edge_path").append("path").call(i).call(t).call(r).call(s))}},{"../../../geom/offset.coffee":161,"../../../util/buckets.coffee":204}],227:[function(e,t,r){var n=e("../../../util/copy.coffee"),a=e("../../../core/fetch/color.coffee"),o=(e("../../../core/fetch/value.coffee"),e("./segments.coffee")),i=e("./style.coffee");t.exports=function(e,t,r,s){function l(e){e.attr("x",0).attr("y",0).attr("width",0).attr("height",0)}function u(t,r){r||(r=0),t.attr("x",function(e){var t=e.d3plus.r?2*e.d3plus.r:e.d3plus.width;return-t/2-r/2}).attr("y",function(e){var t=e.d3plus.r?2*e.d3plus.r:e.d3plus.height;return-t/2-r/2}).attr("width",function(e){var t=e.d3plus.r?2*e.d3plus.r:e.d3plus.width;return t+r}).attr("height",function(e){var t=e.d3plus.r?2*e.d3plus.r:e.d3plus.height;return t+r}).attr("rx",function(t){var n=t.d3plus.r?2*t.d3plus.r:t.d3plus.width,a=["circle","donut"].indexOf(e.shape.value)>=0;return a?(n+r)/2:0}).attr("ry",function(t){var n=t.d3plus.r?2*t.d3plus.r:t.d3plus.height,a=["circle","donut"].indexOf(e.shape.value)>=0;return a?(n+r)/2:0}).attr("shape-rendering",function(t){return["square"].indexOf(e.shape.value)>=0?e.shape.rendering.value:"auto"})}function c(t,r,n,a){r||(r=0),"number"!=typeof n&&(n=void 0),"number"!=typeof a&&(a=void 0),t.attrTween("d",function(t){if(void 0===n)var o=t.d3plus.r?t.d3plus.r:d3.max([t.d3plus.width,t.d3plus.height]);else var o=n;if(void 0===a)var i=t.d3plus.segments[t.d3plus.shape];else var i=a;e.arcs[t.d3plus.shape][t.d3plus.id]||(e.arcs[t.d3plus.shape][t.d3plus.id]={r:0},e.arcs[t.d3plus.shape][t.d3plus.id].a="donut"===t.d3plus.shape?2*Math.PI:0);var s=d3.interpolate(e.arcs[t.d3plus.shape][t.d3plus.id].r,o+r),l=d3.interpolate(e.arcs[t.d3plus.shape][t.d3plus.id].a,i);return function(r){return e.arcs[t.d3plus.shape][t.d3plus.id].r=s(r),e.arcs[t.d3plus.shape][t.d3plus.id].a=l(r),f(t)}})}e.arcs||(e.arcs={donut:{},active:{},temp:{}});var f=d3.svg.arc().startAngle(0).endAngle(function(t){var r=e.arcs[t.d3plus.shape][t.d3plus.id].a;return r>2*Math.PI?2*Math.PI:r}).innerRadius(function(t){if(t.d3plus.static||"donut"!==e.shape.value)return 0;var r=e.arcs[t.d3plus.shape][t.d3plus.id].r;return r*e.data.donut.size}).outerRadius(function(t){var r=e.arcs[t.d3plus.shape][t.d3plus.id].r;return"donut"===e.shape.value?r:2*r});t.each(function(t){function r(t){t.attr("stroke",h).attr("stroke-width",1).attr("shape-rendering",e.shape.rendering.value)}var s=o(e,t,"active"),f=o(e,t,"temp"),d=o(e,t,"total"),p=d3.select(this),h=a(e,t),v=[],g=[];if(d&&e.types[e.type.value].fill){if(f){var m=n(t);m.d3plus.shape="temp",v.push(m),g=["temp"]}if(s&&(s=2,t.visible?1:0})},h=function(t){e.draw.timing?t.transition().duration(e.draw.timing).attr("opacity",0).remove():t.remove()},v=function(t){var n="bottom"===e.labels.valign.value?"top":"bottom";t.attr("font-weight",e.labels.font.weight).attr("font-family",e.labels.font.family.value).attr("stroke","none").attr("pointer-events",function(e){return e.mouse?"auto":"none"}).attr("fill",function(t){if(t.color)return t.color;var r=l(t.parent,e),n=c(r),a=t.text?.15:1;return o(r,n,.2,a)}).each(function(t){if(t.resize instanceof Array){t.resize[0],t.resize[1]}var a=t.resize,o=!0;if(t.text){a instanceof Array||(a=[9,50],o=t.resize);var i=t.y-t.h*r[1]/2+t.padding/2;"bottom"===n&&(i+=t.h*r[1]/2),f().align("center").container(d3.select(this)).height(t.h*r[1]/2).padding(t.padding/2).resize(o).size(a).text(e.format.value(100*t.text,{key:"share",vars:e})).width(t.w*r[1]).valign(n).x(t.x-t.w*r[1]/2+t.padding/2).y(i).draw()}else{t.resize instanceof Array||(a=[7,40*(r[1]/r[0])],o=t.resize);var s="bottom"===e.labels.valign.value?t.share:0;f().align(t.anchor||e.labels.align.value).container(d3.select(this)).height(t.h*r[1]-t.share).padding(t.padding/2).resize(o).size(a).shape(t.shape||"square").text(t.names).valign(e.labels.valign.value).width(t.w*r[1]).x(t.x-t.w*r[1]/2+t.padding/2).y(t.y-t.h*r[1]/2+t.padding/2+s).draw()}}).attr("transform",function(e){var t=d3.select(this).attr("transform")||"",n=e.angle||0,a=e.translate&&e.translate.x?e.translate.x:0,o=e.translate&&e.translate.y?e.translate.y:0;return t.length&&(t=t.split(")").slice(-3).join(")")),"rotate("+n+","+a+","+o+")scale("+1/r[1]+")translate("+(e.x*r[1]-e.x)+","+(e.y*r[1]-e.y)+")"+t})};if("edges"===t||e.labels.value){if(e.dev.value){var g="drawing "+t+" labels";i.time(g)}d.each(function(t){function o(t){var r="string"==typeof l.background?l.background:"none"===e.background.value?"#ffffff":e.background.value,n="string"==typeof l.background?l.background:r,a=_.attr("transform").split(")");a.pop(),a.pop(),a.push(""),a=a.join(")"),t.attr("fill",n).attr(E).attr("transform",a)}var i=t.d3plus&&"label"in t.d3plus&&!t.d3plus.label,l=t.d3plus_label||null,c=t.d3plus_share,f=t.d3plus.text?t.d3plus.text:l&&l.names?l.names:e.labels.text.value?a(e,t,e.labels.text.value):n(e,t),d=l&&"group"in l?l.group:d3.select(this),g=0,m=e.types[e.type.value].fill;if(f instanceof Array||(f=[f]),l)if(["line","area"].indexOf(e.shape.value)>=0)var y=!0;else if(t&&"d3plus"in t)var x=s(e,t,"active"),b=s(e,t,"temp"),w=s(e,t,"total"),y=!b&&!x||x>=w||!x&&b>=w;if(i||!(l&&l.force||y)&&m)delete t.d3plus_label,d3.select(this).selectAll("text#d3plus_label_"+t.d3plus.id+", rect#d3plus_label_bg_"+t.d3plus.id).call(h),e.g.labels.selectAll("text#d3plus_label_"+t.d3plus.id+", rect#d3plus_label_bg_"+t.d3plus.id).call(h);else{if(c&&t.d3plus.share&&c.w-2*e.labels.padding>=10&&c.h-2*e.labels.padding>=10&&"middle"!=e.labels.valign.value){c.resize=e.labels.resize.value!==!1&&(!(c&&"resize"in c)||c.resize),c.padding=e.labels.padding,c.text=t.d3plus.share,c.parent=t;var _=d.selectAll("text#d3plus_share_"+t.d3plus.id).data([c],function(e){return e.w+""+e.h+e.text});e.draw.timing&&1===e.zoom.scale?(_.transition().duration(e.draw.timing/2).call(v),_.enter().append("text").attr("id","d3plus_share_"+t.d3plus.id).attr("class","d3plus_share").attr("opacity",0).call(v).transition().duration(e.draw.timing/2).delay(e.draw.timing/2).attr("opacity",1)):(_.attr("opacity",1).call(v),_.enter().append("text").attr("id","d3plus_share_"+t.d3plus.id).attr("class","d3plus_share").attr("opacity",1).call(v)),g=_.node().getBBox().height+e.labels.padding,_.exit().call(h)}else d.selectAll("text.d3plus_share").call(h);if(l&&(l.resize=e.labels.resize.value!==!1&&(!(l&&"resize"in l)||l.resize),l.padding="number"==typeof l.padding?l.padding:e.labels.padding),l&&l.w*r[1]-l.padding>=20&&l.h*r[1]-l.padding>=10&&f.length){for(var k=e.format.locale.value.ui.and,z=e.format.locale.value.ui.more,A=0;A0?O.y:-O.height/2};E.width+=e.labels.padding*r[0],E.height+=e.labels.padding*r[0],E.x-=e.labels.padding*r[0]/2,E.y-=e.labels.padding*r[0]/2;var F=_.attr("transform").match(/translate\(([^a-z]+)\)/gi)[0];F=F.replace(/([^a-z])\s([^a-z])/gi,"$1,$2"),F=F.split(","),F.length>1&&(F=F[F.length-1],F=F.substring(0,F.length-1),E.y+=parseFloat(F))}else var M=[],E={};var S=d.selectAll("rect#d3plus_label_bg_"+t.d3plus.id).data(M),T="number"==typeof l.background?l.background:"string"==typeof l.background?1:.6;e.draw.timing?(S.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),S.transition().duration(e.draw.timing).attr("opacity",T).call(o),S.enter().insert("rect",".d3plus_label").attr("id","d3plus_label_bg_"+t.d3plus.id).attr("class","d3plus_label_bg").attr("opacity",0).call(o).transition().duration(e.draw.timing).attr("opacity",T)):(S.exit().remove(),S.enter().insert("rect",".d3plus_label").attr("id","d3plus_label_bg_"+t.d3plus.id).attr("class","d3plus_label_bg"),S.attr("opacity",T).call(o))}}else delete t.d3plus_label,d3.select(this).selectAll("text#d3plus_label_"+t.d3plus.id+", rect#d3plus_label_bg_"+t.d3plus.id).call(h),e.g.labels.selectAll("text#d3plus_label_"+t.d3plus.id+", rect#d3plus_label_bg_"+t.d3plus.id).call(h)}}),e.dev.value&&i.timeEnd(g)}else{if(e.dev.value){var g="removing "+t+" labels";i.time(g)}d.selectAll("text.d3plus_label, rect.d3plus_label_bg").call(h),e.g.labels.selectAll("text.d3plus_label, rect.d3plus_label_bg").call(h),e.dev.value&&i.timeEnd(g)}}},{"../../../client/rtl.coffee":40,"../../../color/mix.coffee":46,"../../../color/text.coffee":50,"../../../core/console/print.coffee":52,"../../../core/fetch/text.js":66,"../../../core/fetch/value.coffee":67,"../../../string/list.coffee":174,"../../../textwrap/textwrap.coffee":200,"../../../util/copy.coffee":207,"./color.coffee":220,"./segments.coffee":233}],229:[function(e,t,r){function n(e){e.attr("x",function(e){return e.d3plus.x}).attr("y",function(e){return e.d3plus.y}).attr("width",0).attr("height",0)}function a(e,t){void 0===t&&(t=0),e.attr("x",function(e){var r=e.d3plus.r?2*e.d3plus.r:e.d3plus.width;return e.d3plus.x-(r/2+t/2)}).attr("y",function(e){var r=e.d3plus.r?2*e.d3plus.r:e.d3plus.height;return e.d3plus.y-(r/2+t/2)}).attr("width",function(e){var r=e.d3plus.r?2*e.d3plus.r:e.d3plus.width;return r+t}).attr("height",function(e){var r=e.d3plus.r?2*e.d3plus.r:e.d3plus.height;return r+t}).attr("rx",function(e){var r=e.d3plus.r?2*e.d3plus.r:e.d3plus.width;return(r+t)/2}).attr("ry",function(e){var r=e.d3plus.r?2*e.d3plus.r:e.d3plus.height;return(r+t)/2})}function o(e,t,r,n){var o=e.draw.timing?e.timing.mouseevents:0;void 0===n&&(n=0),o?(d3.select(t.parentNode).selectAll("path.d3plus_line").transition().duration(o).style("stroke-width",function(t){var a=r;if(a.constructor!==Number){var o=c(e,t,r);a=o&&o.length?d3.max(o):e.data.stroke.width}return a+n}),d3.select(t.parentNode).selectAll("rect").transition().duration(o).style("stroke-width",function(t){var n=r;if(n.constructor!==Number){var a=c(e,t,r);n=a&&a.length?d3.max(a):e.data.stroke.width}return n}).call(a,n)):(d3.select(t.parentNode).selectAll("path.d3plus_line").style("stroke-width",function(t){var a=r;if(a.constructor!==Number){var o=c(e,t,r);a=o&&o.length?d3.max(o):e.data.stroke.width}return a+n}),d3.select(t.parentNode).selectAll("rect").style("stroke-width",function(t){var n=r;if(n.constructor!==Number){var a=c(e,t,r);n=a&&a.length?d3.max(a):e.data.stroke.width}return n}).call(a,n))}var i=e("../../../util/copy.coffee"),s=e("../../../util/closest.coffee"),l=e("../../../client/pointer.coffee"),u=e("./style.coffee"),c=e("../../../core/fetch/value.coffee");t.exports=function(e,t,r,f){var d=d3.svg.line().x(function(e){return e.d3plus.x}).y(function(e){return e.d3plus.y}).interpolate(e.shape.interpolate.value),p=e.size.value||e.data.stroke.width,h=e[e.axes.discrete],v=function(t){var r=p;if(r.constructor!==Number){var n=c(e,t,p);r=n&&n.length?d3.max(n):e.data.stroke.width}return r<15?15:r},g=h.ticks.values.map(function(e){return e.constructor===Date?e.getTime():e});t.each(function(t){var r=!1,f=[],m=[],y=i(t),x=d3.select(this);y.values=[],y.segment_key=y.key,t.values.forEach(function(n,a,o){var l=c(e,n,h.value);l.constructor===Date&&(l=l.getTime());var u=g.indexOf(s(g,l));r===!1||r===u-1?(y.values.push(n),y.segment_key+="_"+u):(y.values.length>1?f.push(y):m.push(y.values[0]),y=i(t),y.values=[n]),a===o.length-1&&(y.values.length>1?f.push(y):m.push(y.values[0])),r=u});var b=x.selectAll("path.d3plus_line").data(f,function(e){return e.d3plus||(e.d3plus={}),e.d3plus.shape="line",e.segment_key}),w=x.selectAll("rect.d3plus_anchor").data(m,function(e){return e.d3plus||(e.d3plus={}),e.d3plus.r=p,e.d3plus.id});e.draw.timing?(b.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),b.transition().duration(e.draw.timing).attr("d",function(e){return d(e.values)}).call(u,e),b.enter().append("path").attr("class","d3plus_line").style("stroke-linecap","round").attr("d",function(e){return d(e.values)}).call(u,e).attr("opacity",0).transition().duration(e.draw.timing).attr("opacity",1),w.enter().append("rect").attr("class","d3plus_anchor").attr("id",function(e){return e.d3plus.id}).call(n).call(u,e),w.transition().duration(e.draw.timing).call(a).call(u,e),w.exit().transition().duration(e.draw.timing).call(n).remove()):(b.exit().remove(),b.enter().append("path").attr("class","d3plus_line").style("stroke-linecap","round"),b.attr("d",function(e){return d(e.values)}).call(u,e),w.enter().append("rect").attr("class","d3plus_anchor").attr("id",function(e){return e.d3plus.id}),w.exit().remove(),w.call(a).call(u,e));var _=x.selectAll("path.d3plus_mouse").data(f,function(e){return e.segment_key});_.enter().append("path").attr("class","d3plus_mouse").attr("d",function(e){return d(e.values)}).style("stroke","black").style("stroke-width",v).style("fill","none").style("stroke-linecap","round").attr("opacity",0),_.on(l.over,function(t){!e.draw.frozen&&e.mouse.value&&e.mouse.over.value&&o(e,this,p,2)}).on(l.out,function(t){!e.draw.frozen&&e.mouse.value&&e.mouse.out.value&&o(e,this,p,0)}),e.draw.timing?_.transition().duration(e.draw.timing).attr("d",function(e){return d(e.values)}).style("stroke-width",v):_.attr("d",function(e){return d(e.values)}).style("stroke-width",v),_.exit().remove()})}},{"../../../client/pointer.coffee":38,"../../../core/fetch/value.coffee":67,"../../../util/closest.coffee":206,"../../../util/copy.coffee":207,"./style.coffee":234}],230:[function(e,t,r){t.exports=function(e){function t(t){t.attr("d",e.edges.path).style("stroke-width",function(e){return Math.max(1,e.dy)}).style("stroke","#ddd").style("fill","none").attr("transform",function(e){return"translate("+e.d3plus.x+","+e.d3plus.y+")"})}var r=e.returned.edges||[],n=e.g.edges.selectAll("g.d3plus_edge_path").data(r,function(t){return t.d3plus.id="path_"+t[e.edges.source][e.id.value]+"_"+t[e.edges.target][e.id.value],t.d3plus.id});e.draw.timing?(n.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),n.selectAll("text.d3plus_label, rect.d3plus_label_bg").transition().duration(e.draw.timing/2).attr("opacity",0).remove(),n.selectAll("path").data(function(e){return[e]}).transition().duration(e.draw.timing).call(t),n.enter().append("g").attr("class","d3plus_edge_path").append("path").style("stroke-width",0).transition().duration(e.draw.timing).call(t)):(n.exit().remove(),n.selectAll("text.d3plus_label, rect.d3plus_label_bg").remove(),n.selectAll("path").data(function(e){return[e]}).call(t),n.enter().append("g").attr("class","d3plus_edge_path").append("path").call(t))}},{}],231:[function(e,t,r){var n,a,o,i;i=e("./style.coffee"),o={},n={},a={r:{},a:{}},t.exports=function(e,t,r,s){var l,u,c,f,d;c=e.id.nesting[e.depth.value+1],f=d3.svg.line.radial().interpolate("linear-closed").radius(function(e){return e.d3plus.r}).angle(function(e){return e.d3plus.a}),l=function(t){return e.labels.value&&(t.d3plus.label?t.d3plus_label=t.d3plus.label:delete t.d3plus_label),[t]},e.draw.timing?(t.each(function(t){var r,n,a,o,i;for(o=t[c],i=[],n=0,a=o.length;n=0?90:0}:e.d3plus.label?e.d3plus_label=e.d3plus.label:delete e.d3plus_label,[e]},d=function(t){return t.style("stroke-width",e.data.stroke.width).style("stroke","#444").attr("fill","none").attr("shape-rendering",e.shape.rendering.value)},i=function(e){return e.attr("x1",0).attr("x2",0).attr("y1",0).attr("y2",0)},c=function(e){return e.attr("x1",function(e){var t,r,n;return["top","bottom"].indexOf(e.d3plus.position)>=0?0:(t=e.d3plus.offset||0,r=e.d3plus.width||0,n=t<0?-r:r,n+t)}).attr("x2",function(e){return["top","bottom"].indexOf(e.d3plus.position)>=0?0:e.d3plus.offset||0}).attr("y1",function(e){var t,r,n;return["left","right"].indexOf(e.d3plus.position)>=0?0:(r=e.d3plus.offset||0,t=e.d3plus.height||0,n=r<0?-t:t,n+r)}).attr("y2",function(e){return["left","right"].indexOf(e.d3plus.position)>=0?0:e.d3plus.offset||0}).attr("marker-start","url(#d3plus_whisker_marker)")},s=e.defs.selectAll("#d3plus_whisker_marker").data([0]),s.enter().append("marker").attr("id","d3plus_whisker_marker").attr("markerUnits","userSpaceOnUse").style("overflow","visible").append("line"),a=t.datum(),a?(u=a.d3plus.position,l=["top","bottom"].indexOf(u)>=0?"horizontal":"vertical",f="horizontal"===l?a.d3plus.width:a.d3plus.height):(l="horizontal",f=0),s.select("line").attr("x1","horizontal"===l?-f/2:0).attr("x2","horizontal"===l?f/2:0).attr("y1","vertical"===l?-f/2:0).attr("y2","vertical"===l?f/2:0).call(d).style("stroke-width",2*e.data.stroke.width),e.draw.timing?(r.append("line").attr("class","d3plus_data").call(d).call(i),t.selectAll("line.d3plus_data").data(o).transition().duration(e.draw.timing).call(d).call(c),n.selectAll("line.d3plus_data").transition().duration(e.draw.timing).call(i)):(r.append("line").attr("class","d3plus_data"),t.selectAll("line.d3plus_data").data(o).call(d).call(c))}},{}],238:[function(e,t,r){var n=e("../../../client/pointer.coffee"),a=e("../../../client/prefix.coffee"),o=e("../../../core/console/print.coffee"),i=e("../../../client/touch.coffee"),s=e("../zoom/propagation.coffee");t.exports=function(e){e.dev.value&&o.time("creating SVG elements"),e.svg=e.container.value.selectAll("svg#d3plus").data([0]),e.svg.enter().insert("svg","#d3plus_message").attr("id","d3plus").attr("width",e.width.value).attr("height",e.height.value).attr("xmlns","http://www.w3.org/2000/svg").attr("xmlns:xlink","http://www.w3.org/1999/xlink"),e.g.bg=e.svg.selectAll("rect#bg").data(["bg"]),e.g.bg.enter().append("rect").attr("id","bg").attr("fill",e.background.value).attr("stroke","none").attr("width",e.width.value).attr("height",e.height.value),e.g.timeline=e.svg.selectAll("g#timeline").data(["timeline"]),e.g.timeline.enter().append("g").attr("id","timeline").attr("transform","translate(0,"+e.height.value+")"),e.g.legend=e.svg.selectAll("g#key").data(["key"]),e.g.legend.enter().append("g").attr("id","key").attr("transform","translate(0,"+e.height.value+")"),e.g.footer=e.svg.selectAll("g#footer").data(["footer"]),e.g.footer.enter().append("g").attr("id","footer").attr("transform","translate(0,"+e.height.value+")");var t="clipping_"+e.container.id;e.g.clipping=e.svg.selectAll("#clipping").data(["clipping"]),e.g.clipping.enter().append("clipPath").attr("id",t).append("rect").attr("width",e.width.viz).attr("height",e.height.viz),e.g.container=e.svg.selectAll("g#container").data(["container"]),e.g.container.enter().append("g").attr("id","container").attr("clip-path","url(#"+t+")").attr("transform","translate("+e.margin.left+","+e.margin.top+")"),e.g.zoom=e.g.container.selectAll("g#zoom").data(["zoom"]),e.g.zoom.enter().append("g").attr("id","zoom"),e.g.viz=e.g.zoom.selectAll("g#d3plus_viz").data(["d3plus_viz"]),e.g.viz.enter().append("g").attr("id","d3plus_viz"),e.g.overlay=e.g.viz.selectAll("rect#d3plus_overlay").data([{id:"d3plus_overlay"}]),e.g.overlay.enter().append("rect").attr("id","d3plus_overlay").attr("width",e.width.value).attr("height",e.height.value).attr("opacity",0),e.g.overlay.on(n.move,function(t){i&&s(e,d3.event),e.types[e.type.value].zoom&&e.zoom.pan.value&&e.zoom.behavior.scaleExtent()[0]1&&v(B[0])&&(B=o(r,B,[O])),r.size.value&&v(B[0])){var q=[],N=B.filter(function(e){var t=u(r,e,r.size.value);return!(null===t||"d3plus"in e&&e.d3plus.merged)||void q.push(e)});n(N,r.size.value,"desc",[],r),B=N.concat(q)}var P=r.tooltip.children.value===!0?3:r.tooltip.children.value,I="short"===A?P:r.data.large,D=B.length,V=d3.min([D,I]);g={values:[]};for(var R=0;RV&&(g.d3plusMore=D-V)}m.d3plus.tooltip&&(j=c(j,m.d3plus.tooltip)),r.tooltip.size.value&&(C&&"number"!=typeof r.size.value&&(j[p("size")]=C),r.axes.opposite&&r[r.axes.opposite].value!==r.size.value&&(j[p(r.axes.opposite)]=u(r,m,r[r.axes.opposite].value)),r.axes.opposite&&r[r.axes.opposite+"2"].value!==r.size.value&&(j[p(r.axes.opposite+"2")]=u(r,m,r[r.axes.opposite+"2"].value)),r.color.valueScale&&(j[p("color")]=u(r,m,r.color.value)));var J=d(r,m,"active"),W=d(r,m,"temp"),Q=d(r,m,"total");"number"==typeof J&&J>0&&Q&&(j[p("active")]=J+"/"+Q+" ("+r.format.value(J/Q*100,{key:"share",vars:r,data:m})+")"),"number"==typeof W&&W>0&&Q&&(j[p("temp")]=W+"/"+Q+" ("+r.format.value(W/Q*100,{key:"share",vars:r,data:m})+")"),r.tooltip.share.value&&m.d3plus.share&&(j.share=r.format.value(100*m.d3plus.share,{key:"share",vars:r,data:m}));var M="depth"in e?e.depth:y,K=e.title||l(r,m,M)[0],Z=h(m,r.icon.value,u,r,r.id.nesting[M]),$=e.titleOnly?[]:i(r,m,A,j,g,M);if(Z=1===Z.length&&"string"==typeof Z[0]&&Z[0],$.length>0||E||!m.d3plus_label&&"short"==A&&K||m.d3plus_label&&(!("visible"in m.d3plus_label)||"visible"in m.d3plus_label&&m.d3plus_label.visible===!1)){K||(K=r.format.value(Y,{key:r.id.value,vars:r}));var M="d3plus"in m&&"merged"in m.d3plus?y-1:"depth"in e?e.depth:y;if(M<0&&(M=0),M=r.id.nesting[M],"string"==typeof r.icon.style.value)var ee=r.icon.style.value;else if("object"==typeof r.icon.style.value&&r.icon.style.value[M])var ee=r.icon.style.value[M];else var ee="default";var te=r.tooltip.small;e.width?te=e.width:k&&(te=r.tooltip.large);var re=!k&&"long"!==e.length||k&&r.tooltip.fullscreen.value?d3.select("body"):r.container.value;!e.description&&m&&r.tooltip.sub.value&&(e.description=u(r,m,r.tooltip.sub.value)),a({align:z,arrow:b,locale:r.format.locale.value,background:r.tooltip.background,curtain:r.tooltip.curtain.color,curtainopacity:r.tooltip.curtain.opacity,fontcolor:r.tooltip.font.color,fontfamily:r.tooltip.font.family.value,fontsize:r.tooltip.font.size,fontweight:r.tooltip.font.weight,data:$,color:s(r,m),allColors:!0,footer:e.footer===!1?e.footer:E,fullscreen:k,html:t,js:e.js,icon:Z,id:_,max_height:e.maxheight,max_width:te,mouseevents:x,offset:T,parent:re,stacked:r.tooltip.stacked.value,style:ee,title:K,description:e.description,width:e.width||k||0!=$.length?te:"auto",x:F,y:S})}else f(_)}"d3plus"in e.data||(e.data.d3plus={});var r=e.vars,m=e.data,y="d3plus"in m&&"depth"in m.d3plus?m.d3plus.depth:r.depth.value,x=(e.ex,!!e.mouseevents&&e.mouseevents),b=!("arrow"in e)||e.arrow,w=u(r,m,r.id.value),_=e.id||r.type.value;if(!d3.event||"click"!=d3.event.type||!r.tooltip.html.value&&!r.tooltip.value.long||"fullscreen"in e){var k=!1,z=e.anchor||r.tooltip.anchor,A=e.length||"short",j=g(m,r);if(j===-1){var M=r.id.nesting[y-1];u(r,w,M)}var O="";if(r.mouse.click.value&&(!r.mouse.viz||r.mouse.viz.click!==!1))if(1===j&&r.zoom.value)var O=r.format.value(r.format.locale.value.ui.expand);else if(j===-1&&r.zoom.value&&r.history.states.length&&!r.tooltip.value.long)var O=r.format.value(r.format.locale.value.ui.collapse);else if(r.small||"short"!=A||!r.tooltip.html.value&&!r.tooltip.value.long||1===r.focus.value.length&&r.focus.value[0]==w){if("long"==A)var O=r.footer.value||""}else var O=r.format.locale.value.ui.moreInfo;var E=!!O.length&&r.format.value(O,{key:"footer",vars:r})}else{var k=!0,b=!1,x=!0,A="long",E=r.footer.value;r.covered=!0}if("x"in e)var F=e.x;else if("static"===r.types[r.type.value].tooltip){var F=m.d3plus.x;r.zoom.translate&&r.zoom.scale&&(F=r.zoom.translate[0]+F*r.zoom.scale),F+=r.margin.left,"long"!==e.length&&(S+=p.x(),F+=r.container.value.node().getBoundingClientRect().left,F+=parseFloat(r.container.value.style("padding-left"),10))}else var F=d3.mouse(d3.select("html").node())[0];if("y"in e)var S=e.y;else if("static"==r.types[r.type.value].tooltip){var S=m.d3plus.y;r.zoom.translate&&r.zoom.scale&&(S=r.zoom.translate[1]+S*r.zoom.scale),S+=r.margin.top,"long"!==e.length&&(S+=p.y(),S+=r.container.value.node().getBoundingClientRect().top,S+=parseFloat(r.container.value.style("padding-top"),10))}else var S=d3.mouse(d3.select("html").node())[1];if("offset"in e)var T=e.offset;else if("static"==r.types[r.type.value].tooltip){var T=m.d3plus.r?m.d3plus.r:m.d3plus.height/2;r.zoom.scale&&(T*=r.zoom.scale)}else var T=3;if(k||"long"===e.length)if("string"==typeof r.tooltip.html.value)t(r.tooltip.html.value);else if("function"==typeof r.tooltip.html.value)t(r.tooltip.html.value(w));else if(r.tooltip.html.value&&"object"==typeof r.tooltip.html.value&&r.tooltip.html.value.url){var B=r.tooltip.html.value.url;"function"==typeof B&&(B=B(w)),d3.json(B,function(e){var n=r.tooltip.html.value.callback?r.tooltip.html.value.callback(e):e;t(n)})}else t(e.html);else t(e.html)}},{"../../../array/sort.coffee":34,"../../../client/scroll.js":41,"../../../core/data/nest.js":60,"../../../core/fetch/color.coffee":63,"../../../core/fetch/text.js":66,"../../../core/fetch/value.coffee":67,"../../../object/merge.coffee":171,"../../../object/validate.coffee":172,"../../../tooltip/create.js":201,"../../../tooltip/remove.coffee":203,"../../../util/uniques.coffee":210,"../shapes/segments.coffee":233,"../zoom/direction.coffee":250,"./data.js":241}],241:[function(e,t,r){var n=e("../../../util/copy.coffee"),a=e("../../../core/fetch/value.coffee"),o=e("../../../core/fetch/color.coffee"),i=e("../../../core/fetch/text.js"),s=e("../../../color/legible.coffee"),l=e("../../../object/merge.coffee"),u=e("../../../client/prefix.coffee"),c=e("../../../string/format.js"),f=e("../../../object/validate.coffee");t.exports=function(e,t,r,d,p,h){function v(r,n){if(e.attrs.value[n])var o=n;else var o=null;n&&(n=e.format.value(n));var i=m[r]||a(e,t,r,o);if(f(i))w.push({name:e.format.value(r),value:e.format.value(i.value,{key:i.key,vars:e}),group:n});else if(null!=i&&"undefined"!=i&&!(i instanceof Array)&&("string"==typeof i&&i.indexOf("d3plus_other")<0||"string"!=typeof i)){var s=e.format.locale.value.ui[r]?e.format.value(e.format.locale.value.ui[r]):e.format.value(r),l=x.indexOf(r)>=0;i instanceof Array?i.forEach(function(n){n=e.format.value(n,{key:r,vars:e,data:t})}):i=e.format.value(i,{key:r,vars:e,data:t});var u={name:s,value:i,highlight:l,group:n};if(e.descs.value)if("function"==typeof e.descs.value){var c=e.descs.value(r);"string"==typeof c&&(u.desc=c)}else r in e.descs.value&&(u.desc=e.descs.value[r]);w.push(u)}}if(e.small)return[];if(!r)var r="long";if("long"==r)var g="short";else var g="long";var m={};if(d&&"string"==typeof d)d=[d];else if(d&&"object"==typeof d){m=l(m,d);var d=[];for(var y in m)d.push(y)}else if(!d)var d=[];var x=[];if(e.tooltip.value instanceof Array)var b=e.tooltip.value;else if("string"==typeof e.tooltip.value)var b=[e.tooltip.value];else{if(e.tooltip.value[e.id.nesting[h]])var b=e.tooltip.value[e.id.nesting[h]];else var b=e.tooltip.value;b instanceof Array||(b=b[r]?b[r]:b[g]?[]:l({"":[]},b)),"string"==typeof b?b=[b]:b instanceof Array||(b=l({"":[]},b))}var w=[];if(b.constructor===Array&&(b={"":b}),e.id.nesting.length&&hh&&b[e]&&delete b[e]})}for(var _ in b){b[_].constructor!==Array&&(b[_]=[b[_]]);for(var k=d.length;k>0;k--)b[_].indexOf(d[k-1])>=0&&d.splice(k-1,1)}if(e.tooltip.value.long&&"object"==typeof e.tooltip.value.long){for(var _ in e.tooltip.value.long)for(var k=d.length;k>0;k--){var z=d[k-1];e.tooltip.value.long[_].indexOf(z)>=0&&(b[_]||(b[_]=[]),b[_].push(z),d.splice(k-1,1))}}d.length&&(b[""]||(b[""]=[]),b[""]=b[""].concat(d));for(var _ in b)b[_].forEach(function(e){v(e,_)});if(p){var A=e.format.locale.value.ui.including,j=p.d3plus_colors;p.values.forEach(function(t){var r=d3.keys(t)[0];w.push({group:e.format.value(A),highlight:!(!j||!j[r])&&j[r],name:r,value:t[r]})}),p.d3plusMore&&w.push({group:e.format.value(A),highlight:!0,name:c(e.format.locale.value.ui.more,p.d3plusMore),value:""})}if(e.tooltip.connections.value&&"long"===r){var M=e.edges.connections(t[e.id.value],e.id.value,!0);M.length&&M.forEach(function(t){var r=e.data.viz.filter(function(r){return r[e.id.value]===t[e.id.value]}),r=r.length?r[0]:t,n=i(e,r)[0],a=o(e,r),l=e.tooltip.font.size,c="square"==e.shape.value?0:l;styles=["background-color: "+a,"border-color: "+s(a),"border-style: solid","border-width: "+e.data.stroke.width+"px","display: inline-block","height: "+l+"px","left: 0px","position: absolute","width: "+l+"px","top: 0px",u()+"border-radius: "+c+"px"],node="
";var f=function(){e.self.focus([r[e.id.value]]).draw()};w.push({group:e.format.value(e.format.locale.value.ui.primary),highlight:!1,link:f,name:""})})}return w}},{"../../../client/prefix.coffee":39,"../../../color/legible.coffee":44,"../../../core/fetch/color.coffee":63,"../../../core/fetch/text.js":66,"../../../core/fetch/value.coffee":67,"../../../object/merge.coffee":171,"../../../object/validate.coffee":172,"../../../string/format.js":173,"../../../util/copy.coffee":207}],242:[function(e,t,r){var n;n=e("../../../core/console/print.coffee"),t.exports=function(e){var t,r,a,o,i,s,l,u,c,f;if(e.group=e.g.apps[e.type.value],e.mouse.viz=!1,e.edges.path=!1,f=e.types[e.type.value],u=f.requirements||[],a=u.indexOf("data")>=0,o=!a||a&&e.data.viz.length,!e.error.internal&&o){for(t=e.format.locale.value.visualization[e.type.value],e.dev.value&&n.time("running "+t),l=e.data.viz,i=0,s=l.length;i1&&r).focus({callback:o}).format(e.format.locale.language).format({number:e.format.number.value,text:e.format.text.value}).title(e.format.value(s)).type(t.type||"auto").ui({align:e.ui.align.value,border:e.ui.border,color:{primary:e.ui.color.primary.value,secondary:e.ui.color.secondary.value},padding:e.ui.padding,margin:0}).width(t.width||!1).draw()});var c=s.node().offsetHeight||s.node().getBoundingClientRect().height;c&&(e.margin[r]+=c),e.dev.value&&t&&o.timeEnd("drawing custom UI elements")}},{"../../../core/console/print.coffee":52,"../../../form/form.js":104,"../../../object/validate.coffee":172,"../../../util/copy.coffee":207}],244:[function(e,t,r){var n,a,o,i;n=e("../../../client/pointer.coffee"),a=e("../../../color/lighter.coffee"),o=e("../../../core/console/print.coffee"),i=e("../../../client/css.coffee"),t.exports=function(e){var t,r,s,l,u,c,f,d,p,h,v,g,m,y,x;return!e.small&&e.history.states.length>0?(e.dev.value&&o.time("drawing back button"),t=e.container.value.selectAll("div#d3plus_back_button").data(["d3plus_back_button"]).style("position","relative").style("z-index",1900),p=e.title.sub.font.size,r=e.title.sub.font.color,u=e.title.sub.font.family.value,x=e.title.sub.font.weight,d=e.title.sub.padding,g=!1,e.title.sub.value&&["start","left"].indexOf(e.title.sub.font.align)<0?g="sub":e.title.total.value&&["start","left"].indexOf(e.title.total.font.align)<0?g="total":e.title.value&&["start","left"].indexOf(e.title.font.align)<0&&(g="title"),g?(h=function(e){var t;return t=e.attr("transform").match(/translate\(([^a-z]+)\)/gi)[0],t=t.replace(/([^a-z])\s([^a-z])/gi,"$1,$2"),t=t.split(","),t=t[t.length-1],parseFloat(t.substring(0,t.length-1))},m=e.svg.select(".d3plus_title."+g),y=h(m)+h(m.select("text"))):(y=e.margin.top-e.title.padding,f=p+2*d,e.margin.top+=f),s=parseFloat(e.container.value.style("padding-top"),10),y+=s,s=parseFloat(e.container.value.style("padding-left"),10),c=e.margin.left+p/2+s,v=function(e){return e.style("position","absolute").style("left",c+"px").style("top",y+"px").style("color",r).style("font-family",u).style("font-weight",x).style("font-size",p+"px")},l=t.enter().append("div").attr("id","d3plus_back_button").style("opacity",0).call(v).html(function(){var t;return i("font-awesome")&&0===e.icon.back.value.indexOf("fa-")?(t=""):t=e.icon.back.value+" ",t+e.format.value(e.format.locale.value.ui.back)}),t.on(n.over,function(){if(!e.small&&e.history.states.length>0)return d3.select(this).style("cursor","pointer").transition().duration(e.timing.mouseevents).style("color",a(r,.25))}).on(n.out,function(){if(!e.small&&e.history.states.length>0)return d3.select(this).style("cursor","auto").transition().duration(e.timing.mouseevents).style("color",r)}).on(n.click,function(){return e.history.back()}).transition().duration(e.draw.timing).style("opacity",1).call(v),e.dev.value?o.timeEnd("drawing back button"):void 0):e.container.value.selectAll("div#d3plus_back_button").transition().duration(e.draw.timing).style("opacity",0).remove()}},{"../../../client/css.coffee":36,"../../../client/pointer.coffee":38,"../../../color/lighter.coffee":45,"../../../core/console/print.coffee":52}],245:[function(e,t,r){var n=e("../../../array/sort.coffee"),a=e("../../../util/buckets.coffee"),o=e("../../../util/copy.coffee"),i=e("../tooltip/create.js"),s=e("../../../core/data/nest.js"),l=e("../../../util/dataURL.coffee"),u=e("../../../client/pointer.coffee"),c=e("../../../core/fetch/value.coffee"),f=e("../../../core/fetch/color.coffee"),d=e("../../../core/fetch/text.js"),p=e("../../../core/console/print.coffee"),h=e("../../../tooltip/remove.coffee"),v=e("../../../color/text.coffee"),g=e("../../../util/uniques.coffee"),m=e("../../../client/scroll.js"),y=e("../../../string/strip.js"),x=e("../../../textwrap/textwrap.coffee"),b=(e("../../../client/touch.coffee"),e("../../../object/validate.coffee"));t.exports=function(e){function t(t){t.attr("transform",function(t,r){var n=B+r*(e.ui.padding+_);return"translate("+n+","+e.ui.padding+")"})}function r(t){t.attr("width",_).attr("height",_).attr("fill",function(t){d3.select(this.parentNode).select("text").remove();var r=g(t,e.icon.value,c,e,V),n=f(e,t,V);if(e.legend.icons.value&&1===r.length&&"string"==typeof r[0]){r=r[0];var a,o=y(r+"_"+n),i=e.icon.style.value,s=e.defs.selectAll("pattern#"+o).data([o]);a="string"==typeof i?e.icon.style.value:b(i)&&i[V]?i[V]:"default",n="knockout"==a?n:"none",s.select("rect").transition().duration(e.draw.timing).attr("fill",n).attr("width",_).attr("height",_),s.select("image").transition().duration(e.draw.timing).attr("width",_).attr("height",_);var u=s.enter().append("pattern").attr("id",o).attr("width",_).attr("height",_);return u.append("rect").attr("fill",n).attr("stroke","none").attr("width",_).attr("height",_),u.append("image").attr("xlink:href",r).attr("width",_).attr("height",_).each(function(e){0===r.indexOf("/")||r.indexOf(window.location.hostname)>=0?l(r,function(e){s.select("image").attr("xlink:href",e)}):s.select("image").attr("xlink:href",r)}),"url(#"+o+")"}if(e.legend.labels.value){var p;if(p=e.legend.text.value?[c(e,t,e.legend.text.value,D)]:d(e,t,D),1===p.length&&!(p[0]instanceof Array)&&p[0].length){var h=d3.select(this.parentNode).append("text"),m=e.legend.font.size;m instanceof Array||(m=[m]),h.attr("font-size",m[m.length-1]+"px").attr("font-weight",e.legend.font.weight).attr("font-family",e.legend.font.family.value).attr("stroke","none").attr("fill",v(n)).attr("x",0).attr("y",0).each(function(t){x().align("middle").container(d3.select(this)).height(_).padding(e.ui.padding).resize(m.length>1).size(m).text(p[0]).width(_).valign("middle").draw()}),h.select("tspan").empty()&&h.remove()}}return n})}var w=!0,_=0;if(!e.error.internal&&e.color.value&&!e.small&&e.legend.value)if(e.color.valueScale)if(e.color.valueScale){e.dev.value&&p.time("drawing color scale"),e.g.legend.selectAll("g.d3plus_color").transition().duration(e.draw.timing).attr("opacity",0).remove();var k=e.color.valueScale.domain(),z=e.color.valueScale.range();k.length<=2&&(k=a(k,6));var A=e.g.legend.selectAll("g.d3plus_scale").data(["scale"]);A.enter().append("g").attr("class","d3plus_scale").attr("opacity",0);var j=e.container.id+"_legend_heatmap",M=A.selectAll("#"+j).data(["heatmap"]);M.enter().append("linearGradient").attr("id",j).attr("x1","0%").attr("y1","0%").attr("x2","100%").attr("y2","0%").attr("spreadMethod","pad");var O=M.selectAll("stop").data(d3.range(0,z.length));O.enter().append("stop").attr("stop-opacity",1),O.attr("offset",function(e){return Math.round(e/(z.length-1)*100)+"%"}).attr("stop-color",function(e){return z[e]}),O.exit().remove();var E=A.selectAll("rect#gradient").data(["gradient"]);E.enter().append("rect").attr("id","gradient").attr("x",function(t){return"middle"==e.legend.align?e.width.value/2:"end"==e.legend.align?e.width.value:0}).attr("y",e.ui.padding).attr("width",0).attr("height",e.legend.gradient.height).attr("stroke",e.legend.font.color).attr("stroke-width",1).style("fill","url(#"+j+")");var F=A.selectAll("text.d3plus_tick").data(d3.range(0,k.length));F.enter().append("text").attr("class","d3plus_tick").attr("stroke","none").attr("x",function(t){return"middle"==e.legend.align?e.width.value/2:"end"==e.legend.align?e.width.value:0}).attr("y",function(t){return this.getBBox().height+e.legend.gradient.height+2*e.ui.padding});var S=0;F.order().attr("font-weight",e.legend.font.weight).attr("font-family",e.legend.font.family.value).attr("font-size",e.legend.font.size+"px").style("text-anchor",e.legend.font.align).attr("fill",e.legend.font.color).text(function(t){return e.format.value(k[t],{key:e.color.value,vars:e})}).attr("y",function(t){return this.getBBox().height+e.legend.gradient.height+2*e.ui.padding}).each(function(e){var t=Math.ceil(this.getBBox().width);t>S&&(S=t)}),S+=2*e.labels.padding;var T=S*(k.length-1);if(T+S=0){if(q=o(e.nodes.restriced||e.nodes.value),e.data.viz.length)for(var N=0;N=0)D=R,V=e.id.nesting[R];else for(var U=0;U<=e.depth.value;U++){D=U,V=e.id.nesting[U];var L=g(q,function(t){return c(e,t,V)}),Y=g(q,I);if(L.length>=Y.length&&Y.length>1)break}var H=[e.color.value],z=s(e,q,H,!1);e.dev.value&&p.timeEnd("grouping data by color");var X=e.width.value;_=e.legend.size;var T=_*z.length+e.ui.padding*(z.length+1);if(_ instanceof Array){e.dev.value&&p.time("calculating legend size");for(var N=_[1];N>=_[0];N--)if(T=N*z.length+e.ui.padding*(z.length+1),X>=T){_=N;break}e.dev.value&&p.timeEnd("calculating legend size")}else"number"!=typeof _&&_!==!1&&(_=30);if(X=0?d(e,t,f)[0]:e.format.value(c(e,t,e.color.value,V),{key:e.color.value,vars:e,data:t});var p,h;if(e.legend.filters.value&&!(l instanceof Array)){p="
";var v=e.format.locale.value;p+="
"+e.format.value(v.method.mute)+"
",p+="
"+e.format.value(v.method.solo)+"
",p+="
",h=function(t){var r={border:"1px solid #ccc",display:"inline-block",margin:"1px 2px",padding:"3px 5px"};t.select(".mute").style(r).on(u.over,function(){d3.select(this).style("cursor","pointer")}).on(u.click,function(){var t=e.id.mute.value;e.history.states.push(function(){e.self.id({mute:t}).draw()}),e.self.id({mute:l}).draw()}),t.select(".solo").style(r).on(u.over,function(){d3.select(this).style("cursor","pointer")}).on(u.click,function(){var t=e.id.solo.value;e.history.states.push(function(){e.self.id({solo:t}).draw()}),e.self.id({solo:l}).draw()})}}i({data:t,html:p,js:h,depth:D,footer:!1,vars:e,x:o,y:s,mouseevents:this,title:n,titleOnly:!e.legend.data.value,offset:.4*_})}).on(u.out,function(t){h(e.type.value)}),e.dev.value&&p.timeEnd("drawing legend")}}else w=!1;if(e.legend.value&&key&&w){if(e.dev.value&&p.time("positioning legend"),_)var K=_+e.ui.padding;else var Z=e.g.legend.node().getBBox(),K=Z.height+Z.y;0===e.margin.bottom&&(e.margin.bottom+=e.ui.padding),e.margin.bottom+=K,e.g.legend.transition().duration(e.draw.timing).attr("transform","translate(0,"+(e.height.value-e.margin.bottom)+")"),e.dev.value&&p.timeEnd("positioning legend")}else e.dev.value&&p.time("hiding legend"),e.g.legend.transition().duration(e.draw.timing).attr("transform","translate(0,"+e.height.value+")"),e.dev.value&&p.timeEnd("hiding legend")}},{"../../../array/sort.coffee":34,"../../../client/pointer.coffee":38,"../../../client/scroll.js":41,"../../../client/touch.coffee":43,"../../../color/text.coffee":50,"../../../core/console/print.coffee":52,"../../../core/data/nest.js":60,"../../../core/fetch/color.coffee":63,"../../../core/fetch/text.js":66,"../../../core/fetch/value.coffee":67,"../../../object/validate.coffee":172,"../../../string/strip.js":175,"../../../textwrap/textwrap.coffee":200,"../../../tooltip/remove.coffee":203,"../../../util/buckets.coffee":204,"../../../util/copy.coffee":207,"../../../util/dataURL.coffee":209,"../../../util/uniques.coffee":210,"../tooltip/create.js":240}],246:[function(e,t,r){var n=e("../../../client/pointer.coffee"),a=e("../../../color/text.coffee");t.exports=function(e,t){function r(t){t.style(i).style("position","absolute").style("background-color",l).style("text-align","center").style("left",function(){return"center"==s?"50%":"0px"}).style("width",function(){return"center"==s?"auto":e.width.value+"px"}).style("margin-left",function(){return"center"==s?-(this.offsetWidth/2)+"px":"0px"}).style("top",function(){return"center"==s?"50%":"top"==s?"0px":"auto"}).style("bottom",function(){return"bottom"==s?"0px":"auto"}).style("margin-top",function(){if("large"==o){var e=this.offsetHeight||this.getBoundingClientRect().height;return-e/2+"px"}return"0px"})}t=e.messages.value?t:null;var o=e.messages.style.value||(t===e.error.internal?"large":e.messages.style.backup);if("large"===o)var i=e.messages,s="center";else{if(e.footer.value)var i=e.footer;else if(e.title.value)var i=e.title;else if(e.title.sub.value)var i=e.title.sub;else if(e.title.total.value)var i=e.title.total;else var i=e.title.sub;var s=i.position}var i={color:i.font.color,"font-family":i.font.family.value,"font-weight":i.font.weight,"font-size":i.font.size+"px",padding:i.padding+"px"},l=e.messages.background.value;l||(l=e.background.value,"none"!==l&&"transparent"!==l||(l=a(i.color))),e.g.message=e.container.value.selectAll("div#d3plus_message").data(["message"]);var u=e.g.message.enter().append("div").attr("id","d3plus_message").attr("opacity",0);u.append("div").attr("class","d3plus_message_text").style("display","block"),e.g.message.select(".d3plus_message_text").text(t?t:e.g.message.text());var c=navigator.onLine,f=75,d=e.g.message.selectAll(".d3plus_message_branding").data(e.messages.branding.value&&"center"===s?[0]:[]);d.enter().append("div").attr("class","d3plus_message_branding").style("margin-top","15px").style("padding-top","0px").style("display","block").style("font-size","11px").style("background-size",f+"px").style("background-position","center 10px").style("background-repeat","no-repeat").style("cursor","pointer").on(n.click,function(){window.open("http://www.d3plus.org/","_blank")});var p=d3.hsl(l).l<.5?e.messages.branding.image.dark:e.messages.branding.image.light;d.text(c?"Powered by:":"Powered by D3plus").style("background-color",c?l:"transparent").style("background-image",c?"url('"+p+"')":"none").style("min-width",c?f+"px":"auto").style("height",c?f+"px":"auto"),d.exit().remove(),e.g.message.style("display",t?"inline-block":"none").call(r).style("opacity",t?1:0)}},{"../../../client/pointer.coffee":38,"../../../color/text.coffee":50}],247:[function(e,t,r){var n,a,o,i,s,l,u,c,f,d;n=e("../../../util/closest.coffee"),a=e("../../../client/css.coffee"),i=e("../../../font/sizes.coffee"),o=e("../../../client/pointer.coffee"),s=e("../../../color/mix.coffee"),u=e("../../../client/prefix.coffee"),c=e("../../../core/console/print.coffee"),f=e("../../../color/text.coffee"),d=e("../../../core/data/time.coffee"),l=!1,t.exports=function(e){var t,r,i,p,h,v,g,m,y,x,b,w,_,k,z,A,j,M,O,E,F,S,T,B,C,q,N,P,I,D,V,R,U,L,Y,H,X,G,J,W,Q,K,Z,$,ee,te,re,ne,ae,oe,ie;if(!e.timeline.value||e.error.internal&&e.data.missing||e.small||!e.data.time||!(e.data.time.values.length>1))return e.g.timeline.transition().duration(e.draw.timing).attr("transform","translate(0,"+e.height.value+")");if(e.dev.value&&c.time("drawing timeline"),H={"font-weight":e.ui.font.weight,"font-family":e.ui.font.family.value,"font-size":e.ui.font.size+"px","text-anchor":"middle"},ie=e.data.time.ticks.map(function(e){return new Date(e)}),Q=d(e,{values:ie,style:H}),te=Q.values.map(Number),W=Q.format,e.time.solo.value.length)for(w=d3.extent(e.time.solo.value),b=_=0,A=w.length;_=ne,t=e.width.value-2*e.ui.padding,U&&e.timeline.play.value&&(t-=N+e.ui.padding),!U||te.length=1)e=[r,t];else if(O+1<=ie.length)e=[r,oe[O+1]];else{for(e=[r],b=1;b<=1;)O+b<=ie.length?e.push(oe[O+b]):e.unshift(oe[O-(O+b-ie.length)]),b++;e=[e[0],e[e.length-1]]}return p=e,L.attr("fill",Y),d3.select(this).call(i.extent(e))}},P=function(){var t;return j-O===ie.length-$?t=[]:(t=ae.filter(function(e,t){return t>=O&&t=p[0]&&n?(a=1,r=f(e.ui.color.secondary.value)):(a=.5,r=f(e.ui.color.primary.value)),$&&e.background.value&&"none"!==e.background.value&&(r=d3.rgb(f(e.background.value))),r=d3.rgb(r),"rgba("+r.r+","+r.g+","+r.b+","+a+")"},r=e.g.timeline.selectAll("rect.d3plus_timeline_background").data(["background"]),r.enter().append("rect").attr("class","d3plus_timeline_background").attr("shape-rendering","crispEdges").attr("width",ee+2).attr("height",Z+2).attr("fill",e.ui.color.primary.value).attr("x",D-1).attr("y",e.ui.padding),r.transition().duration(e.draw.timing).attr("width",ee+2).attr("height",Z+2).attr("fill",e.ui.color.primary.value).attr("x",D-1).attr("y",e.ui.padding),J=e.g.timeline.selectAll("g#ticks").data(["ticks"]),J.enter().append("g").attr("id","ticks").attr("transform","translate("+e.width.value/2+","+e.ui.padding+")"),h=e.g.timeline.selectAll("g#brush").data(["brush"]),h.enter().append("g").attr("id","brush"),z=e.g.timeline.selectAll("g#labels").data(["labels"]),z.enter().append("g").attr("id","labels"),L=z.selectAll("text").data(ie,function(e,t){return t}),L.enter().append("text").attr("stroke","none").attr("y",0).attr("dy","0.5ex").attr("x",0),re=d3.time.scale().domain(d3.extent(oe)).rangeRound([0,ee]),L.order().attr(H).text(function(e,t){return te.indexOf(+e)>=0?W(e):""}).attr("opacity",function(t,r){return e.data.time.dataSteps.indexOf(r)>=0?1:.4}).attr("fill",Y).attr("transform",function(t,r){var n,a;return n=D+re(t),$||(n+=k/2),a=Z/2+e.ui.padding+1,$&&(a+=Z/2+ne),"translate("+Math.round(n)+","+Math.round(a)+")"}),L.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),i=d3.svg.brush().x(re).extent(p).on("brush",v).on("brushend",g),X=e.axes.discrete&&e[e.axes.discrete].value===e.time.value?e[e.axes.discrete].ticks.color:e.x.ticks.color,J.attr("transform","translate("+D+","+(e.ui.padding+1)+")").transition().duration(e.draw.timing).call(d3.svg.axis().scale(re).orient("top").ticks(function(){return oe}).tickFormat("").tickSize(-Z).tickPadding(0)).selectAll("line").attr("stroke-width",1).attr("shape-rendering","crispEdges").attr("stroke",function(t){return te.indexOf(+t)>=0?X:s(X,e.background.value,.4,1)}),J.selectAll("path").attr("fill","none"),h.attr("transform","translate("+D+","+(e.ui.padding+1)+")").attr("opacity",1).call(i),L.attr("pointer-events","none"),h.selectAll("rect.background").attr("fill","none").style("visibility","visible").attr("height",Z).attr("shape-rendering","crispEdges").on(o.move,function(){var t;return t=e.timeline.hover.value,["grab","grabbing"].indexOf(t)>=0&&(t=u()+t),d3.select(this).style("cursor",t)}),h.selectAll("rect.extent").attr("opacity",.75).attr("height",Z).attr("fill",e.ui.color.secondary.value).attr("shape-rendering","crispEdges").on(o.move,function(){var t;return t=e.timeline.hover.value,["grab","grabbing"].indexOf(t)>=0&&(t=u()+t),d3.select(this).style("cursor",t)}),e.timeline.handles.value?(x=h.selectAll("g.resize").selectAll("rect.d3plus_handle").data(["d3plus_handle"]),x.enter().insert("rect","rect").attr("class","d3plus_handle"),x.attr("fill",e.timeline.handles.color).attr("transform",function(t){var r;return r="resize e"===this.parentNode.className.baseVal?-e.timeline.handles.size:0,"translate("+r+",0)"}).attr("width",e.timeline.handles.size).style("visibility","visible").attr("shape-rendering","crispEdges").attr("opacity",e.timeline.handles.opacity),h.selectAll("g.resize").selectAll("rect").attr("height",Z)):h.selectAll("g.resize").remove(),K=e.g.timeline.node().getBBox(),0===e.margin.bottom&&(e.margin.bottom+=e.ui.padding),e.margin.bottom+=K.height+K.y,e.g.timeline.transition().duration(e.draw.timing).attr("transform","translate(0,"+Math.round(e.height.value-e.margin.bottom-e.ui.padding/2)+")"),e.margin.bottom+=e.ui.padding,e.dev.value?c.time("drawing timeline"):void 0}},{"../../../client/css.coffee":36,"../../../client/pointer.coffee":38,"../../../client/prefix.coffee":39,"../../../color/mix.coffee":46,"../../../color/text.coffee":50,"../../../core/console/print.coffee":52,"../../../core/data/time.coffee":62,"../../../font/sizes.coffee":102,"../../../util/closest.coffee":206}],248:[function(e,t,r){var n=e("../../../client/pointer.coffee"),a=e("../../../core/fetch/value.coffee"),o=e("../../../core/console/print.coffee"),i=e("../../../client/rtl.coffee"),s=e("../../../textwrap/textwrap.coffee");t.exports=function(e){function t(t){t.attr("font-size",function(e){return e.style.font.size}).attr("fill",function(t){return t.link?e.links.font.color:t.style.font.color}).attr("font-family",function(t){return t.link?e.links.font.family.value:t.style.font.family.value}).attr("font-weight",function(t){return t.link?e.links.font.weight:t.style.font.weight}).style("text-decoration",function(t){return t.link?e.links.font.decoration.value:t.style.font.decoration.value}).style("text-transform",function(t){return t.link?e.links.font.transform.value:t.style.font.transform.value})}function r(e){var t=e.style.font.align;return"center"==t?"middle":"left"==t&&!i||"right"==t&&i?"start":"left"==t&&i||"right"==t&&!i?"end":t}var l=e.size.value?e.size.value:"number"===e.color.type&&e.color.value;if(e.data.viz&&e.title.total.value&&!e.small)if(l){e.dev.value&&o.time("calculating total value");var u=e.data.pool;e.focus.value.length&&(u=e.data.viz.filter(function(t){return t[e.id.value]==e.focus.value[0]}));var c,f=e.aggs.value[l]||"sum";if(f.constructor===Function?c=f(u):(u=u.reduce(function(t,r){var n=a(e,r,l);return n instanceof Array?t=t.concat(n):t.push(n),t},[]),c=d3[f](u)),0!==c&&null!==c&&void 0!==c||(c=!1),"number"==typeof c){var d="";if(e.data.mute.length||e.data.solo.length||e.focus.value.length){var p=d3.sum(e.data.value,function(t){if(e.time.solo.value.length>0)var r=e.time.solo.value.indexOf(a(e,t,e.time.value))>=0;else if(e.time.mute.value.length>0)var r=e.time.solo.value.indexOf(a(e,t,e.time.value))<0;else var r=!0;if(r)return a(e,t,l)});if(p>c){var d=c/p*100,h=e.format.value(p,{key:e.size.value,vars:e});d=" ("+e.format.value(d,{key:"share",vars:e})+" of "+h+")"}}c=e.format.value(c,{key:e.size.value,vars:e});var v=e.title.total.value,g=v.prefix||e.format.value(e.format.locale.value.ui.total)+": ";c=g+c,v.suffix?c+=v.suffix:null,c+=d}e.dev.value&&o.timeEnd("calculating total value")}else var c=!1;else var c=!1;var m=[];if(e.footer.value&&m.push({link:e.footer.link,style:e.footer,type:"footer",value:e.footer.value}),!e.small){if(e.title.value){var y=e.title.value;"function"==typeof y&&(y=y(e.self)),m.push({link:e.title.link,style:e.title,type:"title",value:y})}if(e.title.sub.value){var y=e.title.sub.value;"function"==typeof y&&(y=y(e.self)),m.push({link:e.title.sub.link,style:e.title.sub,type:"sub",value:y})}e.title.total.value&&c&&m.push({link:e.title.total.link,style:e.title.total,type:"total",value:c})}e.dev.value&&o.time("drawing titles");var x=e.svg.selectAll("g.d3plus_title").data(m,function(e){return e.type}),b=e.title.width||e.width.value-e.margin.left-e.margin.right;x.enter().append("g").attr("class",function(e){return"d3plus_title "+e.type}).attr("opacity",0).append("text").attr("stroke","none").call(t),x.each(function(n){var a=d3.select(this).select("text").call(t),o=r(n);s().align(o).container(a).height(e.height.value/2).size(!1).text(n.value).width(b).draw(),n.y=e.margin[n.style.position],e.margin[n.style.position]+=this.getBBox().height+2*n.style.padding}).on(n.over,function(t){t.link&&d3.select(this).transition().duration(e.timing.mouseevents).style("cursor","pointer").select("text").attr("fill",e.links.hover.color).attr("font-family",e.links.hover.family.value).attr("font-weight",e.links.hover.weight).style("text-decoration",e.links.hover.decoration.value).style("text-transform",e.links.hover.transform.value)}).on(n.out,function(r){r.link&&d3.select(this).transition().duration(e.timing.mouseevents).style("cursor","auto").select("text").call(t)}).on(n.click,function(e){if(e.link){var t="/"!=e.link.charAt(0)?"_blank":"_self";window.open(e.link,t)}}).attr("opacity",1).attr("transform",function(t){var n=t.style.position,a="top"==n?0+t.y:e.height.value-t.y;"bottom"==n?a-=this.getBBox().height+t.style.padding:a+=t.style.padding;var o=r(t);if("start"===o)var i=e.margin.left+e.title.padding;else{d3.select(this).select("text").node().getBBox().width;i="middle"===o?e.width.value/2-b/2:e.width.value-b-e.margin.right-e.title.padding}return"translate("+i+","+a+")"}),x.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),e.margin.top>0&&(e.margin.top+=e.title.padding),e.margin.bottom>0&&(e.margin.bottom+=e.title.padding);var w=e.title.height;w&&e.margin[e.title.position]l&&(f=l),e.zoom.scale=f,d=[e.width.viz/2-e.zoom.size.width*f/2-t[0][0]*f,e.height.viz/2-e.zoom.size.height*f/2-t[0][1]*f],e.zoom.translate=d,e.zoom.behavior.translate(d).scale(f),e.zoom.size={height:e.zoom.bounds[1][1]-e.zoom.bounds[0][1],width:e.zoom.bounds[1][0]-e.zoom.bounds[0][0]},e.zoom.reset=!1,(e.labels.value||e.labels.changed)&&n(e),a(e,r)}},{"./labels.coffee":251,"./transform.coffee":254}],250:[function(e,t,r){t.exports=function(e,t){var r,n,a;return n=t.id.nesting.length-1,r=t.depth.value,a=t.id.nesting[r+1],t.types[t.type.value].nesting===!1?0:(e.d3plus.merged||a in e&&r0||e&&a&&!(a in e))||!t.small&&t.tooltip.html.value?0:-1}},{}],251:[function(e,t,r){var n;n=e("../../../core/console/print.coffee"),t.exports=function(e){var t,r;if(e.dev.value&&n.time("determining label visibility"),r=e.zoom.behavior.scaleExtent(),t=function(t){return t.attr("opacity",function(t){var n;return t||(t={}),n=parseFloat(d3.select(this).attr("font-size"),10),t.visible=n*(e.zoom.scale/r[1])>=2,t.visible?1:0})},e.draw.timing?e.g.viz.selectAll("text.d3plus_label").transition().duration(e.draw.timing).call(t):e.g.viz.selectAll("text.d3plus_label").call(t),e.dev.value)return n.timeEnd("determining label visibility")}},{"../../../core/console/print.coffee":52}],252:[function(e,t,r){var n,a,o;n=e("./labels.coffee"),a=e("../../../tooltip/remove.coffee"),o=e("./transform.coffee"),t.exports=function(e){var t,r,i,s,l,u,c,f,d,p,h;return r=d3.event.sourceEvent?d3.event.sourceEvent.type:null,l=d3.event.translate,s=d3.event.scale,i=e.zoom.bounds,f=(e.width.viz-e.zoom.size.width*s)/2,c=f>0?f:0,u=f>0?e.width.viz-f:e.width.viz,h=(e.height.viz-e.zoom.size.height*s)/2,p=h>0?h:0,d=h>0?e.height.viz-h:e.height.viz,l[0]+i[0][0]*s>c?l[0]=-i[0][0]*s+c:l[0]+i[1][0]*sp?l[1]=-i[0][1]*s+p:l[1]+i[1][1]*sn.behavior.scaleExtent()[0],r=e.types[e.type.value].zoom&&n.value&&n.scroll.value,a=t.touches&&t.touches.length>1&&r,a||o||t.stopPropagation()}},{}],254:[function(e,t,r){t.exports=function(e,t){var r;return"number"!=typeof t&&(t=e.timing.transitions),r="translate("+e.zoom.translate+")",r+="scale("+e.zoom.scale+")",t?e.g.viz.transition().duration(t).attr("transform",r):e.g.viz.attr("transform",r)}},{}],255:[function(e,t,r){var n;n=e("../../core/methods/filter.coffee"),t.exports={accepted:[!1,Function,Object,String],deprecates:"active_var",mute:n(!0),solo:n(!0),spotlight:{accepted:[Boolean],deprecates:"spotlight",value:!1},value:!1}},{"../../core/methods/filter.coffee":81}],256:[function(e,t,r){t.exports={accepted:[Object],deprecated:"nesting_aggs",objectAccess:!1,value:{}}},{}],257:[function(e,t,r){var n;n=e("../../core/methods/process/data.coffee"),t.exports={accepted:[!1,Array,Object,String],delimiter:{accepted:String,value:"|"},filetype:{accepted:[!1,"json","xml","html","csv","dsv","tsv","txt"],value:!1},keys:{},process:n,value:!1}},{"../../core/methods/process/data.coffee":87}],258:[function(e,t,r){var n,a;n=e("../../core/methods/process/margin.coffee"),a=e("../../core/methods/rendering.coffee"),t.exports={background:{color:"#fafafa",rendering:a(),stroke:{color:"#ccc",width:1}},margin:{accepted:[Number,Object,String],process:function(e){var t;return void 0===e&&(e=this.value),t=e,n(e,this),t},value:10},mirror:{accepted:[Boolean],deprecates:["mirror_axis","mirror_axes"],value:!1},ticks:{accepted:[Boolean],value:!0}}},{"../../core/methods/process/margin.coffee":90,"../../core/methods/rendering.coffee":92}],259:[function(e,t,r){t.exports={accepted:[String],value:"#ffffff"}},{}],260:[function(e,t,r){t.exports={accepted:[Function,String],value:!1}},{}],261:[function(e,t,r){var n,a;n=e("../../core/methods/filter.coffee"),a=e("../../color/scale.coffee"),t.exports={accepted:[!1,Array,Function,Object,String],deprecates:"color_var",domain:{accepted:[!1,Array],value:!1},focus:"#444444",heatmap:["#282F6B","#419391","#AFD5E8","#EACE3F","#B35C1E","#B22200"],missing:"#eeeeee",mute:n(!0),primary:"#d74b03",range:["#B22200","#FFEE8D","#759143"],scale:{accepted:[Array,Function,"d3plus","category10","category20","category20b","category20c"],process:function(e){return e instanceof Array?d3.scale.ordinal().range(e):"d3plus"===e?a:"string"==typeof e?d3.scale[e]():e},value:"d3plus"},solo:n(!0),secondary:"#e5b3bb",value:!1}},{"../../color/scale.coffee":48,"../../core/methods/filter.coffee":81}],262:[function(e,t,r){t.exports={accepted:[Array,Function,String],index:{accepted:[Boolean],value:!0},process:function(e,t){return"string"==typeof e&&(e=[e]),e},value:!1}},{}],263:[function(e,t,r){arguments[4][108][0].apply(r,arguments)},{dup:108}],264:[function(e,t,r){var n;n=e("../../util/d3selection.coffee"),t.exports={accepted:[!1,Array,Object,String],id:"default",process:function(e,t){return e!==!1&&("default"===t.container.id&&t.self.container({id:"d3plus_"+ +new Date}),n(e)?e.append("div"):e instanceof Array?d3.select(e[0][0]).append("div"):(this.selector=e,d3.select(e).append("div")))},value:!1}},{"../../util/d3selection.coffee":208}],265:[function(e,t,r){var n,a;n=e("../../core/methods/filter.coffee"),a=e("../../core/methods/process/data.coffee"),t.exports={accepted:[!1,Array,Function,Object,String],center:[0,0],filetype:{accepted:["json"],value:"json"},fit:{accepted:["auto","height","width"],value:"auto"},key:!1,mute:n(!1),padding:20,process:a,projection:{accepted:["albers","albersUsa","azimuthalEqualArea","azimuthalEquidistant","conicConformal","conicEqualArea","conicEquidistant","equirectangular","gnomonic","mercator","orthographic","stereographic","transverseMercator",Function],value:"mercator"},simplify:{accepted:[Boolean],value:!0},solo:n(!1),threshold:{accepted:[Number],value:.9},value:!1}},{"../../core/methods/filter.coffee":81,"../../core/methods/process/data.coffee":87}],266:[function(e,t,r){var n,a,o;n=e("../../core/fetch/value.coffee"),a=e("../../client/ie.js"),o=e("../../string/strip.js"),t.exports={accepted:[void 0,!0,Array,String],chainable:!1,data:[],process:function(e,t){var r,i,s,l,u,c,f,d,p,h,v,g,m,y,x,b,w,_,k,z,A,j,M,O,E,F,S,T,B,C,q,N,P,I,D,V;if(void 0===t.returned)return[];if(e=e||t.cols.value,e instanceof Array?l=e:"string"==typeof e&&(l=[e]),c=[],D=[],t.title.value?(I=t.title.value,"function"==typeof I&&(I=I(t.self)),I=o(I),O=250,I=I.substr(0,O)):I="D3plus Visualization Data",e===!0)for(l=d3.keys(t.data.keys),c.push(l),C=t.data.value,v=0,y=C.length;v=0&&(e=this.accepted[t]),e},value:"middle"},color:{accepted:[!1,String],value:!1},font:{decoration:n(),family:a(),size:11,transform:o(),weight:200},padding:7,resize:{accepted:[Boolean],value:!0},text:{accepted:[!1,Function,String],value:!1},segments:2,valign:{accepted:[!1,"top","middle","bottom"],value:"middle"},value:!0}},{"../../core/methods/font/decoration.coffee":83,"../../core/methods/font/family.coffee":84,"../../core/methods/font/transform.coffee":86}],284:[function(e,t,r){var n;n=e("../../core/methods/font/family.coffee"),t.exports={accepted:[Boolean],align:"middle",data:{accepted:[Boolean],value:!0},filters:{accepted:[Boolean],value:!1},font:{align:"middle",color:"#444444",family:n(),size:[8,14],weight:200},gradient:{height:10},icons:{accepted:[Boolean],value:!0},labels:{accepted:[Boolean],value:!0},order:{accepted:["color","id","size","text",Function],sort:{accepted:["asc","desc"],value:"asc"},value:"color"},size:[8,30],tooltip:{accepted:[Boolean],value:!0},text:{accepted:[!1,Function,String],value:!1},title:{accepted:[!1,Function,String],value:!1},value:!0}},{"../../core/methods/font/family.coffee":84}],285:[function(e,t,r){var n,a,o;n=e("../../core/methods/font/decoration.coffee"),a=e("../../core/methods/font/family.coffee"),o=e("../../core/methods/font/transform.coffee"),t.exports={font:{color:"#444444",decoration:n(),family:a(),transform:o(),weight:200},hover:{color:"#444444",decoration:n(),family:a(),transform:o(),weight:200}}},{"../../core/methods/font/decoration.coffee":83,"../../core/methods/font/family.coffee":84,"../../core/methods/font/transform.coffee":86}],286:[function(e,t,r){arguments[4][123][0].apply(r,arguments)},{"../../core/methods/process/margin.coffee":90,dup:123}],287:[function(e,t,r){var n,a,o;n=e("../../core/methods/font/decoration.coffee"),a=e("../../core/methods/font/family.coffee"),o=e("../../core/methods/font/transform.coffee"),t.exports={accepted:[Boolean,String],background:{accepted:[!1,String],value:!1},branding:{accepted:[Boolean],image:{dark:"http://d3plus.org/assets/img/icon-transparent-invert.png",light:"http://d3plus.org/assets/img/icon-transparent.png"},value:!1},font:{color:"#444",decoration:n(),family:a(),size:16,transform:o(),weight:200},padding:5,style:{accepted:[!1,"small","large"],value:!1},value:!0}},{"../../core/methods/font/decoration.coffee":83,"../../core/methods/font/family.coffee":84,"../../core/methods/font/transform.coffee":86}],288:[function(e,t,r){t.exports={accepted:[Boolean],click:{accepted:[Boolean,Function],value:!0},move:{accepted:[Boolean,Function],value:!0},out:{accepted:[Boolean,Function],value:!0},over:{accepted:[Boolean,Function],value:!0},value:!0}},{}],289:[function(e,t,r){var n;n=e("../../core/methods/process/data.coffee"),t.exports={accepted:[!1,Array,Function,String],delimiter:{accepted:[String],value:"|"},filetype:{accepted:[!1,"json","xml","html","csv","dsv","tsv","txt"],value:!1},overlap:.6,process:n,value:!1}},{"../../core/methods/process/data.coffee":87}],290:[function(e,t,r){t.exports={accepted:[Boolean,Function,String],agg:{accepted:[!1,Function,"sum","min","max","mean","median"],value:!1},deprecates:["sort"],sort:{accepted:["asc","desc"],value:"desc"},value:!1}},{}],291:[function(e,t,r){t.exports={accepted:[Boolean],value:!1,timeout:400,process:function(e,t){var r,n;return!!e&&(r=null,n=function(){var e,r,n;if(r=t.container.value.node().parentNode.getBoundingClientRect(),n=r.width,e=r.height,t.self.width(n),t.self.height(e),t.width.changed||t.height.changed)return t.self.draw()},d3.select(window).on("resize."+t.container.id,function(e){return function(t){return clearTimeout(r),r=setTimeout(n,e.timeout)}}(this)),e)}}},{}],292:[function(e,t,r){var n;n=e("../../core/methods/rendering.coffee"),t.exports={accepted:function(e){var t;return t=e.types[e.type.value].shapes,!t||t instanceof Array||(t=[t]),t.length?t:["square"]},interpolate:{accepted:["basis","basis-open","cardinal","cardinal-open","linear","monotone","step","step-before","step-after"],deprecates:"stack_type",value:"linear"},rendering:n(),value:!1}},{"../../core/methods/rendering.coffee":92}],293:[function(e,t,r){var n;n=e("../../core/methods/filter.coffee"),t.exports={accepted:[!1,Function,Number,Object,String],dataFilter:!0,deprecates:["value","value_var"],mute:n(!0),scale:{accepted:[Function],deprecates:"size_scale",domain:{min:{accepted:[!1,Number],value:!1},max:{accepted:[!1,Number],value:!1}},range:{max:{accepted:[Function,Number],value:function(e){return Math.floor(d3.max([d3.min([e.width.viz,e.height.viz])/15,6]))}},min:{accepted:[Function,Number],value:3}},value:d3.scale.sqrt()},solo:n(!0),threshold:{accepted:[Boolean,Function,Number],value:!1},value:!1}},{"../../core/methods/filter.coffee":81}],294:[function(e,t,r){t.exports={value:!1}},{}],295:[function(e,t,r){var n;n=e("../../core/methods/filter.coffee"),t.exports={accepted:[!1,Function,Object,String],deprecates:["else_var","else"],mute:n(!0),solo:n(!0),value:!1}},{"../../core/methods/filter.coffee":81}],296:[function(e,t,r){var n;n=e("../../core/methods/filter.coffee"),t.exports={accepted:[Array,Boolean,Function,Object,String],deprecates:["name_array","text_var"],nesting:!0,mute:n(!0),solo:n(!0),value:!1}},{"../../core/methods/filter.coffee":81}],297:[function(e,t,r){var n;n=e("../../core/methods/filter.coffee"),t.exports={accepted:[Array,Boolean,Function,Object,String],dataFilter:!0,deprecates:["year","year_var"],fixed:{accepted:[Boolean],deprecates:["static_axis","static_axes"],value:!0},format:{accepted:[!1,Array,Function,String],value:!1},mute:n(!1),solo:n(!1),value:!1}},{"../../core/methods/filter.coffee":81}],298:[function(e,t,r){t.exports={accepted:[Boolean],align:"middle",hover:{accepted:["all-scroll","col-resize","crosshair","default","grab","grabbing","move","pointer"],value:"pointer"},handles:{accepted:[Boolean],color:"#666",opacity:1,size:3,stroke:"#666",value:!0},height:{accepted:[!1,Number],value:!1},play:{accepted:[Boolean],icon:{accepted:[!1,String],awesome:"",fallback:"►"},pause:{accepted:[!1,String],awesome:"",fallback:"❚❚"},timing:{accepted:[Number],value:1500},value:!0},value:!0}},{}],299:[function(e,t,r){t.exports={mouseevents:60,transitions:600,ui:200}},{}],300:[function(e,t,r){var n,a,o,i;n=e("../../core/methods/font/decoration.coffee"),a=e("../../core/methods/font/family.coffee"),i=e("../../core/methods/font/transform.coffee"),o=e("../../string/strip.js"),t.exports={accepted:[!1,Function,String],font:{align:"center",color:"#444444",decoration:n(),family:a(),size:16,transform:i(),weight:400},height:!1,link:!1,padding:2,position:"top",process:function(e,t){var r;return 0===t.container.id.indexOf("default")&&e&&(r=o(e).toLowerCase(),t.self.container({id:r})),e},sub:{accepted:[!1,Function,String],deprecates:"sub_title",font:{align:"center",color:"#444444",decoration:n(),family:a(),size:12,transform:i(),weight:200},link:!1,padding:1,position:"top",value:!1},total:{accepted:[Boolean,Object],deprecates:"total_bar",font:{align:"center",color:"#444444",decoration:n(),family:a(),size:12,transform:i(),weight:200,value:!1},link:!1,padding:1,position:"top",value:!1},width:!1,value:!1}},{"../../core/methods/font/decoration.coffee":83,"../../core/methods/font/family.coffee":84,"../../core/methods/font/transform.coffee":86,"../../string/strip.js":175}],301:[function(e,t,r){var n,a;n=e("../../core/methods/font/family.coffee"),a=e("../../core/methods/font/transform.coffee"),t.exports={accepted:[Boolean,Array,Function,Object,String],anchor:"top center",background:"#ffffff",children:{accepted:[Boolean,Number],value:!0},connections:{accepted:[Boolean],value:!0},curtain:{color:"#ffffff",opacity:.8},deprecates:"tooltip_info",extent:{accepted:[Boolean],value:!0},font:{color:"#444",family:n(),size:12,transform:a(),weight:200},fullscreen:{accepted:[Boolean],value:!1},html:{accepted:[!1,Function,Object,String],deprecates:"click_function",value:!1},iqr:{accepted:[Boolean],value:!0},large:250,share:{accepted:[Boolean],value:!0},size:{accepted:[Boolean],value:!0},small:225,stacked:{accepted:[Boolean],value:!1},sub:{accepted:[!1,Function,String],value:!1},value:!0}},{"../../core/methods/font/family.coffee":84,"../../core/methods/font/transform.coffee":86}],302:[function(e,t,r){var n;n=e("../../core/methods/filter.coffee"),t.exports={accepted:[!1,Function,Object,String],deprecates:["total_var"],mute:n(!0),solo:n(!0),value:!1}},{"../../core/methods/filter.coffee":81}],303:[function(e,t,r){t.exports={accepted:function(e){return d3.keys(e.types)},mode:{accepted:function(e){return e.types[e.type.value].modes||[!1]},value:!1},value:"tree_map"}},{}],304:[function(e,t,r){var n,a,o,i;o=e("../../core/methods/font/family.coffee"),n=e("../../core/methods/font/align.coffee"),a=e("../../core/methods/font/decoration.coffee"),i=e("../../core/methods/font/transform.coffee"),t.exports={accepted:[Array,Boolean],align:n("center"),border:1,color:{primary:{process:function(e,t){var r;return r=this.value,t.ui.color.secondary.value||(t.ui.color.secondary.value=d3.rgb(r).darker(.75).toString()),e},value:"#ffffff"},secondary:{value:!1}},display:{acceped:["block","inline-block"],value:"inline-block"},font:{align:"center",color:"#444",decoration:a(),family:o(),size:11,transform:i(),weight:200},margin:5,padding:5,position:{accepted:["top","right","bottom","left"],value:"bottom"},value:!1}},{"../../core/methods/font/align.coffee":82,"../../core/methods/font/decoration.coffee":83,"../../core/methods/font/family.coffee":84,"../../core/methods/font/transform.coffee":86}],305:[function(e,t,r){t.exports={accepted:[!1,Number],secondary:!1,small:200,value:!1}},{}],306:[function(e,t,r){t.exports={accepted:[Boolean],behavior:d3.behavior.zoom().scaleExtent([1,1]).duration(0),click:{accepted:[Boolean],value:!0},pan:{accepted:[Boolean],value:!0},scroll:{accepted:[Boolean],deprecates:"scroll_zoom",value:!0},value:!0}},{}],307:[function(e,t,r){var n,a,o,i,s,l,u,c;a=e("../../util/closest.coffee"),o=e("../../core/fetch/value.coffee"),i=e("./helpers/graph/draw.coffee"),s=e("./helpers/graph/nest.coffee"),l=e("../../array/sort.coffee"),u=e("./helpers/graph/stack.coffee"),c=e("../../core/data/threshold.js"),n=function(e){var t,r,n,a,s,c,f,d,p,h,v;if(i(e,{buffer:e.axes.opposite,zero:!0}),a=e.x.domain.viz.concat(e.y.domain.viz),a.indexOf(void 0)>=0)return[];for(r=l(e.data.viz,null,null,null,e),n=e[e.axes.discrete],p=e[e.axes.opposite],s=0,f=r.length;s=0)return[];if(E=e.data.viz,e.axes.stacked)for(x=0,_=E.length;x<_;x++)D=E[x],l(e,D.values);for(U=e.axes[Y]/e[e.axes.discrete].ticks.values.length,I=e[e.axes.discrete].padding.value,I<1&&(I*=U),2*I>U&&(I=.1*U),M=U-2*I,e.axes.stacked||(e[d].persist.position.value?(V=e[d].value,h=c.call(e.id.nesting,V)>=0?d3.max(E,function(e){return e.values.length}):u(E,e.id.value,o,e).length,M/=h,T=U/2-M/2-I,H=d3.scale.ordinal(),1===h?H.domain([0]).range([0]):H.domain([0,h-1]).range([-T,T])):H=d3.scale.linear()),f=[],C=e[N],B=C.scale.viz.domain().slice(),0===N.indexOf("y")&&(B=B.reverse()),B[0]<=0&&B[1]>=0?X=0:B[0]<0?X(d3.max(B)):X=d3.min(B),e[d].persist.position.value&&!e.axes.stacked&&(y=u(d3.merge(E.map(function(e){return e.values})),e.id.value,o,e,e.id.value,!1),H.domain(y),1===y.length?H.range([0]):H.range(a(H.range(),y.length))),j=d3.max(E,function(e){return e.values.length}),b=0,k=E.length;b=0?[]:(n=e.axes.discrete,b=e.axes.opposite,r="x"===n?e.axes.margin.viz.left:e.axes.margin.viz.top,x="x"===b?e.axes.margin.viz.left:e.axes.margin.viz.top,c="x"===n?"height":"width",O="x"===n?"width":"height",j=e.axes[O]/e[n].ticks.values.length,A=e.size.value,A="number"==typeof A?A:100,j=d3.min([j-2*e.labels.padding,A]),m=e.type.mode.value,m instanceof Array||(m=[m,m]),v=function(t){var r,n,o;n={};for(r in e.data.keys)o=l(t,r,a,e),n[r]=1===o.length?o[0]:o;return n},y=!1,p=[],f=e.format.value(e.format.locale.value.ui.iqr),d=e.format.value(e.format.locale.value.ui.max),g=e.format.value(e.format.locale.value.ui.min),w=e.format.value(e.format.locale.value.ui.percentile),t=e.format.value(e.format.locale.value.ui.tukey_bottom),M=e.format.value(e.format.locale.value.ui.tukey_top),_=e.format.value(e.format.locale.value.ui.quartile_first),k=e.format.value(e.format.locale.value.ui.quartile_third),h=e.format.value(e.format.locale.value.ui.median),z=[],d3.nest().key(function(t){return a(e,t,e[n].value)}).rollup(function(o){var u,A,E,F,S,T,B,C,q,N,P,I,D,V,R,U,L,Y,H,X,G,J,W,Q,K,Z,$,ee,te,re,ne,ae;for(J=e[b].scale.viz,re=o.map(function(t){return a(e,t,e[b].value)}),re.sort(function(e,t){return e-t}),ee=l(re),C=d3.quantile(re,.25),U=d3.quantile(re,.5),W=d3.quantile(re,.75),Q={},"tukey"===m[1]?(N=C-W,K=W-1.5*N,Z=M):"extent"===m[1]?(K=d3.max(re),Z=d):"number"==typeof m[1]&&(K=d3.quantile(re,(100-m[1])/100),Z=i(w,m[1])),K=d3.min([d3.max(re),K]),e.tooltip.extent.value&&(Q[Z]={key:e[b].value,value:K}),e.tooltip.iqr.value&&(Q[k]={key:e[b].value,value:W},Q[h]={key:e[b].value,value:U},Q[_]={key:e[b].value,value:C}),"tukey"===m[0]?(N=C-W,u=C+1.5*N,A=t):"extent"===m[0]?(u=d3.min(re),A=g):"number"==typeof m[0]&&(u=d3.quantile(re,m[0]/100),Z=i(w,m[0])),u=d3.max([d3.min(re),u]),e.tooltip.extent.value&&(Q[A]={key:e[b].value,value:u}),F=[],E=[],$=[],G=[],q=0,V=o.length;q=C&&te<=W?F.push(S):te>=u&&teW?$.push(S):G.push(S);for(I=a(e,o[0],e[n].value),ne=e[n].scale.viz(I),ne+=r,D=e.format.value(I,{key:e[n].value,vars:e}),I.constructor===Date&&(I=I.getTime()),I=s(I),F=v(F),F.d3plus={color:"white",id:"box_"+I,init:{},label:!1,shape:"square",stroke:"#444",text:i(f,D)},F.d3plus[O]=j,F.d3plus.init[O]=j,F.d3plus[c]=Math.abs(J(C)-J(W)),F.d3plus[n]=ne,ae=d3.min([J(C),J(W)])+F.d3plus[c]/2,ae+=x,F.d3plus[b]=ae,F.d3plus.tooltip=Q,z.push(F),Y={d3plus:{id:"median_line_"+I,position:"height"===c?"top":"right",shape:"whisker",static:!0}},X=e.format.value(U,{key:e[b].value,vars:e}),D={background:"#fff",names:[X],padding:0,resize:!1,x:0,y:0},T=Math.abs(J(U)-J(C)),B=Math.abs(J(U)-J(W)),H=2*d3.min([T,B]),L=2*e.data.stroke.width+2*e.labels.padding,D["width"===O?"w":"h"]=j-L,D["width"===c?"w":"h"]=H-L,Y.d3plus.label=D,Y.d3plus[O]=j,Y.d3plus[n]=ne,Y.d3plus[b]=J(U)+x,z.push(Y),E=v(E),E.d3plus={id:"bottom_whisker_line_"+I,offset:F.d3plus[c]/2,position:"height"===c?"bottom":"left",shape:"whisker",static:!0},"x"===b&&(E.d3plus.offset*=-1),E.d3plus[c]=Math.abs(J(u)-J(C)),E.d3plus[O]=j,E.d3plus[n]=ne,E.d3plus[b]=ae,z.push(E),$=v($),$.d3plus={id:"top_whisker_line_"+I,offset:F.d3plus[c]/2,position:"height"===c?"top":"right",shape:"whisker",static:!0},"y"===b&&($.d3plus.offset*=-1),$.d3plus[c]=Math.abs(J(K)-J(W)),$.d3plus[O]=j,$.d3plus[n]=ne,$.d3plus[b]=ae,z.push($),P=0,R=G.length;P0)for(;(F-1)*a>=d;)F--;for(r=e.width.viz/a,t=e.height.viz/F,e.size.value?(I=e.size.scale.domain.min.value,P=e.size.scale.domain.max.value,v="number"==typeof I?I:d3.min(e.data.viz,function(t){return s(e,t,e.size.value,e.id.value,"min")}),h="number"==typeof P?P:d3.max(e.data.viz,function(t){return s(e,t,e.size.value,e.id.value)}),p=[v,h]):p=[0,0],O=5,B=d3.min([r,t])/2-2*O,_=e.labels.value&&!e.small&&B>=40?d3.max([20,d3.min([.25*B,50])]):0,B-=_,C=d3.min([B,e.size.scale.range.min.value]),T=e.size.scale.value.domain(p).rangeRound([C,B]),M=d3.layout.pack().children(function(e){return e.values}).padding(O).radius(function(e){return T(e)}).size([r-2*O,t-2*O-_]).value(function(e){return e.value}),f=[],E=0,y=x=0,k=m.length;x3*e.labels.padding?e.labels.padding:0,c.d3plus.label={x:0,y:-(B+R+_/2),w:2*B,h:_-R,padding:0,resize:!0,color:u(o(e,c,c.d3plus.depth)),force:!0});return f.sort(function(e,t){return e.d3plus.depth-t.d3plus.depth})},a.fill=!0,a.requirements=["data"],a.scale=1.05,a.shapes=["circle","donut"],t.exports=a},{"../../array/sort.coffee":34,"../../color/legible.coffee":44,"../../core/data/group.coffee":57,"../../core/fetch/color.coffee":63,"../../core/fetch/text.js":66,"../../core/fetch/value.coffee":67}],311:[function(e,t,r){var n,a;a=e("../../../core/console/print.coffee"),n=function(e){var t,r;r={circle:"scatter",donut:"scatter",line:"line",square:"scatter",area:"stacked"},t=r[e.shape.value],a.warning('The "chart" visualization type has been deprecated and will be removed in version 2.0. Please use the "'+t+'" visualization type.'),e.self.type(t).draw()},n.shapes=["circle","donut","line","square","area"],t.exports=n},{"../../../core/console/print.coffee":52}],312:[function(e,t,r){var n;n=function(e){var t,r,n,a,o,i;return t=e.coords.value,n=e.coords.key||d3.keys(t.objects)[0],i=topojson.feature(t,t.objects[n]),r=i.features,o=e.coords.solo.value,a=e.coords.mute.value,r=r.filter(function(t){return t[e.id.value]=t.id,o.length?o.indexOf(t.id)>=0:!a.length||a.indexOf(t.id)<0})},n.libs=["topojson"],n.nesting=!1,n.requirements=["coords"],n.scale=1,n.shapes=["coordinates"],n.zoom=!0,t.exports=n},{}],313:[function(e,t,r){var n,a,o;n=e("../../../../core/fetch/color.coffee"),a=e("../../../../color/legible.coffee"),o=e("../../../../core/console/print.coffee"),t.exports=function(e){var t,r,i,s,l,u,c,f,d,p,h,v;for(t=e.axes,c=e.axes.margin.viz,s=t.stacked||!t.ticks.value?[]:e.data.viz,v=2*s.length>e.data.large?0:e.draw.timing,d=function(r,o){return 0===o.indexOf("y")?r.attr("x1",-2).attr("x2",-8).attr("y1",function(e){return e.d3plus.y-c.top}).attr("y2",function(e){return e.d3plus.y-c.top}):r.attr("x1",function(e){return e.d3plus.x-c.left}).attr("x2",function(e){return e.d3plus.x-c.left}).attr("y1",t.height+2).attr("y2",t.height+8),r.style("stroke",function(t){return a(n(e,t))}).style("stroke-width",e.data.stroke.width).attr("shape-rendering",e.shape.rendering.value)},e.dev.value&&o.time("creating axis tick groups"),h=e.group.select("g#d3plus_graph_plane").selectAll("g.d3plus_data_tick").data(s,function(r){var n;return n=t.discrete?"_"+r.d3plus[t.discrete]:"","tick_"+r[e.id.value]+"_"+r.d3plus.depth+n; +}),h.enter().append("g").attr("class","d3plus_data_tick").attr("opacity",0),e.dev.value&&o.timeEnd("creating axis tick groups"),f=["x","y"],l=0,u=f.length;l0?p.transition().duration(v).call(d,r):p.call(d,r),p.enter().append("line").attr("class","d3plus_data_"+r).call(d,r),e.dev.value&&v&&o.timeEnd("styling "+r+" ticks");v>0?(h.transition().duration(v).attr("opacity",1),h.exit().transition().duration(v).attr("opacity",0).remove()):(h.attr("opacity",1),h.exit().remove())}},{"../../../../color/legible.coffee":44,"../../../../core/console/print.coffee":52,"../../../../core/fetch/color.coffee":63}],314:[function(e,t,r){var n,a,o,i;n=e("./includes/axes.coffee"),a=e("./includes/svg.coffee"),o=e("./includes/mouse.coffee"),i=e("./includes/plot.coffee"),t.exports=function(e,t){void 0===t&&(t={}),n(e,t),i(e,t),a(e,t),e.mouse.viz=t.mouse===!0&&o}},{"./includes/axes.coffee":315,"./includes/mouse.coffee":317,"./includes/plot.coffee":318,"./includes/svg.coffee":319}],315:[function(e,t,r){var n,a,o,i,s,l,u,c,f,d,p,h;n=e("../../../../../array/sort.coffee"),i=e("./buffer.coffee"),o=e("../../../../../util/buckets.coffee"),l=e("../../../../../core/fetch/data.js"),u=e("../../../../../core/fetch/value.coffee"),d=e("../../../../../core/console/print.coffee"),h=e("../../../../../util/uniques.coffee"),t.exports=function(e,t){var r,n,o,l,v,g,m,y,x,b,w,_;for(o=s(e),!o&&e.axes.dataset||(e.axes.dataset=c(e)),e.axes.scale=!(!t.buffer||t.buffer===!0)&&p(e,t.buffer),r=e.width.viz>e.height.viz?["y","y2","x","x2"]:["x","x2","y","y2"],v=0,m=r.length;v0?n:0}),n=d3.sum(r,function(r){var n;return n=u(e,r,e[t].value),n<0?n:0}),[n,a]}).entries(T),q=d3.merge(c.map(function(e){return e.values})),d3.extent(q)}if(e[t].value===e.time.value)return e.time.solo.value.length?d3.extent(e.time.solo.value).map(function(e){return e.constructor!==Date?(e+="",4===e.length&&parseInt(e)+""===e&&(e+="/01/01"),new Date(e)):e}):d3.extent(e.data.time.ticks);for(q=[],M=e.axes.dataset,g=0,b=M.length;g0}),s=q.every(function(e){return e<0}),(l||s)&&(z=l?1:-1,q.push("log"===e[t].scale.value?z:0))),d3.extent(q)},f=function(e,t,r){var n,a,i,s,l;return a=0===t.indexOf("x")?e.width.viz:e.height.viz,s=e[t].scale.value,["discrete","share"].indexOf(s)>=0&&(s="linear"),l=10,"string"==typeof r[0]?(s="ordinal",n=o([0,a],r.length)):(n=[0,a],"linear"===e[t].scale.value&&(l=Math.floor(a/(4*e[t].ticks.font.size)))),e[t].scale.ticks=l,i=d3.scale[s]().domain(r).range(n),"clamp"in i&&i.clamp(!0),i},p=function(e,t){var r,n,a;return t===!0&&(t="size"),t in e&&(t=e[t].value),a=e.size.scale.range.min.value,"function"==typeof a&&(a=a(e)),n=e.size.scale.range.max.value,"function"==typeof n&&(n=n(e)),t===!1?e.size.scale.value.domain([0,1]).rangeRound([n,n]):"number"==typeof t?e.size.scale.value.domain([0,1]).rangeRound([t,t]):t?(e.dev.value&&d.time("calculating buffer scale"),r=d3.extent(e.axes.dataset,function(r){var n;return n=u(e,r,t),n?n:0}),r[0]===r[1]&&(a=n),e.dev.value&&d.timeEnd("calculating buffer scale"),e.size.scale.value.domain(r).rangeRound([a,n])):void 0}},{"../../../../../array/sort.coffee":34,"../../../../../core/console/print.coffee":52,"../../../../../core/fetch/data.js":64,"../../../../../core/fetch/value.coffee":67,"../../../../../util/buckets.coffee":204,"../../../../../util/uniques.coffee":210,"./buffer.coffee":316}],316:[function(e,t,r){var n,a;n=e("../../../../../util/buckets.coffee"),a=e("../../../../../util/closest.coffee"),t.exports=function(e,t,r){var o,i,s,l,u,c,f,d,p,h,v,g,m,y,x,b,w,_,k,z,A,j,M,O,E,F,S,T,B,C,q,N;if("share"!==e[t].scale.value&&!e[t].range.value&&e[t].reset){if(F=e[t].scale.viz.copy(),"clamp"in F&&F.clamp(!1),t===e.axes.discrete){if(h=F.domain(),"string"==typeof h[0]){for(y=h.length;y>=0;)h.splice(y,0,"d3plus_buffer_"+y),y--;return j=F.range(),j=n(d3.extent(j),h.length),e[t].scale.viz.domain(h).range(j)}if(0===t.indexOf("y")&&(h=h.slice().reverse()),1===e[t].ticks.values.length)h=[h[0],h[0]],e[t].value===e.time.value&&1!==e.data.time.ticks.length?(u=a(e.data.time.ticks,h[0]),S=e.data.time.ticks.indexOf(u),S>0?h[0]=e.data.time.ticks[S-1]:(d=e.data.time.ticks[S+1]-u,h[0]=new Date(u.getTime()-d)),S=0;)f=y?A[y-1]+o:A[y]-o,h.splice(y,0,f),y--;j=F.range(),j=n(d3.extent(j),h.length),e[t].scale.viz.domain(h).range(j)}return 0===t.indexOf("y")&&(h=h.reverse()),e[t].scale.viz.domain(h)}if("x"===r&&0===t.indexOf("x")||"y"===r&&0===t.indexOf("y")||r===!0)return h=F.domain(),l=h[0]>=0&&h[1]>=0,s=h[0]<=0&&h[1]<=0,"log"===e[t].scale.value?(N=l?1:-1,l&&0===t.indexOf("y")&&(h=h.slice().reverse()),w=Math.pow(10,parseInt(Math.abs(h[0])).toString().length-1)*N,b=h[0]%w,x=b,b&&x/w<=.1&&(x+=w*N),_=0===b?w:x,h[0]-=_,0===h[0]&&(h[0]=N),C=Math.pow(10,parseInt(Math.abs(h[1])).toString().length-1)*N,B=h[1]%C,T=Math.abs(C-B),B&&T/C<=.1&&(T+=C*N),q=0===B?C:T,h[1]+=q,0===h[1]&&(h[1]=N),l&&0===t.indexOf("y")&&(h=h.reverse())):(N=0,0===t.indexOf("y")&&(h=h.slice().reverse()),E=h.filter(function(e){return e.constructor===String}),i=.05*Math.abs(h[1]-h[0])||1,E.length||(h[0]=h[0]-i,h[1]=h[1]+i,(l&&h[0]N)&&(h[0]=N),(l&&h[1]N)&&(h[1]=N)),0===t.indexOf("y")&&(h=h.reverse())),e[t].scale.viz.domain(h);if(e.axes.scale)return c=!1,e.axes.mirror.value&&(z=0===t.indexOf("y")?"x":"y",c=e[z].scale.viz,O=e.width.viz>e.height.viz?"x":"y"),t===O&&c?h=c.domain().slice().reverse():(M=F.range()[1],k=e.axes.scale.range()[1],m=F.invert(1.5*-k),g=F.invert(M+1.5*k),h=[m,g],0===t.indexOf("y")&&(h=h.reverse()),v=F.domain(),v=v[1]-v[0],v||(h[0]-=1,h[1]+=1),0===t.indexOf("y")&&(h=h.reverse())),e[t].scale.viz.domain(h)}}},{"../../../../../util/buckets.coffee":204,"../../../../../util/closest.coffee":206}],317:[function(e,t,r){var n,a,o,i,s,l;n=e("../../../../../util/copy.coffee"),a=e("../../../../../client/pointer.coffee"),o=e("../../../../../core/fetch/color.coffee"),i=e("../../../../../core/fetch/value.coffee"),s=e("../../../../../color/legible.coffee"),l=e("../../../../../color/text.coffee"),t.exports=function(e,t){var r,n,u,c,f,d,p,h,v,g,m,y,x,b,w,_,k,z,A;return r=d3.event.type===a.click&&(t.tooltip.value.long||t.tooltip.html.value),u=[a.over,a.move].indexOf(d3.event.type)>=0,z=e.d3plus.x,A=e.d3plus.y,m=e.d3plus.r||0,b=t.types[t.type.value].scale||1,m*=b,c=t.axes,g=t.axes.margin.viz,k=t.draw.timing?t.timing.mouseevents:0,!r&&u?(n=s(o(t,e)),f=["x","y","x2","y2"].filter(function(r){var n;return n=i(t,e,t[r].value),n&&!(n instanceof Array)&&r!==t.axes.stacked&&t[r].mouse.value})):f=[],d=function(e){return e.attr("x1",function(e){return 0===e.indexOf("x")?z:z-m}).attr("y1",function(e){return 0===e.indexOf("y")?A:A+m}).attr("x2",function(e){return 0===e.indexOf("x")?z:z-m}).attr("y2",function(e){return 0===e.indexOf("y")?A:A+m}).attr("opacity",0)},p=function(e){return e.style("stroke",function(e){return"area"===t.shape.value?"white":n}).attr("stroke-dasharray",function(e){return t[e].mouse.dasharray.value}).attr("shape-rendering",function(e){return t[e].mouse.rendering.value}).style("stroke-width",function(e){return t[e].mouse.width})},h=function(r){return r.attr("x1",function(e){return 0===e.indexOf("x")?z:z-m}).attr("y1",function(e){return 0===e.indexOf("y")?A:A+m}).attr("x2",function(r){return 0===r.indexOf("x")?z:e.d3plus.x0?e.d3plus.x0:"y"===r?g.left-t[r].ticks.size:g.left+c.width+t[r].ticks.size}).attr("y2",function(r){return 0===r.indexOf("y")?A:e.d3plus.y0?e.d3plus.y0:"x"===r?c.height+g.top+t[r].ticks.size:g.top-t[r].ticks.size}).style("opacity",1)},v=t.g.labels.selectAll("line.d3plus_mouse_axis_label").data(f),k?(v.enter().append("line").attr("class","d3plus_mouse_axis_label").attr("pointer-events","none").call(d).call(p),v.transition().duration(k).call(h).call(p),v.exit().transition().duration(k).call(d).remove()):(v.call(h).call(p),v.enter().append("line").attr("class","d3plus_mouse_axis_label").attr("pointer-events","none").call(d).call(p),v.exit().remove()),w=function(r){return r.attr("font-size",function(e){return t[e].ticks.font.size+"px"}).attr("font-family",function(e){return t[e].ticks.font.family.value}).attr("font-weight",function(e){return t[e].ticks.font.weight}).attr("x",function(e){return 0===e.indexOf("x")?z:"y"===e?g.left-5-t[e].ticks.size:g.left+c.width+5+t[e].ticks.size}).attr("y",function(r){return 0===r.indexOf("y")?A:e.d3plus.y0?e.d3plus.y+(e.d3plus.y0-e.d3plus.y)/2+g.top-6:"x"===r?c.height+g.top+5+t[r].ticks.size:g.top-5-t[r].ticks.size-1.35*t[r].ticks.font.size}).attr("fill","area"===t.shape.value?"white":l(n))},_=t.g.labels.selectAll("text.d3plus_mouse_axis_label").data(f),_.enter().append("text").attr("class","d3plus_mouse_axis_label").attr("id",function(e){return e+"_d3plusmouseaxislabel"}).attr("dy",function(e){return 0===e.indexOf("y")?.35*t[e].ticks.font.size:t[e].ticks.font.size}).style("text-anchor",function(e){return"y"===e?"end":"y2"===e?"start":"middle"}).attr("opacity",0).attr("pointer-events","none").call(w),_.text(function(r){var n,a;return n=t.axes.stacked||r,a=i(t,e,t[n].value),t.format.value(a,{key:t[n].value,vars:t,labels:t[n].affixes.value})}),k?(_.transition().duration(k).delay(k).attr("opacity",1).call(w),_.exit().transition().duration(k).attr("opacity",0).remove()):(_.attr("opacity",1).call(w),_.exit().remove()),y=function(r){var a;return a=function(e){var t;return t=d3.select("text#"+e+"_d3plusmouseaxislabel"),t.size()?t.node().getBBox():{width:0,height:0}},r.attr("x",function(e){var r;return r=a(e).width,0===e.indexOf("x")?z-r/2-5:"y"===e?g.left-t[e].ticks.size-r-10:g.left+c.width+t[e].ticks.size}).attr("y",function(r){var n;return n=a(r).height,0===r.indexOf("y")?A-(n/2+5):e.d3plus.y0?e.d3plus.y+(e.d3plus.y0-e.d3plus.y)/2+g.top-(n/2+5):"x"===r?c.height+g.top+t[r].ticks.size:g.top-t[r].ticks.size-n-10}).attr("width",function(e){return a(e).width+10}).attr("height",function(e){return a(e).height+10}).style("stroke","area"===t.shape.value?"transparent":n).attr("fill",n).attr("shape-rendering",function(e){return t[e].mouse.rendering.value}).style("stroke-width",function(e){return t[e].mouse.width})},x=t.g.labels.selectAll("rect.d3plus_mouse_axis_label").data(f),k?(x.enter().insert("rect","text.d3plus_mouse_axis_label").attr("class","d3plus_mouse_axis_label").attr("pointer-events","none").attr("opacity",0).call(y),x.transition().duration(k).delay(k).attr("opacity",1).call(y),x.exit().transition().duration(k).attr("opacity",0).remove()):(x.attr("opacity",1).call(y),x.enter().insert("rect","text.d3plus_mouse_axis_label").attr("class","d3plus_mouse_axis_label").attr("pointer-events","none").call(y),x.exit().remove())}},{"../../../../../client/pointer.coffee":38,"../../../../../color/legible.coffee":44,"../../../../../color/text.coffee":50,"../../../../../core/fetch/color.coffee":63,"../../../../../core/fetch/value.coffee":67,"../../../../../util/copy.coffee":207}],318:[function(e,t,r){var n,a,o,i,s,l,u,c,f,d,p;n=e("../../../../../util/buckets.coffee"),a=e("./buffer.coffee"),i=e("../../../../../core/fetch/value.coffee"),s=e("../../../../../font/sizes.coffee"),f=e("../../../../../textwrap/textwrap.coffee"),d=e("../../../../../core/data/time.coffee"),p=e("../../../../../util/uniques.coffee"),t.exports=function(e,t){var r,n,s,l,c,f,p,h,v,g,m,y,x,b,w,_,k,z,A,j;for(e.axes.margin.viz={top:e.axes.margin.top,right:e.axes.margin.right,bottom:e.axes.margin.bottom,left:e.axes.margin.left},e.axes.height=e.height.viz,e.axes.width=e.width.viz,r=e.width.viz>e.height.viz?["y","y2","x","x2"]:["x","x2","y","y2"],c=0,h=r.length;c4?e:(e+="",4===e.length&&parseInt(e)+""===e&&(e+="/01/01"),new Date(e).getTime())}))}if(e.small)for(e.axes.width-=e.axes.margin.viz.left+e.axes.margin.viz.right,e.axes.height-=e.axes.margin.viz.top+e.axes.margin.viz.bottom,f=0,v=r.length;fk&&A.join("").indexOf(" ")>0?(e[t].ticks.wrap=!0,z=s(A,m,{mod:function(t){return f().container(d3.select(t)).height(e.axes.height/2).width(k).draw()}}),x=d3.max(z,function(e){return e.width}),y=d3.max(z,function(e){return e.height})):e[t].ticks.wrap=!1,e[t].ticks.baseline="auto",x<=k?e[t].ticks.rotate=0:xe.width.value&&(v=h-e.width.value+e.axes.margin.viz.right,e.axes.width-=v,e.axes.margin.viz.right+=v)):e[t].ticks.hidden=!0,w=e[t].label.fetch(e),w?(_={"font-family":e[t].label.font.family.value,"font-weight":e[t].label.font.weight,"font-size":e[t].label.font.size+"px","text-transform":e[t].label.font.transform.value,"letter-spacing":e[t].label.font.spacing+"px"},e[t].label.height=s([w],_)[0].height):e[t].label.height=0,e[t].label.value&&(e.axes.margin.viz[c]+=e[t].label.height,e.axes.margin.viz[c]+=2*e[t].label.padding));if(e.axes.height-=e.axes.margin.viz.top+e.axes.margin.viz.bottom,e.x.scale.viz.range(n([0,e.axes.width],b.length)),g&&e.x2.scale.viz.range(n([0,e.axes.width],g.length)),e.y.scale.viz.range(n([0,e.axes.height],F.length)),M)return e.y2.scale.viz.range(n([0,e.axes.height],M.length))},o=function(e,t){return d3.svg.axis().tickSize(e[t].ticks.size).tickPadding(5).orient(e[t].orient.value).scale(e[t].scale.viz).tickValues(e[t].ticks.values).tickFormat(function(r,n){var a,o;return e[t].ticks.hidden?null:(o=e[t].scale.value,a=r.constructor===Date?+r:r,e[t].ticks.visible.indexOf(a)>=0?"share"===o?e.format.value(100*r,{key:"share",vars:e,labels:e[t].affixes.value,output:t}):r.constructor===Date?e[t].ticks.format(r):"log"===o?l(r):e.format.value(r,{key:e[t].value,vars:e,labels:e[t].affixes.value,output:t}):null)})},c="⁰¹²³⁴⁵⁶⁷⁸⁹",l=function(e){var t,r,n;return r=Math.round(Math.log(Math.abs(e))/Math.LN10),n=Math.abs(e).toString().charAt(0),t="10 "+(r+"").split("").map(function(e){return c[e]}).join(""),"1"!==n&&(t=n+" x "+t),e<0?"-"+t:t}},{"../../../../../core/data/time.coffee":62,"../../../../../core/fetch/value.coffee":67,"../../../../../font/sizes.coffee":102,"../../../../../textwrap/textwrap.coffee":200,"../../../../../util/buckets.coffee":204,"../../../../../util/uniques.coffee":210,"./buffer.coffee":316}],319:[function(e,t,r){var n,a,o;n=e("../../../../../color/mix.coffee"),a=e("../../../../../textwrap/textwrap.coffee"),o=e("../../../../../object/validate.coffee"),t.exports=function(e){var t,r,i,s,l,u,c,f,d,p,h,v,g,m,y,x,b,w,_,k,z,A,j,M,O,E,F,S,T,B,C,q,N,P,I,D,V,R,U,L,Y,H,X,G,J,W,Q,K,Z,$,ee,te,re,ne,ae,oe,ie,se,le,ue,ce;if(h=e.x.domain.viz.concat(e.y.domain.viz),h.indexOf(void 0)>=0)return null;for(f={width:e.axes.width,height:e.axes.height,fill:e.axes.background.color,stroke:e.axes.background.stroke.color,"stroke-width":e.axes.background.stroke.width,"shape-rendering":e.axes.background.rendering.value},r={left:"start",center:"middle",right:"end"},s=e.small?[]:[0],oe=function(t,r){return t.attr("x1",function(t){return 0===r.indexOf("x")?e.x.scale.viz(t):0}).attr("x2",function(t){return 0===r.indexOf("x")?e.x.scale.viz(t):e.axes.width}).attr("y1",function(t){return 0===r.indexOf("y")?e.y.scale.viz(t):0}).attr("y2",function(t){return 0===r.indexOf("y")?e.y.scale.viz(t):e.axes.height})},ie=function(t,r,a){var o,i,s;return o=a?e[r].grid.color:e[r].ticks.color,i="log"===e[r].scale.value,s=e[r].ticks.visible||[],t.attr("stroke",function(t){var l;return 0===t?e[r].axis.color:(t.constructor===Date&&(t=+t),l=s.indexOf(t)>=0,!l||i&&"1"!==Math.abs(t).toString().charAt(0)?a&&"transparent"!==e.axes.background.color?n(o,e.axes.background.color,.4,1):"transparent"!==e.background.value?n(o,e.background.value,.4,1):n(o,"white",.4,1):o)}).attr("stroke-width",e[r].ticks.width).attr("shape-rendering",e[r].ticks.rendering.value)},v=function(t,r,n){var a;return a=0===r?"axis":"ticks",r=e[t][a].font[n],r&&(r.length||"number"==typeof r)?r:e[t].ticks.font[n]},ae=function(t,r){var a;return a="log"===e[r].scale.value,t.attr("font-size",function(e){return v(r,e,"size")+"px"}).attr("stroke","none").attr("fill",function(t){var o;return o=v(r,t,"color"),a&&"1"!==Math.abs(t).toString().charAt(0)?n(o,e.background.value,.4,1):o}).attr("font-family",function(e){return v(r,e,"family").value}).attr("font-weight",function(e){return v(r,e,"weight")}).style("text-transform",function(e){return v(r,e,"transform").value}).style("letter-spacing",function(e){return v(r,e,"spacing")+"px"})},q=function(t,r){var n,a;return n=0===r.indexOf("x")?"height":"width",a=0===r.indexOf("x")?"y":"x",t.attr(a+"1",0).attr(a+"2",e.axes[n]).attr(r+"1",function(e){return e.coords.line}).attr(r+"2",function(e){return e.coords.line}).attr("stroke",function(t){return t.color||e[r].lines.color}).attr("stroke-width",e[r].lines.width).attr("shape-rendering",e[r].lines.rendering.value).attr("stroke-dasharray",e[r].lines.dasharray.value)},T=function(t,n){var a;return a=0===n.indexOf("x")?"y":"x",t.attr(a,function(e){return e.coords.text[a]+"px"}).attr(n,function(e){return e.coords.text[n]+"px"}).attr("dy",e[n].lines.font.position.value).attr("text-anchor",r[e[n].lines.font.align.value]).attr("transform",function(e){return e.transform}).attr("font-size",e[n].lines.font.size+"px").attr("fill",function(t){return t.color||e[n].lines.color}).attr("font-family",e[n].lines.font.family.value).attr("font-weight",e[n].lines.font.weight)},L="translate("+e.axes.margin.viz.left+","+e.axes.margin.viz.top+")",U=e.group.selectAll("g#d3plus_graph_plane").data([0]),U.transition().duration(e.draw.timing).attr("transform",L),U.enter().append("g").attr("id","d3plus_graph_plane").attr("transform",L),c=U.selectAll("rect#d3plus_graph_background").data([0]),c.transition().duration(e.draw.timing).attr(f),c.enter().append("rect").attr("id","d3plus_graph_background").attr("x",0).attr("y",0).attr(f),D=U.selectAll("path#d3plus_graph_mirror").data([0]),D.enter().append("path").attr("id","d3plus_graph_mirror").attr("fill","#000").attr("fill-opacity",.03).attr("stroke-width",1).attr("stroke","#ccc").attr("stroke-dasharray","10,10").attr("opacity",0),D.transition().duration(e.draw.timing).attr("opacity",function(){return e.axes.mirror.value?1:0}).attr("d",function(){var e,t;return t=f.width,e=f.height,"M "+t+" "+e+" L 0 "+e+" L "+t+" 0 Z"}),Z=0!==e.x.ticks.rotate,ue=function(t,r){var n,o;return o="x"===r?e.axes.height:0,n=t.attr("transform","translate(0,"+o+")").call(e[r].axis.svg.scale(e[r].scale.viz)).selectAll("g.tick"),n.selectAll("line").attr("y2",function(t){var n;return t.constructor===Date&&(t=+t),n=d3.select(this).attr("y2"),e[r].ticks.visible.indexOf(t)>=0?n:n/2}),n.select("text").style("text-anchor",Z&&"x"===r?"end":Z?"start":"middle").call(ae,r).each(function(t){if(d3.select(this).attr("dy","0px").attr("font-size",function(e){return v(r,e,"size")+"px"}),t.constructor===Date&&(t=+t),!e[r].ticks.hidden&&e[r].ticks.visible.indexOf(t)>=0)return a().container(d3.select(this)).rotate(e[r].ticks.rotate).align(Z?"end":"center").valign(Z?"middle":"x"===r?"top":"bottom").width(e[r].ticks.maxWidth+2).height(e[r].ticks.maxHeight).padding(0).x(-e[r].ticks.maxWidth/2).y("x2"===r?-(e[r].ticks.maxHeight+2*e.labels.padding):0).draw()})},ce=function(t,r){var n,a;return a="y2"===r?e.axes.width:0,n=t.attr("transform","translate("+a+", 0)").call(e[r].axis.svg.scale(e[r].scale.viz)).selectAll("g.tick"),n.selectAll("line").attr("y2",function(t){var r;return t.constructor===Date&&(t=+t),r=d3.select(this).attr("y2"),e.x.ticks.visible.indexOf(t)>=0?r:r/2}),n.select("text").call(ae,r)},J=["x","x2","y","y2"],x=0,A=J.length;x=0&&e[R].axis.value&&(m=[0])),e[i].value===e.time.value&&(m=m.map(function(e){return e+="",4===e.length&&parseInt(e)+""===e&&(e+="/01/01"),new Date(e).getTime()})),g=U.selectAll("g#d3plus_graph_"+i+"grid").data([0]),g.enter().append("g").attr("id","d3plus_graph_"+i+"grid"),N=g.selectAll("line").data(m,function(e,t){return e.constructor===Date?e.getTime():e}),N.transition().duration(e.draw.timing).call(oe,i).call(ie,i,!0),N.enter().append("line").style("opacity",0).call(oe,i).call(ie,i,!0).transition().duration(e.draw.timing).delay(e.draw.timing/2).style("opacity",1),N.exit().transition().duration(e.draw.timing/2).style("opacity",0).remove();for(Q=["x","x2","y","y2"],w=0,M=Q.length;w=0:d>=p[0]&&d<=p[1],le&&(d=o(F)?F:{position:d},d.coords={line:e[i].scale.viz(d.position)},S.push(d),d.text&&(d.axis=i,d.padding=.5*e[i].lines.font.padding.value,d.align=e[i].lines.font.align.value,Y=e[i].lines.font.position.text,re="middle"===Y?0:2*d.padding,"top"===Y&&(re=-re),0===i.indexOf("x")?(ne="left"===d.align?e.axes.height:"center"===d.align?e.axes.height/2:0,"left"===d.align&&(ne-=2*d.padding),"right"===d.align&&(ne+=2*d.padding)):(ne="left"===d.align?0:"center"===d.align?e.axes.width/2:e.axes.width,"right"===d.align&&(ne-=2*d.padding),"left"===d.align&&(ne+=2*d.padding)), +d.coords.text={},d.coords.text[0===i.indexOf("x")?"y":"x"]=ne,d.coords.text[i]=e[i].scale.viz(d.position)+re,d.transform=0===i.indexOf("x")?"rotate(-90,"+d.coords.text.x+","+d.coords.text.y+")":null,te.push(d)));N=B.selectAll("line.d3plus_graph_"+i+"line").data(S,function(e){return e.position}),N.enter().append("line").attr("class","d3plus_graph_"+i+"line").attr("opacity",0).call(q,i),N.transition().duration(e.draw.timing).attr("opacity",1).call(q,i),N.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),P=B.selectAll("text.d3plus_graph_"+i+"line_text").data(te,function(e){return e.position}),P.enter().append("text").attr("class","d3plus_graph_"+i+"line_text").attr("id",function(e){var t;return t=e.position+"",t=t.replace("-","neg"),t=t.replace(".","p"),"d3plus_graph_"+i+"line_text_"+t}).attr("opacity",0).call(T,i),P.text(function(e){return e.text}).transition().duration(e.draw.timing).attr("opacity",1).call(T,i),P.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),G=function(t){var r;return r=function(e){var t;return t=e.position+"",t=t.replace("-","neg"),t=t.replace(".","p"),U.select("text#d3plus_graph_"+e.axis+"line_text_"+t).node().getBBox()},t.attr("x",function(e){return r(e).x-e.padding}).attr("y",function(e){return r(e).y-e.padding}).attr("transform",function(e){return e.transform}).attr("width",function(e){return r(e).width+2*e.padding}).attr("height",function(e){return r(e).height+2*e.padding}).attr("fill","transparent"!==e.axes.background.color?e.axes.background.color:"white")},X=e[i].lines.font.background.value?te:[],C=B.selectAll("rect.d3plus_graph_"+i+"line_rect").data(X,function(e){return e.position}),C.enter().insert("rect","text.d3plus_graph_"+i+"line_text").attr("class","d3plus_graph_"+i+"line_rect").attr("pointer-events","none").attr("opacity",0).call(G),C.transition().delay(e.draw.timing).each("end",function(t){return d3.select(this).transition().duration(e.draw.timing).attr("opacity",1).call(G)}),C.exit().transition().duration(e.draw.timing).attr("opacity",0).remove()}}},{"../../../../../color/mix.coffee":46,"../../../../../object/validate.coffee":172,"../../../../../textwrap/textwrap.coffee":200}],320:[function(e,t,r){var n,a,o;n=e("../../../../core/fetch/value.coffee"),a=e("../../../../string/strip.js"),o=e("../../../../util/uniques.coffee"),t.exports=function(e,t,r){var i,s,l,u,c,f,d;return void 0===r?r=e.id.nesting.slice(0,e.depth.value+1):r.constructor!==Array&&(r=[r]),void 0===s&&(s=[]),t||(t=e.data.viz),i=e[e.axes.discrete],u=e[e.axes.opposite],d=i.value===e.time.value,d?(f=e.data.time.ticks,l=e.time.solo.value.length?"solo":"mute",e.time[l].value.length&&(c=e.time[l].value.slice().map(function(e){return e.constructor!==Date&&(e+="",4===e.length&&parseInt(e)+""===e&&(e+="/01/01"),e=new Date(e)),+e}),f=f.filter(function(e){return"solo"===l?c.indexOf(+e)>=0:c.indexOf(+e)<0}))):f=i.ticks.values?i.ticks.values:o(t,i.value,n,e),d3.nest().key(function(t){var o,i,s,l,u;for(l="nesting",i=0,s=r.length;i=0){c=!1;break}c?f.push(r):h.push(r)}else x>=0&&h.push(r),x<0&&f.push(r);return 0===h.length||0===f.length?g(t):(h.length&&(h=g(h)),f.length&&(f=g(f)),h.concat(f))}},{"../../../../core/fetch/value.coffee":67}],322:[function(e,t,r){var n,a,o,i,s,l;n=e("../../core/fetch/value.coffee"),a=e("./helpers/graph/draw.coffee"),i=e("./helpers/graph/nest.coffee"),s=e("../../array/sort.coffee"),l=e("./helpers/graph/stack.coffee"),o=function(e){var t,r,o,i,u,c,f,d,p,h,v;if(a(e,{buffer:e.axes.opposite,mouse:!0}),o=e.x.domain.viz.concat(e.y.domain.viz),o.indexOf(void 0)>=0)return[];for(r=s(e.data.viz,null,null,null,e),i=0,c=r.length;ih)var g=e.height.viz/p;else var g=e.width.viz/d;var u=.25*l;u*g<2&&(u=2/g)}}var m=e.size.scale.value.domain(s).range([u,l]);e.zoom.bounds=[[o[0]-1.1*l,i[0]-1.1*l],[o[1]+1.1*l,i[1]+1.1*l]];var y=[],x={};return t.forEach(function(t){var r=e.data.viz.filter(function(r){return r[e.id.value]==t[e.id.value]})[0],n=r||{};n[e.id.value]=t[e.id.value],n.d3plus={},n.d3plus.x=t.x,n.d3plus.y=t.y;var o=a(e,n,e.size.value);n.d3plus.r=o?m(o):m.range()[0],x[n[e.id.value]]={x:n.d3plus.x,y:n.d3plus.y,r:n.d3plus.r},y.push(n)}),y.sort(function(e,t){return t.d3plus.r-e.d3plus.r}),r.forEach(function(t,r){t.d3plus&&delete t.d3plus.spline,t[e.edges.source].d3plus={};var n=x[t[e.edges.source][e.id.value]];void 0!==n?(t[e.edges.source].d3plus.r=n.r,t[e.edges.source].d3plus.x=n.x,t[e.edges.source].d3plus.y=n.y):delete t[e.edges.source].d3plus,t[e.edges.target].d3plus={};var a=x[t[e.edges.target][e.id.value]];void 0!==a?(t[e.edges.target].d3plus.r=a.r,t[e.edges.target].d3plus.x=a.x,t[e.edges.target].d3plus.y=a.y):delete t[e.edges.target].d3plus}),{nodes:y,edges:r}};o.nesting=!1,o.requirements=["nodes","edges"],o.scale=1.05,o.shapes=["circle","square","donut"],o.tooltip="static",o.zoom=!0,t.exports=o},{"../../core/fetch/value.coffee":67,"../../network/smallestGap.coffee":168}],324:[function(e,t,r){var n,a,o,i,s=[].indexOf||function(e){for(var t=0,r=this.length;t=0&&(J=u),s.call(l,N)>=0&&(D=u);null!==J&&null===D?J+1===X.all.length-1?X.all.splice(J+1,0,[g]):X.all[J+1].push(g):D-J===1?X.all.splice(D,0,[g]):D-J>1&&X.all[D-1].push(g)}oe+=q}for(ae=Math.floor(e.height.viz/oe),de=[],v=0;v=0&&(V.d3plus.x=ue(u));V.d3plus.y=fe(H[V[e.id.value]]),e.size.value?(le=n(e,V,e.size.value),V.d3plus.r=le?ie(le):B):V.d3plus.r=T,V.d3plus.r<.1*c&&!e.small?V.d3plus.label={x:0,y:V.d3plus.r+2*e.labels.padding,w:.6*c,h:b+T-V.d3plus.r,resize:!1}:delete V.d3plus.label}for(re=i.paths,Y=U=0,E=re.length;U1?n(t.d3plus,r.d3plus,e.id.nesting.concat([e.size.value]),void 0,[],e):n(t.d3plus,r.d3plus,[e.size.value],"desc",[],e)}),r=o(e,e.data.viz,[]),l=u(r),f=[],c=d3.min([e.width.viz,e.height.viz])/2-2*e.labels.padding,a=0,s=l.length;a=20){z=w;break}for(K=n([R/z,R],z-1).reverse(),K.length===z&&K.shift(),$=e.group.selectAll(".d3plus_radar_rings").data(K,function(e,t){return t}),Z=function(t){return t.attr("fill",function(t,r){return 0===r?e.axes.background.color:"transparent"}).attr("cx",e.width.viz/2+e.margin.top).attr("cy",e.height.viz/2+e.margin.left).attr("stroke",e.x.grid.value?e.x.grid.color:"transparent")},$.enter().append("circle").attr("class","d3plus_radar_rings").call(Z).attr("r",0),$.transition().duration(e.draw.timing).call(Z).attr("r",function(e){return e}),$.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),S=d3.scale.ordinal().domain(C).range(d3.range(0,C.length)),O=[],U=0,I=C.length;U90?(t-=180,c=-(R+2*e.labels.padding+B),a="end"):(c=R+2*e.labels.padding,a="start"),ae=r<0||r>Math.PI,Q=r=0,h&&(ie-=B/2),O.push({text:M,angle:t,x:c,anchor:a,offset:H});return E=e.group.selectAll("g.d3plus_radar_label_group").data([0]),E.enter().append("g").attr("class","d3plus_radar_label_group").attr("transform","translate("+e.width.viz/2+","+e.height.viz/2+")"),E.transition().duration(e.draw.timing).attr("transform","translate("+e.width.viz/2+","+e.height.viz/2+")"),re=E.selectAll(".d3plus_radar_labels").data(e.labels.value?O:[],function(e,t){return t}),T=function(e){return e.attr(ne).each(function(e,t){return d().container(d3.select(this)).height(F).width(B).align(e.anchor).text(e.text).padding(0).valign("middle").x(e.x).y(-F/2).draw()}).attr("transform",function(e){var t;return t=d3.select(this).attr("transform")||"",t.length&&(t=t.split(")").slice(-3).join(")")),"rotate("+e.angle+")"+t})},re.call(T),re.enter().append("text").attr("class","d3plus_radar_labels").attr("opacity",0).call(T).transition().duration(e.draw.timing).attr("opacity",1),re.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),x=e.group.selectAll(".d3plus_radar_lines").data(O,function(e,t){return t}),b=function(t){return t.attr("stroke",e.x.grid.color).attr("x1",e.width.viz/2+e.margin.left).attr("y1",e.height.viz/2+e.margin.top)},x.enter().append("line").attr("class","d3plus_radar_lines").call(b).attr("x2",e.width.viz/2+e.margin.left).attr("y2",e.height.viz/2+e.margin.top),x.transition().duration(e.draw.timing).call(b).attr("x2",function(t){return e.width.viz/2+e.margin.left+t.offset.x}).attr("y2",function(t){return e.height.viz/2+e.margin.top+t.offset.y}),x.exit().transition().duration(e.draw.timing).attr("opacity",0).remove(),e.mouse.viz={click:!1},m},c.requirements=["data","size"],c.shapes=["radial"],t.exports=c},{"../../array/comparator.coffee":32,"../../array/sort.coffee":34,"../../core/data/threshold.js":61,"../../core/fetch/text.js":66,"../../core/fetch/value.coffee":67,"../../font/sizes.coffee":102,"../../geom/offset.coffee":161,"../../textwrap/textwrap.coffee":200,"../../util/buckets.coffee":204,"../../util/uniques.coffee":210}],327:[function(e,t,r){var n=e("../../array/sort.coffee"),o=e("../../client/pointer.coffee"),i=e("../../core/fetch/value.coffee"),s=e("../../core/fetch/color.coffee"),l=e("../../color/legible.coffee"),u=e("../../tooltip/remove.coffee"),c=e("../../network/smallestGap.coffee"),f=e("../../color/text.coffee"),d=e("../../util/uniques.coffee"),p=function(e){var t=d3.min([e.height.viz,e.width.viz])/2,r=e.small||!e.labels.value?(t-2*e.labels.padding)/2:t/3,p=e.small||!e.labels.value?1.4*r:r,h=2*r,v=[],g=[],m=e.data.viz.filter(function(t){return t[e.id.value]===e.focus.value[0]})[0];m||(m={d3plus:{}},m[e.id.value]=e.focus.value[0]),m.d3plus.x=e.width.viz/2,m.d3plus.y=e.height.viz/2,m.d3plus.r=.65*p;var y=[],x=[e.focus.value[0]];e.edges.connections(e.focus.value[0],e.id.value).forEach(function(t){var r=t[e.edges.source][e.id.value]==e.focus.value[0]?t[e.edges.target]:t[e.edges.source],n=e.data.viz.filter(function(t){return t[e.id.value]===r[e.id.value]})[0];n||(n={d3plus:{}},n[e.id.value]=r[e.id.value]),n.d3plus.edges=e.edges.connections(n[e.id.value],e.id.value).filter(function(t){return t[e.edges.source][e.id.value]!=e.focus.value[0]&&t[e.edges.target][e.id.value]!=e.focus.value[0]}),n.d3plus.edge=t,x.push(n[e.id.value]),y.push(n)});var b=e.order.value||e.color.value||e.size.value||e.id.value;y.sort(function(t,r){var a=t.d3plus.edges.length-r.d3plus.edges.length;return a?a:n([t,r],b,e.order.sort.value,e.color.value||[],e)}),"number"==typeof e.edges.limit.value?y=y.slice(0,e.edges.limit.value):"function"==typeof e.edges.limit.value&&(y=e.edges.limit.value(y));var w=[],_=0;y.forEach(function(t){var r=t[e.id.value];t.d3plus.edges=t.d3plus.edges.filter(function(t){var n=t[e.edges.source][e.id.value],a=t[e.edges.target][e.id.value];return x.indexOf(n)<0&&a==r||x.indexOf(a)<0&&n==r}),_+=t.d3plus.edges.length||1,t.d3plus.edges.forEach(function(t){var n=t[e.edges.source],a=t[e.edges.target],o=a[e.id.value]==r?n:a;x.push(o[e.id.value])})}),n(y,b,e.order.sort.value,e.color.value||[],e);var k=0,z=2*Math.PI,A=0;y.forEach(function(t,r){var o=t.d3plus.edges.length||1,i=z/_*o;0==r&&(A=s,k-=i/2);var s=k+i/2;s-=z/4,t.d3plus.radians=s,t.d3plus.x=e.width.viz/2+p*Math.cos(s),t.d3plus.y=e.height.viz/2+p*Math.sin(s),k+=i,t.d3plus.edges.sort(function(r,a){var r=r[e.edges.source][e.id.value]==t[e.id.value]?r[e.edges.target]:r[e.edges.source],a=a[e.edges.source][e.id.value]==t[e.id.value]?a[e.edges.target]:a[e.edges.source];return n([r,a],b,e.order.sort.value,e.color.value||[],e)}),t.d3plus.edges.forEach(function(r,n){var i=r[e.edges.source][e.id.value]==t[e.id.value]?r[e.edges.target]:r[e.edges.source],l=z/_,u=e.data.viz.filter(function(t){return t[e.id.value]===i[e.id.value]})[0];u||(u={d3plus:{}},u[e.id.value]=i[e.id.value]),a=s-l*o/2+l/2+l*n,u.d3plus.radians=a,u.d3plus.x=e.width.viz/2+h*Math.cos(a),u.d3plus.y=e.height.viz/2+h*Math.sin(a),w.push(u)})});var j=c(y,{accessor:function(e){return[e.d3plus.x,e.d3plus.y]}}),M=c(w,{accessor:function(e){return[e.d3plus.x,e.d3plus.y]}});if(j||(j=r/2),M||(M=r/4),j/2-4<8)var O=d3.min([j/2,8]);else var O=j/2-4;if(M/2-4<4)var E=d3.min([M/2,4]);else var E=M/2-4;E>r/10&&(E=r/10),E>O&&E>10&&(E=.75*O),O>1.5*E&&(O=1.5*E),O=Math.floor(O),E=Math.floor(E);var F=d(y,e.id.value,i,e);F=F.concat(d(w,e.id.value,i,e)),F.push(e.focus.value[0]);var S=e.data.viz.filter(function(t){return F.indexOf(t[e.id.value])>=0});if(e.size.value){var T=d3.extent(S,function(t){return i(e,t,e.size.value)});T[0]==T[1]&&(T[0]=0);var t=d3.scale.linear().domain(T).rangeRound([3,d3.min([O,E])]),B=i(e,m,e.size.value);m.d3plus.r=t(B)}else{var t=d3.scale.linear().domain([1,2]).rangeRound([O,E]);e.edges.label&&(m.d3plus.r=1.5*t(1))}w.forEach(function(r){r.d3plus.ring=2;var n=e.size.value?i(e,r,e.size.value):2;r.d3plus.r=t(n)}),y.forEach(function(r){r.d3plus.ring=1;var n=e.size.value?i(e,r,e.size.value):1;r.d3plus.r=t(n)}),g=[m].concat(y).concat(w),y.forEach(function(t,n){var a=[e.edges.source,e.edges.target],o=t.d3plus.edge;a.forEach(function(t){o[t]=g.filter(function(r){return r[e.id.value]==o[t][e.id.value]})[0]}),delete o.d3plus,v.push(o),e.edges.connections(t[e.id.value],e.id.value).forEach(function(n){var a=n[e.edges.source][e.id.value]==t[e.id.value]?n[e.edges.target]:n[e.edges.source];if(a[e.id.value]!=m[e.id.value]){var o=w.filter(function(t){return t[e.id.value]==a[e.id.value]})[0];if(o);else{o=y.filter(function(t){return t[e.id.value]==a[e.id.value]})[0]}if(o){n.d3plus={spline:!0,translate:{x:e.width.viz/2,y:e.height.viz/2}};var i=[e.edges.source,e.edges.target];i.forEach(function(a,i){n[a]=g.filter(function(t){return t[e.id.value]==n[a][e.id.value]})[0],void 0===n[a].d3plus.edges&&(n[a].d3plus.edges={});var s=0===i?n[e.edges.target][e.id.value]:n[e.edges.source][e.id.value];n[a][e.id.value]==t[e.id.value]?n[a].d3plus.edges[s]={angle:t.d3plus.radians+Math.PI,radius:r/2}:n[a].d3plus.edges[s]={angle:o.d3plus.radians,radius:r/2}}),v.push(n)}}})});var C=!1;return e.background.value&&["transparent","none"].indexOf(e.background.value)<0&&d3.hsl(e.background.value).l<.5&&(C=f(e.background.value)),g.forEach(function(t){if(!e.small&&e.labels.value)if(t[e.id.value]!=e.focus.value[0]){t.d3plus.rotate=t.d3plus.radians*(180/Math.PI);var n=t.d3plus.rotate,a=r-3*e.labels.padding-t.d3plus.r;if(n<-90||n>90){n-=180;var o=-(t.d3plus.r+a/2+e.labels.padding),i="end"}else var o=t.d3plus.r+a/2+e.labels.padding,i="start";var u=y.indexOf(t)>=0,c=1==t.d3plus.ring?j:M;t.d3plus.label={x:o,y:0,w:a,h:c,angle:n,anchor:i,valign:"center",color:C||l(s(e,t)),resize:[8,e.labels.font.size],background:u,mouse:!0}}else if(e.size.value||e.edges.label){var c=p-2*t.d3plus.r-2*e.labels.padding;t.d3plus.label={x:0,y:t.d3plus.r+c/2,w:p,h:c,color:C||l(s(e,t)),resize:[10,40],background:!0,mouse:!0}}else delete t.d3plus.rotate,delete t.d3plus.label;else delete t.d3plus.rotate,delete t.d3plus.label}),e.mouse.viz={},e.mouse.viz[o.click]=function(t){if(t[e.id.value]!=e.focus.value[0]){u(e.type.value);var r=e.focus.value[0];e.history.states.push(function(){e.self.focus(r).draw()}),e.self.focus(t[e.id.value]).draw()}},{edges:v,nodes:g,data:S}};p.filter=function(e,t){var r=e.edges.connections(e.focus.value[0],e.id.value,!0),n=[];r.forEach(function(t){n=n.concat(e.edges.connections(t[e.id.value],e.id.value,!0))});var a=r.concat(n),o=d(a,e.id.value,i,e),s=[];return o.forEach(function(r){var n=t.filter(function(t){return t[e.id.value]==r})[0];if(n)s.push(n);else{var a={d3plus:{}};a[e.id.value]=r,s.push(a)}}),s},p.nesting=!1,p.scale=1,p.shapes=["circle","square","donut"],p.requirements=["edges","focus"],p.tooltip="static",t.exports=p},{"../../array/sort.coffee":34,"../../client/pointer.coffee":38,"../../color/legible.coffee":44,"../../color/text.coffee":50,"../../core/fetch/color.coffee":63,"../../core/fetch/value.coffee":67,"../../network/smallestGap.coffee":168,"../../tooltip/remove.coffee":203,"../../util/uniques.coffee":210}],328:[function(e,t,r){var n,a,o,i,s;n=e("./sankey.js"),a=e("../../client/pointer.coffee"),o=e("../../tooltip/remove.coffee"),s=e("../../util/uniques.coffee"),i=function(e){var t,r,i,s,l,u,c,f,d,p,h,v,g,m,y;for(s=e.focus.value[0],v=2*e.data.stroke.width,y=e.size.value.constructor===Number?e.size.value:20,i=e.edges.connections(s,e.id.value).filter(function(t){return t[e.edges.source][e.id.value]!==s||t[e.edges.target][e.id.value]!==s}),h=[],g=[],i=i.map(function(t){var r,n;return t[e.edges.target][e.id.value]===s?(r={id:"left_"+t[e.edges.source][e.id.value],dupe:"left",data:t[e.edges.source],value:t[e.edges.strength.value]},n=t[e.edges.target]):(r=t[e.edges.source],n={id:"right_"+t[e.edges.target][e.id.value],dupe:"right",data:t[e.edges.target],value:t[e.edges.strength.value]}),g.indexOf(r.id)<0&&h.push(r),g.indexOf(n.id)<0&&h.push(n),g.push(r.id),g.push(n.id),{source:r,target:n,value:t[e.edges.strength.value]||1}}),c=n().nodeWidth(y).nodePadding(e.data.padding.value).size([e.width.viz-2*v,e.height.viz-2*v]).nodes(h).links(i).layout(2),m=[],l=0,f=h.length;l0&&(t.y+=r),a=t.y+t.dy+f;if(r=a-f-d[1],r>0)for(a=t.y-=r,n=i-2;n>=0;--n)t=e[n],r=t.y+t.dy+f-a,r>0&&(t.y-=r),a=t.y})}function o(e,t){return e.y-t.y}var i=d3.nest().key(function(e){return e.x}).sortKeys(d3.ascending).entries(p).map(function(e){return e.values});t(),a();for(var u=1;e>0;--e)n(u*=.99),a(),r(u),a()}function i(){function e(e,t){return e.source.y-t.source.y}function t(e,t){return e.target.y-t.target.y}p.forEach(function(r){r.sourceLinks.sort(t),r.targetLinks.sort(e)}),p.forEach(function(e){var t=0,r=0;e.sourceLinks.forEach(function(e){e.sy=t,t+=e.dy}),e.targetLinks.forEach(function(e){e.ty=r,r+=e.dy})})}function s(e){return e.y+e.dy/2}function l(e){return e.value}var u={},c=24,f=8,d=[1,1],p=[],h=[];return u.nodeWidth=function(e){return arguments.length?(c=+e,u):c},u.nodePadding=function(e){return arguments.length?(f=+e,u):f},u.nodes=function(e){return arguments.length?(p=e,u):p},u.links=function(e){return arguments.length?(h=e,u):h},u.size=function(e){return arguments.length?(d=e,u):d},u.layout=function(n){return e(),t(),r(),o(n),i(),u},u.relayout=function(){return i(),u},u.link=function(){function e(e){var r=e.source.x+e.source.dx,n=e.target.x,a=d3.interpolateNumber(r,n),o=a(t),i=a(1-t),s=e.source.y+e.sy+e.dy/2,l=e.target.y+e.ty+e.dy/2;return"M"+r+","+s+"C"+o+","+s+" "+i+","+l+" "+n+","+l}var t=.5;return e.curvature=function(r){return arguments.length?(t=+r,e):t},e},u}},{}],330:[function(e,t,r){var n,a,o,i,s,l;n=e("../../core/fetch/value.coffee"),a=e("./helpers/graph/draw.coffee"),o=e("../../core/console/print.coffee"),s=e("../../array/sort.coffee"),l=e("./helpers/graph/dataTicks.coffee"),i=function(e){var t,r,o,i,u;if(a(e,{buffer:"size",mouse:!0}),r=e.x.domain.viz.concat(e.y.domain.viz),r.indexOf(void 0)>=0)return[];for(u=e.data.viz,o=0,i=u.length;o=0&&r in t&&(d[r]&&(i.d3plus.color=d[r](i[r])),i.d3plus.text=e.format.value(i[r]),"boolean"==e.data.keys[r]?i.d3plus.label=!1:"string"==e.data.keys[r]&&(i.d3plus.color=e.color.missing,i.d3plus.stroke="#fff",i.d3plus.shape="square"),f.push(i))})}),f};s.shapes=["check","cross","diamond","square","triangle","triangle_up","triangle_down"],s.requirements=["data","cols"],t.exports=s},{"../../color/random.coffee":47,"../../core/fetch/value.coffee":67,"../../util/copy.coffee":207,"../../util/uniques.coffee":210}],332:[function(e,t,r){var n,a,o,i;n=e("../../core/data/threshold.js"),a=e("../../core/data/group.coffee"),o=e("../../object/merge.coffee"),i=function(e){var t,r,n,i,s,l,u;if(n=a(e,e.data.viz),r=d3.layout.treemap().mode(e.type.mode.value).round(!0).size([e.width.viz,e.height.viz]).children(function(e){return e.values}).padding(e.data.padding.value).sort(function(e,t){var r;return r=e.value-t.value,0===r?e.id +
+
+ + +
+ +
+
+
+ + + + + + + + + + + + + + + + + + +
minmaxavgtotalcurrent
{{series.alias}}{{series.stats.min}}{{series.stats.max}}{{series.stats.avg}}{{series.stats.total}}{{series.stats.current}}
+
+
\ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/module.js b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/module.js new file mode 100644 index 0000000..fbbe461 --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/module.js @@ -0,0 +1,18 @@ +'use strict'; + +System.register(['./properties', './heatmapControl'], function (_export, _context) { + "use strict"; + + var pluginName, HeatmapCtrl; + return { + setters: [function (_properties) { + pluginName = _properties.pluginName; + }, function (_heatmapControl) { + HeatmapCtrl = _heatmapControl.HeatmapCtrl; + }], + execute: function () { + _export('PanelCtrl', HeatmapCtrl); + } + }; +}); +//# sourceMappingURL=module.js.map diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/module.js.map b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/module.js.map new file mode 100644 index 0000000..d826922 --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/module.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/module.js"],"names":["pluginName","HeatmapCtrl"],"mappings":";;;;;;;;AAAQA,gB,eAAAA,U;;AACAC,iB,mBAAAA,W;;;2BASPA,W","file":"module.js","sourcesContent":["import {pluginName} from './properties';\r\nimport {HeatmapCtrl} from './heatmapControl';\r\n/*import {loadPluginCss} from 'app/plugins/sdk';\r\n\r\nloadPluginCss({\r\n dark: 'plugins/'+pluginName+'/libs/mermaid/dist/mermaid.css',\r\n light: 'plugins/'+pluginName+'/libs/mermaid/dist/mermaid.css'\r\n});*/\r\n\r\nexport {\r\n\tHeatmapCtrl as PanelCtrl\r\n}; "]} \ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/plugin.json b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/plugin.json new file mode 100644 index 0000000..e09584b --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/plugin.json @@ -0,0 +1,36 @@ +{ + "type": "panel", + "name": "Heatmap", + "id": "savantly-heatmap-panel", + "info": { + "description": "Heatmap panel for grafana", + "author": { + "name": "Jeremy Branham", + "url": "https://github.com/jdbranham" + }, + "keywords": [ + "heatmap", + "panel" + ], + "links": [ + { + "name": "Project site", + "url": "https://github.com/savantly-net/grafana-heatmap" + }, + { + "name": "Apache License", + "url": "https://github.com/savantly-net/grafana-heatmap/blob/master/LICENSE" + } + ], + "version": "0.2.1", + "updated": "2016-10-16", + "logos": { + "small": "img/icn-heatmap-panel.svg", + "large": "img/icn-heatmap-panel.svg" + } + }, + "dependencies": { + "grafanaVersion": "3.x.x", + "plugins": [] + } +} \ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/properties.js b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/properties.js new file mode 100644 index 0000000..61c2ac7 --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/properties.js @@ -0,0 +1,24 @@ +'use strict'; + +System.register([], function (_export, _context) { + "use strict"; + + var pluginName, heatmapEditor, displayEditor; + return { + setters: [], + execute: function () { + _export('pluginName', pluginName = 'savantly-heatmap-panel'); + + _export('heatmapEditor', heatmapEditor = 'public/plugins/' + pluginName + '/heatmapEditor.html'); + + _export('displayEditor', displayEditor = 'public/plugins/' + pluginName + '/displayEditor.html'); + + _export('pluginName', pluginName); + + _export('heatmapEditor', heatmapEditor); + + _export('displayEditor', displayEditor); + } + }; +}); +//# sourceMappingURL=properties.js.map diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/properties.js.map b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/properties.js.map new file mode 100644 index 0000000..7fea9cf --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/properties.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/properties.js"],"names":["pluginName","heatmapEditor","displayEditor"],"mappings":";;;;;;;;;yBACIA,U,GAAa,wB;;4BAChBC,a,GAAgB,oBAAmBD,UAAnB,GAA+B,qB;;4BAC/CE,a,GAAgB,oBAAmBF,UAAnB,GAA+B,qB;;yBAG/CA,U;;4BACAC,a;;4BACAC,a","file":"properties.js","sourcesContent":["\r\nvar pluginName = 'savantly-heatmap-panel',\r\n\theatmapEditor = 'public/plugins/'+ pluginName +'/heatmapEditor.html',\r\n\tdisplayEditor = 'public/plugins/'+ pluginName +'/displayEditor.html';\r\n\r\nexport {\r\n\tpluginName,\r\n\theatmapEditor,\r\n\tdisplayEditor\r\n}"]} \ No newline at end of file diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/series_overrides_heatmap_ctrl.js b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/series_overrides_heatmap_ctrl.js new file mode 100644 index 0000000..19fc46f --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/series_overrides_heatmap_ctrl.js @@ -0,0 +1,103 @@ +'use strict'; + +System.register([], function (_export, _context) { + "use strict"; + + return { + setters: [], + execute: function () { + angular.module('grafana.controllers').controller('SeriesOverridesHeatmapCtrl', ['$scope', '$element', 'popoverSrv', function ($scope, $element, popoverSrv) { + $scope.overrideMenu = []; + $scope.currentOverrides = []; + $scope.override = $scope.override || {}; + + $scope.addOverrideOption = function (name, propertyName, values) { + var option = {}; + option.text = name; + option.propertyName = propertyName; + option.index = $scope.overrideMenu.length; + option.values = values; + + option.submenu = _.map(values, function (value) { + return { text: String(value), value: value }; + }); + + $scope.overrideMenu.push(option); + }; + + $scope.setOverride = function (item, subItem) { + // handle color overrides + if (item.propertyName === 'color') { + $scope.openColorSelector(); + return; + } + + $scope.override[item.propertyName] = subItem.value; + $scope.updateCurrentOverrides(); + $scope.ctrl.render(); + }; + + $scope.colorSelected = function (color) { + $scope.override['color'] = color; + $scope.updateCurrentOverrides(); + $scope.ctrl.render(); + }; + + $scope.thresholdsChanged = function (thresholds) { + $scope.override['thresholds'] = thresholds.value; + $scope.updateCurrentOverrides(); + $scope.ctrl.render(); + }; + + $scope.openColorSelector = function () { + popoverSrv.show({ + element: $element.find(".dropdown")[0], + position: 'top center', + openOn: 'click', + template: '', + model: { + autoClose: true, + colorSelected: $scope.colorSelected + }, + onClose: function onClose() { + $scope.ctrl.render(); + } + }); + }; + + $scope.removeOverride = function (option) { + delete $scope.override[option.propertyName]; + $scope.updateCurrentOverrides(); + $scope.ctrl.refresh(); + }; + + $scope.getSeriesNames = function () { + return _.map($scope.ctrl.seriesList, function (series) { + return series.alias; + }); + }; + + $scope.updateCurrentOverrides = function () { + $scope.currentOverrides = []; + _.each($scope.overrideMenu, function (option) { + var value = $scope.override[option.propertyName]; + if (_.isUndefined(value)) { + return; + } + $scope.currentOverrides.push({ + name: option.text, + propertyName: option.propertyName, + value: String(value) + }); + }); + }; + + //$scope.addOverrideOption('Color', 'color', ['change']); + $scope.addOverrideOption('Thresholds', 'thresholds', ['custom']); + $scope.addOverrideOption('Value', 'valueName', ['avg', 'min', 'max', 'total', 'current']); + $scope.updateCurrentOverrides(); + }]); + } + }; +}); +//# sourceMappingURL=series_overrides_heatmap_ctrl.js.map diff --git a/srv/docker/grafana/data/plugins/savantly-heatmap-panel/series_overrides_heatmap_ctrl.js.map b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/series_overrides_heatmap_ctrl.js.map new file mode 100644 index 0000000..4e15cf5 --- /dev/null +++ b/srv/docker/grafana/data/plugins/savantly-heatmap-panel/series_overrides_heatmap_ctrl.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/series_overrides_heatmap_ctrl.js"],"names":["angular","module","controller","$scope","$element","popoverSrv","overrideMenu","currentOverrides","override","addOverrideOption","name","propertyName","values","option","text","index","length","submenu","_","map","value","String","push","setOverride","item","subItem","openColorSelector","updateCurrentOverrides","ctrl","render","colorSelected","color","thresholdsChanged","thresholds","show","element","find","position","openOn","template","model","autoClose","onClose","removeOverride","refresh","getSeriesNames","seriesList","series","alias","each","isUndefined"],"mappings":";;;;;;;;AAAEA,cAAQC,MAAR,CAAe,qBAAf,EAAsCC,UAAtC,CAAiD,4BAAjD,EAA+E,CAAC,QAAD,EAAW,UAAX,EAAuB,YAAvB,EAAqC,UAASC,MAAT,EAAiBC,QAAjB,EAA2BC,UAA3B,EAAuC;AACzJF,eAAOG,YAAP,GAAsB,EAAtB;AACAH,eAAOI,gBAAP,GAA0B,EAA1B;AACAJ,eAAOK,QAAP,GAAkBL,OAAOK,QAAP,IAAmB,EAArC;;AAEAL,eAAOM,iBAAP,GAA2B,UAASC,IAAT,EAAeC,YAAf,EAA6BC,MAA7B,EAAqC;AAC9D,cAAIC,SAAS,EAAb;AACAA,iBAAOC,IAAP,GAAcJ,IAAd;AACAG,iBAAOF,YAAP,GAAsBA,YAAtB;AACAE,iBAAOE,KAAP,GAAeZ,OAAOG,YAAP,CAAoBU,MAAnC;AACAH,iBAAOD,MAAP,GAAgBA,MAAhB;;AAEAC,iBAAOI,OAAP,GAAiBC,EAAEC,GAAF,CAAMP,MAAN,EAAc,UAASQ,KAAT,EAAgB;AAC7C,mBAAO,EAAEN,MAAMO,OAAOD,KAAP,CAAR,EAAuBA,OAAOA,KAA9B,EAAP;AACD,WAFgB,CAAjB;;AAIAjB,iBAAOG,YAAP,CAAoBgB,IAApB,CAAyBT,MAAzB;AACD,SAZD;;AAcAV,eAAOoB,WAAP,GAAqB,UAASC,IAAT,EAAeC,OAAf,EAAwB;AAC3C;AACA,cAAID,KAAKb,YAAL,KAAsB,OAA1B,EAAmC;AACjCR,mBAAOuB,iBAAP;AACA;AACD;;AAEDvB,iBAAOK,QAAP,CAAgBgB,KAAKb,YAArB,IAAqCc,QAAQL,KAA7C;AACAjB,iBAAOwB,sBAAP;AACAxB,iBAAOyB,IAAP,CAAYC,MAAZ;AACD,SAVD;;AAYA1B,eAAO2B,aAAP,GAAuB,UAASC,KAAT,EAAgB;AACrC5B,iBAAOK,QAAP,CAAgB,OAAhB,IAA2BuB,KAA3B;AACA5B,iBAAOwB,sBAAP;AACAxB,iBAAOyB,IAAP,CAAYC,MAAZ;AACD,SAJD;;AAMA1B,eAAO6B,iBAAP,GAA2B,UAASC,UAAT,EAAoB;AAC9C9B,iBAAOK,QAAP,CAAgB,YAAhB,IAAgCyB,WAAWb,KAA3C;AACAjB,iBAAOwB,sBAAP;AACAxB,iBAAOyB,IAAP,CAAYC,MAAZ;AACA,SAJD;;AAMA1B,eAAOuB,iBAAP,GAA2B,YAAW;AACpCrB,qBAAW6B,IAAX,CAAgB;AACdC,qBAAS/B,SAASgC,IAAT,CAAc,WAAd,EAA2B,CAA3B,CADK;AAEdC,sBAAU,YAFI;AAGdC,oBAAQ,OAHM;AAIdC,sBAAU,qCAJI;AAKdC,mBAAO;AACLC,yBAAW,IADN;AAELX,6BAAe3B,OAAO2B;AAFjB,aALO;AASdY,qBAAS,mBAAW;AAClBvC,qBAAOyB,IAAP,CAAYC,MAAZ;AACD;AAXa,WAAhB;AAaD,SAdD;;AAgBA1B,eAAOwC,cAAP,GAAwB,UAAS9B,MAAT,EAAiB;AACvC,iBAAOV,OAAOK,QAAP,CAAgBK,OAAOF,YAAvB,CAAP;AACAR,iBAAOwB,sBAAP;AACAxB,iBAAOyB,IAAP,CAAYgB,OAAZ;AACD,SAJD;;AAMAzC,eAAO0C,cAAP,GAAwB,YAAW;AACjC,iBAAO3B,EAAEC,GAAF,CAAMhB,OAAOyB,IAAP,CAAYkB,UAAlB,EAA8B,UAASC,MAAT,EAAiB;AACpD,mBAAOA,OAAOC,KAAd;AACD,WAFM,CAAP;AAGD,SAJD;;AAMA7C,eAAOwB,sBAAP,GAAgC,YAAW;AACzCxB,iBAAOI,gBAAP,GAA0B,EAA1B;AACAW,YAAE+B,IAAF,CAAO9C,OAAOG,YAAd,EAA4B,UAASO,MAAT,EAAiB;AAC3C,gBAAIO,QAAQjB,OAAOK,QAAP,CAAgBK,OAAOF,YAAvB,CAAZ;AACA,gBAAIO,EAAEgC,WAAF,CAAc9B,KAAd,CAAJ,EAA0B;AAAE;AAAS;AACrCjB,mBAAOI,gBAAP,CAAwBe,IAAxB,CAA6B;AAC3BZ,oBAAMG,OAAOC,IADc;AAE3BH,4BAAcE,OAAOF,YAFM;AAG3BS,qBAAOC,OAAOD,KAAP;AAHoB,aAA7B;AAKD,WARD;AASD,SAXD;;AAaA;AACAjB,eAAOM,iBAAP,CAAyB,YAAzB,EAAuC,YAAvC,EAAqD,CAAC,QAAD,CAArD;AACAN,eAAOM,iBAAP,CAAyB,OAAzB,EAAkC,WAAlC,EAA+C,CAAC,KAAD,EAAQ,KAAR,EAAe,KAAf,EAAsB,OAAtB,EAA+B,SAA/B,CAA/C;AACAN,eAAOwB,sBAAP;AACD,OAxF8E,CAA/E","file":"series_overrides_heatmap_ctrl.js","sourcesContent":[" angular.module('grafana.controllers').controller('SeriesOverridesHeatmapCtrl', ['$scope', '$element', 'popoverSrv', function($scope, $element, popoverSrv) {\n $scope.overrideMenu = [];\n $scope.currentOverrides = [];\n $scope.override = $scope.override || {};\n\n $scope.addOverrideOption = function(name, propertyName, values) {\n var option = {};\n option.text = name;\n option.propertyName = propertyName;\n option.index = $scope.overrideMenu.length;\n option.values = values;\n\n option.submenu = _.map(values, function(value) {\n return { text: String(value), value: value };\n });\n\n $scope.overrideMenu.push(option);\n };\n\n $scope.setOverride = function(item, subItem) {\n // handle color overrides\n if (item.propertyName === 'color') {\n $scope.openColorSelector();\n return;\n }\n\n $scope.override[item.propertyName] = subItem.value;\n $scope.updateCurrentOverrides();\n $scope.ctrl.render();\n };\n\n $scope.colorSelected = function(color) {\n $scope.override['color'] = color;\n $scope.updateCurrentOverrides();\n $scope.ctrl.render();\n };\n \n $scope.thresholdsChanged = function(thresholds){\n \t$scope.override['thresholds'] = thresholds.value;\n \t$scope.updateCurrentOverrides();\n \t$scope.ctrl.render();\n }\n\n $scope.openColorSelector = function() {\n popoverSrv.show({\n element: $element.find(\".dropdown\")[0],\n position: 'top center',\n openOn: 'click',\n template: '',\n model: {\n autoClose: true,\n colorSelected: $scope.colorSelected,\n },\n onClose: function() {\n $scope.ctrl.render();\n }\n });\n };\n \n $scope.removeOverride = function(option) {\n delete $scope.override[option.propertyName];\n $scope.updateCurrentOverrides();\n $scope.ctrl.refresh();\n };\n\n $scope.getSeriesNames = function() {\n return _.map($scope.ctrl.seriesList, function(series) {\n return series.alias;\n });\n };\n\n $scope.updateCurrentOverrides = function() {\n $scope.currentOverrides = [];\n _.each($scope.overrideMenu, function(option) {\n var value = $scope.override[option.propertyName];\n if (_.isUndefined(value)) { return; }\n $scope.currentOverrides.push({\n name: option.text,\n propertyName: option.propertyName,\n value: String(value)\n });\n });\n };\n\n //$scope.addOverrideOption('Color', 'color', ['change']);\n $scope.addOverrideOption('Thresholds', 'thresholds', ['custom']);\n $scope.addOverrideOption('Value', 'valueName', ['avg', 'min', 'max', 'total', 'current']);\n $scope.updateCurrentOverrides();\n }]);\n"]} \ No newline at end of file