diff --git a/build/collection.js b/build/collection.js new file mode 100644 index 0000000..00dbc91 --- /dev/null +++ b/build/collection.js @@ -0,0 +1,141 @@ +// Generated by CoffeeScript 1.6.2 +var DVLCollection, dvl, + __hasProp = {}.hasOwnProperty, + __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; }; + +dvl = require('./core'); + +DVLCollection = (function() { + function DVLCollection(_arg) { + var data, fn, serialize, that; + + data = _arg.data, serialize = _arg.serialize, fn = _arg.fn; + this._data = data; + this._serialize = serialize; + this._fn = fn; + this._dvlBlocks = {}; + this._dvlVariables = {}; + this._positions = {}; + that = this; + dvl.register({ + listen: data, + fn: function() { + var _data; + + _data = data.value(); + if (!Array.isArray(_data)) { + return; + } + return setTimeout(function() { + that._buildBlocks(_data); + return that._destroyBlocks(_data); + }, 0); + } + }); + data.value(data.value()); + } + + DVLCollection.prototype.toString = function() { + return '[DVLCollection]'; + }; + + DVLCollection.prototype._destroyBlocks = function(_data) { + var k, _block, _ref, _serializedData; + + _serializedData = _data.map(this._serialize); + _ref = this._dvlBlocks; + for (k in _ref) { + if (!__hasProp.call(_ref, k)) continue; + _block = _ref[k]; + if (__indexOf.call(_serializedData, k) < 0) { + delete this._dvlBlocks[k]; + _block.discard(); + } + } + }; + + DVLCollection.prototype._buildBlocks = function(_data) { + var badSerial, badSerials, k, tempDvlBlocks, tempDvlVariables, that, transitionMap, v, _i, _len; + + that = this; + transitionMap = {}; + badSerials = []; + _data.forEach(function(_datum, i) { + var _badSerializedDatum, _serializedDatum; + + _serializedDatum = that._serialize(_datum); + if (that._dvlBlocks[_serializedDatum] == null) { + that._dvlBlocks[_serializedDatum] = dvl.block(function() { + that._dvlVariables[_serializedDatum] = dvl(_datum); + that._positions[i] = _serializedDatum; + return that._fn(that._dvlVariables[_serializedDatum]); + }); + } + if (_serializedDatum === that._positions[i]) { + return; + } + badSerials.push(_badSerializedDatum = that._positions[i]); + return transitionMap[_serializedDatum] = { + badSerial: _badSerializedDatum, + datum: _datum, + index: i + }; + }); + tempDvlVariables = {}; + tempDvlBlocks = {}; + for (k in transitionMap) { + v = transitionMap[k]; + tempDvlVariables[k] = this._dvlVariables[v.badSerial]; + tempDvlBlocks[k] = this._dvlBlocks[v.badSerial]; + } + for (k in transitionMap) { + v = transitionMap[k]; + this._dvlVariables[k] = tempDvlVariables[k]; + this._dvlBlocks[k] = tempDvlBlocks[k]; + this._dvlVariables[k].value(v.datum); + this._positions[v.index] = k; + badSerials.splice(badSerials.indexOf(k), 1); + } + for (_i = 0, _len = badSerials.length; _i < _len; _i++) { + badSerial = badSerials[_i]; + delete this._dvlVariables[badSerial]; + delete this._dvlBlocks[badSerial]; + } + }; + + DVLCollection.factory = function() { + var data, fn, serialize, _ref; + + switch (arguments.length) { + case 1: + _ref = arguments[0], data = _ref.data, serialize = _ref.serialize, fn = _ref.fn; + break; + case 2: + data = arguments[0], fn = arguments[1]; + break; + default: + throw "incorect number of arguments"; + } + if (!dvl.knows(data)) { + throw new Error('data should be dvl variable'); + } + if (typeof fn !== 'function') { + throw new Error('function should be provided'); + } + if (serialize == null) { + serialize = function(item) { + return String(item).toString(); + }; + } + return new DVLCollection({ + data: data, + fn: fn, + serialize: serialize + }); + }; + + return DVLCollection; + +})(); + +module.exports = DVLCollection.factory; diff --git a/dvl.js b/dvl.js index e612120..d62f40d 100644 --- a/dvl.js +++ b/dvl.js @@ -373,7 +373,7 @@ async.requester = { module.exports = async; -},{"./core":3,"./util":12}],2:[function(require,module,exports){ +},{"./core":4,"./util":12}],2:[function(require,module,exports){ // Generated by CoffeeScript 1.6.2 var bind, bindSingle, class_concat, def_data_fn, dvl, id_class_spliter; @@ -390,7 +390,7 @@ class_concat = dvl.op(function(s, d) { }); bind = function(_arg) { - var argsOn, attr, attrList, data, html, join, k, listen, nodeType, onList, out, parent, part, parts, property, propertyList, self, staticClass, staticId, style, styleList, text, transition, transitionExit, v, _i, _len; + var argsOn, attr, attrList, bindWorker, data, html, join, k, listen, nodeType, onList, out, parent, part, parts, property, propertyList, self, staticClass, staticId, style, styleList, text, transition, transitionExit, v, _i, _len; parent = _arg.parent, self = _arg.self, data = _arg.data, join = _arg.join, attr = _arg.attr, style = _arg.style, property = _arg.property, text = _arg.text, html = _arg.html, argsOn = _arg.on, transition = _arg.transition, transitionExit = _arg.transitionExit; if (!parent) { @@ -460,7 +460,7 @@ bind = function(_arg) { onList[k] = v; } out = dvl().name('selection'); - dvl.register({ + bindWorker = dvl.register({ listen: listen, change: [out], fn: function() { @@ -595,11 +595,15 @@ bind = function(_arg) { } } }); + bindWorker.on('discard', function() { + out.value().remove(); + return out.value(null); + }); return out; }; bindSingle = function(_arg) { - var argsOn, attr, attrList, data, datum, html, k, listen, nodeType, onList, parent, part, parts, property, propertyList, self, staticClass, staticId, style, styleList, text, transition, v, _i, _len; + var argsOn, attr, attrList, bindWorker, data, datum, html, k, listen, nodeType, onList, parent, part, parts, property, propertyList, self, staticClass, staticId, style, styleList, text, transition, v, _i, _len; parent = _arg.parent, self = _arg.self, data = _arg.data, datum = _arg.datum, attr = _arg.attr, style = _arg.style, property = _arg.property, text = _arg.text, html = _arg.html, argsOn = _arg.on, transition = _arg.transition; if (data) { @@ -670,7 +674,7 @@ bindSingle = function(_arg) { listen.push(v); onList[k] = v; } - dvl.register({ + bindWorker = dvl.register({ listen: listen, change: [self], fn: function() { @@ -717,6 +721,10 @@ bindSingle = function(_arg) { } } }); + bindWorker.on('discard', function() { + self.value().remove(); + return self.value(null); + }); return self; }; @@ -725,7 +733,150 @@ module.exports = { bindSingle: bindSingle }; -},{"./core":3}],3:[function(require,module,exports){ +},{"./core":4}],3:[function(require,module,exports){ +// Generated by CoffeeScript 1.6.2 +var DVLCollection, dvl, + __hasProp = {}.hasOwnProperty, + __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; }; + +dvl = require('./core'); + +DVLCollection = (function() { + function DVLCollection(_arg) { + var data, fn, serialize, that; + + data = _arg.data, serialize = _arg.serialize, fn = _arg.fn; + this._data = data; + this._serialize = serialize; + this._fn = fn; + this._dvlBlocks = {}; + this._dvlVariables = {}; + this._positions = {}; + that = this; + dvl.register({ + listen: data, + fn: function() { + var _data; + + _data = data.value(); + if (!Array.isArray(_data)) { + return; + } + return setTimeout(function() { + that._buildBlocks(_data); + return that._destroyBlocks(_data); + }, 0); + } + }); + data.value(data.value()); + } + + DVLCollection.prototype.toString = function() { + return '[DVLCollection]'; + }; + + DVLCollection.prototype._destroyBlocks = function(_data) { + var k, _block, _ref, _serializedData; + + _serializedData = _data.map(this._serialize); + _ref = this._dvlBlocks; + for (k in _ref) { + if (!__hasProp.call(_ref, k)) continue; + _block = _ref[k]; + if (__indexOf.call(_serializedData, k) < 0) { + delete this._dvlBlocks[k]; + _block.discard(); + } + } + }; + + DVLCollection.prototype._buildBlocks = function(_data) { + var badSerial, badSerials, k, tempDvlBlocks, tempDvlVariables, that, transitionMap, v, _i, _len; + + that = this; + transitionMap = {}; + badSerials = []; + _data.forEach(function(_datum, i) { + var _badSerializedDatum, _serializedDatum; + + _serializedDatum = that._serialize(_datum); + if (that._dvlBlocks[_serializedDatum] == null) { + that._dvlBlocks[_serializedDatum] = dvl.block(function() { + that._dvlVariables[_serializedDatum] = dvl(_datum); + that._positions[i] = _serializedDatum; + return that._fn(that._dvlVariables[_serializedDatum]); + }); + } + if (_serializedDatum === that._positions[i]) { + return; + } + badSerials.push(_badSerializedDatum = that._positions[i]); + return transitionMap[_serializedDatum] = { + badSerial: _badSerializedDatum, + datum: _datum, + index: i + }; + }); + tempDvlVariables = {}; + tempDvlBlocks = {}; + for (k in transitionMap) { + v = transitionMap[k]; + tempDvlVariables[k] = this._dvlVariables[v.badSerial]; + tempDvlBlocks[k] = this._dvlBlocks[v.badSerial]; + } + for (k in transitionMap) { + v = transitionMap[k]; + this._dvlVariables[k] = tempDvlVariables[k]; + this._dvlBlocks[k] = tempDvlBlocks[k]; + this._dvlVariables[k].value(v.datum); + this._positions[v.index] = k; + badSerials.splice(badSerials.indexOf(k), 1); + } + for (_i = 0, _len = badSerials.length; _i < _len; _i++) { + badSerial = badSerials[_i]; + delete this._dvlVariables[badSerial]; + delete this._dvlBlocks[badSerial]; + } + }; + + DVLCollection.factory = function() { + var data, fn, serialize, _ref; + + switch (arguments.length) { + case 1: + _ref = arguments[0], data = _ref.data, serialize = _ref.serialize, fn = _ref.fn; + break; + case 2: + data = arguments[0], fn = arguments[1]; + break; + default: + throw "incorect number of arguments"; + } + if (!dvl.knows(data)) { + throw new Error('data should be dvl variable'); + } + if (typeof fn !== 'function') { + throw new Error('function should be provided'); + } + if (serialize == null) { + serialize = function(item) { + return String(item).toString(); + }; + } + return new DVLCollection({ + data: data, + fn: fn, + serialize: serialize + }); + }; + + return DVLCollection; + +})(); + +module.exports = DVLCollection.factory; + +},{"./core":4}],4:[function(require,module,exports){ // Generated by CoffeeScript 1.6.2 var DVLBlock, DVLConst, DVLVar, DVLWorker, PriorityQueue, Set, collect_notify, curBlock, curCollectListener, curNotifyListener, default_compare, dvl, end_notify_collect, fn, getBase, init_notify, k, levelPriorityQueue, lift, nextObjId, nsId, op_to_lift, sortGraph, start_notify_collect, toNotify, uniqById, utilModule, variables, workers, __slice = [].slice, @@ -997,11 +1148,21 @@ DVLVar = (function() { }; DVLVar.prototype.discard = function() { - if (this.listeners.length > 0) { - throw "Cannot remove variable " + this.id + " because it has listeners."; + var v, _i, _j, _len, _len1, _ref, _ref1; + + _ref = this.changers; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + v = _ref[_i]; + if (v.change.indexOf(this) > -1) { + v.change.splice(v.change.indexOf(this), 1); + } } - if (this.changers.length > 0) { - throw "Cannot remove variable " + this.id + " because it has changers."; + _ref1 = this.listeners; + for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { + v = _ref1[_j]; + if (v.listen.indexOf(this) > -1) { + v.listen.splice(v.listen.indexOf(this), 1); + } } variables.splice(variables.indexOf(this), 1); return null; @@ -1126,6 +1287,7 @@ DVLWorker = (function() { this.change = change; this.id = nextObjId++; this.updates = new Set(); + this.eventArrays = {}; this.level = workers.length; workers.push(this); hasPrev = false; @@ -1231,7 +1393,7 @@ DVLWorker = (function() { }; DVLWorker.prototype.discard = function() { - var prevWorker, v, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1, _ref2, _ref3; + var prevWorker, v, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1, _ref2, _ref3, _ref4; workers.splice(workers.indexOf(this), 1); _ref = this.listen; @@ -1246,15 +1408,33 @@ DVLWorker = (function() { _ref2 = this.change; for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { v = _ref2[_k]; - v.changers.splice(v.changers.indexOf(this), 1); + if (v.changers.indexOf(this) > -1) { + v.changers.splice(v.changers.indexOf(this), 1); + } } _ref3 = this.listen; for (_l = 0, _len3 = _ref3.length; _l < _len3; _l++) { v = _ref3[_l]; - v.listeners.splice(v.listeners.indexOf(this), 1); + if (v.listeners.indexOf(this) > -1) { + v.listeners.splice(v.listeners.indexOf(this), 1); + } } sortGraph(); this.change = this.listen = this.updates = null; + if ((_ref4 = this.eventArrays.discard) != null) { + _ref4.forEach(function(fn) { + return fn(); + }); + } + }; + + DVLWorker.prototype.on = function(type, fn) { + var _base, _ref; + + if ((_ref = (_base = this.eventArrays)[type]) == null) { + _base[type] = []; + } + this.eventArrays[type].push(fn); }; return DVLWorker; @@ -1339,15 +1519,15 @@ DVLBlock = (function() { }; DVLBlock.prototype.discard = function() { - var d, _i, _len, _ref, _ref1; + var k, v, _ref, _ref1; if ((_ref = this.parent) != null) { _ref.removeMemeber(this); } _ref1 = this.owns; - for (_i = 0, _len = _ref1.length; _i < _len; _i++) { - d = _ref1[_i]; - d.discard(); + for (k in _ref1) { + v = _ref1[k]; + v.discard(); } }; @@ -1372,7 +1552,7 @@ dvl.blockFn = function() { var args, block, ret; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; - block = new DVLBlock(name, curBlock); + curBlock = block = new DVLBlock(name, curBlock); ret = fn.apply(this, args); curBlock = block.parent; return ret; @@ -1392,7 +1572,7 @@ dvl.block = function() { default: throw "bad number of arguments"; } - block = new DVLBlock(name, curBlock); + curBlock = block = new DVLBlock(name, curBlock); fn.call(this); curBlock = block.parent; return block; @@ -2030,51 +2210,7 @@ for (k in op_to_lift) { module.exports = dvl; -},{"../lib/lift":13,"./dataStructure/priorityQueue":5,"./dataStructure/set":6,"./util":12}],4:[function(require,module,exports){ -// Generated by CoffeeScript 1.6.2 -var data, dvl; - -dvl = require('./core'); - -data = {}; - -data.min = function(data, acc) { - acc || (acc = dvl.identity); - return dvl.apply({ - args: [data, acc], - update: true, - fn: function(_data, _acc) { - return _data.reduce(function(_prev, _curr) { - if (_acc(_prev) > _acc(_curr)) { - return _curr; - } else { - return _prev; - } - }); - } - }); -}; - -data.max = function(data, acc) { - acc || (acc = dvl.identity); - return dvl.apply({ - args: [data, acc], - update: true, - fn: function(_data, _acc) { - return _data.reduce(function(_prev, _curr) { - if (_acc(_prev) < _acc(_curr)) { - return _curr; - } else { - return _prev; - } - }); - } - }); -}; - -module.exports = data; - -},{"./core":3}],5:[function(require,module,exports){ +},{"../lib/lift":13,"./dataStructure/priorityQueue":5,"./dataStructure/set":6,"./util":12}],5:[function(require,module,exports){ // Generated by CoffeeScript 1.6.2 var PriorityQueue; @@ -3691,14 +3827,12 @@ dvl.compare = function(acc, reverse) { module.exports = htmlModule; -},{"./bind":2,"./core":3,"d3":15}],8:[function(require,module,exports){ +},{"./bind":2,"./core":4,"d3":15}],8:[function(require,module,exports){ // Generated by CoffeeScript 1.6.2 var bind, bindSingle, dvl, _ref; dvl = require('./core'); -dvl.data = require('./data'); - dvl.async = require('./async'); _ref = require('./bind'), bind = _ref.bind, bindSingle = _ref.bindSingle; @@ -3717,9 +3851,11 @@ dvl.misc = require('./misc'); dvl.util = require('./util'); +dvl.collection = require('./collection'); + module.exports = dvl; -},{"./async":1,"./bind":2,"./core":3,"./data":4,"./html":7,"./misc":9,"./snap":10,"./svg":11,"./util":12}],9:[function(require,module,exports){ +},{"./async":1,"./bind":2,"./collection":3,"./core":4,"./html":7,"./misc":9,"./snap":10,"./svg":11,"./util":12}],9:[function(require,module,exports){ // Generated by CoffeeScript 1.6.2 var d3, dvl, miscModule; @@ -3789,7 +3925,7 @@ miscModule.delay = function(data, time) { module.exports = miscModule; -},{"./core":3,"d3":15}],10:[function(require,module,exports){ +},{"./core":4,"d3":15}],10:[function(require,module,exports){ // Generated by CoffeeScript 1.6.2 var dvl; @@ -3849,7 +3985,7 @@ module.exports = function(_arg) { return out; }; -},{"./core":3}],11:[function(require,module,exports){ +},{"./core":4}],11:[function(require,module,exports){ // Generated by CoffeeScript 1.6.2 var bind, bindSingle, clipId, dvl, svgModule, _ref; @@ -3885,7 +4021,7 @@ svgModule.clipPath = function(_arg) { module.exports = svgModule; -},{"./bind":2,"./core":3}],12:[function(require,module,exports){ +},{"./bind":2,"./core":4}],12:[function(require,module,exports){ // Generated by CoffeeScript 1.6.2 var utilModule; @@ -4066,12 +4202,24 @@ if (typeof module !== 'undefined') { },{}],14:[function(require,module,exports){ d3 = function() { var d3 = { - version: "3.2.7" + version: "3.3.13" }; if (!Date.now) Date.now = function() { return +new Date(); }; + var d3_arraySlice = [].slice, d3_array = function(list) { + return d3_arraySlice.call(list); + }; var d3_document = document, d3_documentElement = d3_document.documentElement, d3_window = window; + try { + d3_array(d3_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; + }; + } try { d3_document.createElement("div").style.setProperty("opacity", 0, ""); } catch (error) { @@ -4197,10 +4345,15 @@ d3 = function() { return array; }; d3.permute = function(array, indexes) { - var permutes = [], i = -1, n = indexes.length; - while (++i < n) permutes[i] = array[indexes[i]]; + var i = indexes.length, permutes = new Array(i); + while (i--) permutes[i] = array[indexes[i]]; return permutes; }; + d3.pairs = function(array) { + var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n); + while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ]; + return pairs; + }; d3.zip = function() { if (!(n = arguments.length)) return []; for (var i = -1, m = d3.min(arguments, d3_zipLength), zips = new Array(m); ++i < m; ) { @@ -4235,8 +4388,19 @@ d3 = function() { return entries; }; d3.merge = function(arrays) { - return Array.prototype.concat.apply([], 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; @@ -4246,7 +4410,7 @@ d3 = function() { } } if ((stop - start) / step === Infinity) throw new Error("infinite range"); - var range = [], k = d3_range_integerScale(Math.abs(step)), i = -1, j; + 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; @@ -4270,7 +4434,9 @@ d3 = function() { } d3.map = function(object) { var map = new d3_Map(); - for (var key in object) map.set(key, object[key]); + if (object instanceof d3_Map) object.forEach(function(key, value) { + map.set(key, value); + }); else for (var key in object) map.set(key, object[key]); return map; }; function d3_Map() {} @@ -4320,7 +4486,7 @@ d3 = function() { } } }); - var d3_map_prefix = "\0", d3_map_prefixCode = d3_map_prefix.charCodeAt(0); + var d3_map_prefix = "\x00", d3_map_prefixCode = d3_map_prefix.charCodeAt(0); d3.nest = function() { var nest = {}, keys = [], sortKeys = [], sortValues, rollup; function map(mapType, array, depth) { @@ -4386,7 +4552,7 @@ d3 = function() { }; d3.set = function(array) { var set = new d3_Set(); - if (array) for (var i = 0; i < array.length; i++) set.add(array[i]); + if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]); return set; }; function d3_Set() {} @@ -4438,20 +4604,6 @@ d3 = function() { } } var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ]; - var d3_array = d3_arraySlice; - function d3_arrayCopy(pseudoarray) { - var i = -1, n = pseudoarray.length, array = []; - while (++i < n) array.push(pseudoarray[i]); - return array; - } - function d3_arraySlice(pseudoarray) { - return Array.prototype.slice.call(pseudoarray); - } - try { - d3_array(d3_documentElement.childNodes)[0].nodeType; - } catch (e) { - d3_array = d3_arrayCopy; - } function d3_noop() {} d3.dispatch = function() { var dispatch = new d3_dispatch(), i = -1, n = arguments.length; @@ -4657,7 +4809,7 @@ d3 = function() { d3_selectionPrototype.classed = function(name, value) { if (arguments.length < 2) { if (typeof name === "string") { - var node = this.node(), n = (name = name.trim().split(/^|\s+/g)).length, i = -1; + 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 { @@ -4674,8 +4826,11 @@ d3 = function() { 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 = name.trim().split(/\s+/).map(d3_selection_classedName); + name = d3_selection_classes(name).map(d3_selection_classedName); var n = name.length; function classedConstant() { var i = -1; @@ -4775,16 +4930,16 @@ d3 = function() { }; function d3_selection_creator(name) { return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? function() { - return d3_document.createElementNS(name.space, name.local); + return this.ownerDocument.createElementNS(name.space, name.local); } : function() { - return d3_document.createElementNS(this.namespaceURI, name); + return this.ownerDocument.createElementNS(this.namespaceURI, name); }; } 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)); + return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null); }); }; d3_selectionPrototype.remove = function() { @@ -4890,7 +5045,7 @@ d3 = function() { 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)) { + if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { subgroup.push(node); } } @@ -4921,7 +5076,7 @@ d3 = function() { function d3_selection_sortComparator(comparator) { if (!arguments.length) comparator = d3.ascending; return function(a, b) { - return !a - !b || comparator(a.__data__, b.__data__); + return a && b ? comparator(a.__data__, b.__data__) : !a - !b; }; } d3_selectionPrototype.each = function(callback) { @@ -5020,6 +5175,13 @@ d3 = function() { } return d3_transition(subgroups, id); }; + d3_selectionPrototype.interrupt = function() { + return this.each(d3_selection_interrupt); + }; + function d3_selection_interrupt() { + var lock = this.__transition__; + if (lock) ++lock.active; + } d3.select = function(node) { var group = [ typeof node === "string" ? d3_select(node, d3_document) : node ]; group.parentNode = d3_documentElement; @@ -5102,13 +5264,16 @@ d3 = function() { } }; } - var d3_event_dragSelect = d3_vendorSymbol(d3_documentElement.style, "userSelect"), d3_event_dragId = 0; + var d3_event_dragSelect = "onselectstart" in d3_document ? null : d3_vendorSymbol(d3_documentElement.style, "userSelect"), d3_event_dragId = 0; function d3_event_dragSuppress() { - var name = ".dragsuppress-" + ++d3_event_dragId, touchmove = "touchmove" + name, selectstart = "selectstart" + name, dragstart = "dragstart" + name, click = "click" + name, w = d3.select(d3_window).on(touchmove, d3_eventPreventDefault).on(selectstart, d3_eventPreventDefault).on(dragstart, d3_eventPreventDefault), style = d3_documentElement.style, select = style[d3_event_dragSelect]; - style[d3_event_dragSelect] = "none"; + var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault); + if (d3_event_dragSelect) { + var style = d3_documentElement.style, select = style[d3_event_dragSelect]; + style[d3_event_dragSelect] = "none"; + } return function(suppressClick) { w.on(name, null); - style[d3_event_dragSelect] = select; + if (d3_event_dragSelect) style[d3_event_dragSelect] = select; if (suppressClick) { function off() { w.on(click, null); @@ -5126,6 +5291,7 @@ d3 = function() { }; var d3_mouse_bug44083 = /WebKit/.test(d3_window.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(); @@ -5142,13 +5308,8 @@ d3 = function() { 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; - } + 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 ]; } @@ -5189,7 +5350,6 @@ d3 = function() { type: "dragstart" }); function moved() { - if (!parent) return ended(); var p = position(parent, eventId), dx = p[0] - origin_[0], dy = p[1] - origin_[1]; dragged |= dx | dy; origin_ = p; @@ -5217,141 +5377,290 @@ d3 = function() { }; return d3.rebind(drag, event, "on"); }; - d3.behavior.zoom = function() { - var translate = [ 0, 0 ], translate0, scale = 1, scaleExtent = d3_behavior_zoomInfinity, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", event = d3_eventDispatch(zoom, "zoom"), x0, x1, y0, y1, touchtime; - function zoom() { - this.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on(mousemove, mousewheelreset).on("dblclick.zoom", dblclicked).on("touchstart.zoom", touchstarted); + var π = Math.PI, τ = 2 * π, halfπ = π / 2, ε = 1e-6, ε2 = ε * ε, d3_radians = π / 180, d3_degrees = 180 / π; + function d3_sgn(x) { + return x > 0 ? 1 : x < 0 ? -1 : 0; + } + function d3_acos(x) { + return x > 1 ? 0 : x < -1 ? π : Math.acos(x); + } + function d3_asin(x) { + return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x); + } + function d3_sinh(x) { + return ((x = Math.exp(x)) - 1 / x) / 2; + } + function d3_cosh(x) { + return ((x = Math.exp(x)) + 1 / x) / 2; + } + function d3_tanh(x) { + return ((x = Math.exp(2 * x)) - 1) / (x + 1); + } + function d3_haversin(x) { + return (x = Math.sin(x / 2)) * x; + } + var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4; + d3.interpolateZoom = function(p0, p1) { + var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2]; + var dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1), dr = r1 - r0, S = (dr || Math.log(w1 / w0)) / ρ; + function interpolate(t) { + var s = t * S; + if (dr) { + var coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0)); + return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ]; + } + return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * s) ]; } - zoom.translate = function(x) { - if (!arguments.length) return translate; - translate = x.map(Number); + interpolate.duration = S * 1e3; + return interpolate; + }; + d3.behavior.zoom = function() { + var view = { + x: 0, + y: 0, + k: 1 + }, translate0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, 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; + function zoom(g) { + g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on(mousemove, mousewheelreset).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted); + } + zoom.event = function(g) { + g.each(function() { + var event_ = 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(event_); + }).tween("zoom:zoom", function() { + var dx = size[0], dy = size[1], cx = dx / 2, cy = 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(event_); + }; + }).each("end.zoom", function() { + zoomended(event_); + }); + } else { + this.__chart__ = view; + zoomstarted(event_); + zoomed(event_); + zoomended(event_); + } + }); + }; + 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(x) { - if (!arguments.length) return scale; - scale = +x; + zoom.scale = function(_) { + if (!arguments.length) return view.k; + view = { + x: view.x, + y: view.y, + k: +_ + }; rescale(); return zoom; }; - zoom.scaleExtent = function(x) { + zoom.scaleExtent = function(_) { if (!arguments.length) return scaleExtent; - scaleExtent = x == null ? d3_behavior_zoomInfinity : x.map(Number); + 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.x = function(z) { if (!arguments.length) return x1; x1 = z; x0 = z.copy(); - translate = [ 0, 0 ]; - scale = 1; + view = { + x: 0, + y: 0, + k: 1 + }; return zoom; }; zoom.y = function(z) { if (!arguments.length) return y1; y1 = z; y0 = z.copy(); - translate = [ 0, 0 ]; - scale = 1; + view = { + x: 0, + y: 0, + k: 1 + }; return zoom; }; function location(p) { - return [ (p[0] - translate[0]) / scale, (p[1] - translate[1]) / scale ]; + return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ]; } function point(l) { - return [ l[0] * scale + translate[0], l[1] * scale + translate[1] ]; + return [ l[0] * view.k + view.x, l[1] * view.k + view.y ]; } function scaleTo(s) { - scale = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s)); + view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s)); } function translateTo(p, l) { l = point(l); - translate[0] += p[0] - l[0]; - translate[1] += p[1] - l[1]; + view.x += p[0] - l[0]; + view.y += p[1] - l[1]; } function rescale() { if (x1) x1.domain(x0.range().map(function(x) { - return (x - translate[0]) / scale; + return (x - view.x) / view.k; }).map(x0.invert)); if (y1) y1.domain(y0.range().map(function(y) { - return (y - translate[1]) / scale; + return (y - view.y) / view.k; }).map(y0.invert)); } - function dispatch(event) { + function zoomstarted(event) { + event({ + type: "zoomstart" + }); + } + function zoomed(event) { rescale(); event({ type: "zoom", - scale: scale, - translate: translate + scale: view.k, + translate: [ view.x, view.y ] + }); + } + function zoomended(event) { + event({ + type: "zoomend" }); } function mousedowned() { var target = this, event_ = event.of(target, arguments), eventTarget = d3.event.target, dragged = 0, w = d3.select(d3_window).on(mousemove, moved).on(mouseup, ended), l = location(d3.mouse(target)), dragRestore = d3_event_dragSuppress(); + d3_selection_interrupt.call(target); + zoomstarted(event_); function moved() { dragged = 1; translateTo(d3.mouse(target), l); - dispatch(event_); + zoomed(event_); } function ended() { w.on(mousemove, d3_window === target ? mousewheelreset : null).on(mouseup, null); dragRestore(dragged && d3.event.target === eventTarget); + zoomended(event_); } } function touchstarted() { - var target = this, event_ = event.of(target, arguments), touches = d3.touches(target), locations = {}, distance0 = 0, scale0 = scale, now = Date.now(), name = "zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove." + name, touchend = "touchend." + name, w = d3.select(d3_window).on(touchmove, moved).on(touchend, ended), t = d3.select(target).on(mousedown, null), dragRestore = d3_event_dragSuppress(); - touches.forEach(function(t) { - locations[t.identifier] = location(t); - }); - if (touches.length === 1) { - if (now - touchtime < 500) { - var p = touches[0], l = location(touches[0]); - scaleTo(scale * 2); - translateTo(p, l); - d3_eventPreventDefault(); - dispatch(event_); + var target = this, event_ = event.of(target, arguments), locations0 = {}, distance0 = 0, scale0, eventId = d3.event.changedTouches[0].identifier, touchmove = "touchmove.zoom-" + eventId, touchend = "touchend.zoom-" + eventId, w = d3.select(d3_window).on(touchmove, moved).on(touchend, ended), t = d3.select(target).on(mousedown, null).on(touchstart, started), dragRestore = d3_event_dragSuppress(); + d3_selection_interrupt.call(target); + started(); + zoomstarted(event_); + function relocate() { + var touches = d3.touches(target); + scale0 = view.k; + touches.forEach(function(t) { + if (t.identifier in locations0) locations0[t.identifier] = location(t); + }); + return touches; + } + function started() { + 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], l = locations0[p.identifier]; + scaleTo(view.k * 2); + translateTo(p, l); + d3_eventPreventDefault(); + zoomed(event_); + } + 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; } - 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(target), p0 = touches[0], l0 = locations[p0.identifier]; - if (p1 = touches[1]) { - var p1, l1 = locations[p1.identifier], scale1 = d3.event.scale; - if (scale1 == null) { - var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1; - scale1 = distance0 && Math.sqrt(distance1 / distance0); + var touches = d3.touches(target), p0, l0, p1, l1; + 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); - dispatch(event_); + zoomed(event_); } 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(); + } + } w.on(touchmove, null).on(touchend, null); - t.on(mousedown, mousedowned); + t.on(mousedown, mousedowned).on(touchstart, touchstarted); dragRestore(); + zoomended(event_); } } function mousewheeled() { + var event_ = event.of(this, arguments); + if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this), + zoomstarted(event_); + mousewheelTimer = setTimeout(function() { + mousewheelTimer = null; + zoomended(event_); + }, 50); d3_eventPreventDefault(); - if (!translate0) translate0 = location(d3.mouse(this)); - scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * scale); - translateTo(d3.mouse(this), translate0); - dispatch(event.of(this, arguments)); + var point = center || d3.mouse(this); + if (!translate0) translate0 = location(point); + scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k); + translateTo(point, translate0); + zoomed(event_); } function mousewheelreset() { translate0 = null; } function dblclicked() { - var p = d3.mouse(this), l = location(p), k = Math.log(scale) / Math.LN2; + var event_ = event.of(this, arguments), p = d3.mouse(this), l = location(p), k = Math.log(view.k) / Math.LN2; + zoomstarted(event_); scaleTo(Math.pow(2, d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1)); translateTo(p, l); - dispatch(event.of(this, arguments)); + zoomed(event_); + zoomended(event_); } return d3.rebind(zoom, event, "on"); }; @@ -5409,25 +5718,6 @@ d3 = function() { } return d3_rgb(vv(h + 120), vv(h), vv(h - 120)); } - var π = Math.PI, ε = 1e-6, ε2 = ε * ε, d3_radians = π / 180, d3_degrees = 180 / π; - function d3_sgn(x) { - return x > 0 ? 1 : x < 0 ? -1 : 0; - } - function d3_acos(x) { - return x > 1 ? 0 : x < -1 ? π : Math.acos(x); - } - function d3_asin(x) { - return x > 1 ? π / 2 : x < -1 ? -π / 2 : Math.asin(x); - } - function d3_sinh(x) { - return (Math.exp(x) - Math.exp(-x)) / 2; - } - function d3_cosh(x) { - return (Math.exp(x) + Math.exp(-x)) / 2; - } - function d3_haversin(x) { - return (x = Math.sin(x / 2)) * x; - } d3.hcl = function(h, c, l) { return arguments.length === 1 ? h instanceof d3_Hcl ? 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) : d3_hcl(+h, +c, +l); }; @@ -5769,7 +6059,7 @@ d3 = function() { }; } function d3_xhr(url, mimeType, response, callback) { - var xhr = {}, dispatch = d3.dispatch("progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null; + var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null; if (d3_window.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(); @@ -5832,6 +6122,7 @@ d3 = function() { 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; }; @@ -5851,11 +6142,11 @@ d3 = function() { 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, callback); + 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.row(row); + return xhr; } function response(request) { return dsv.parse(request.responseText); @@ -5959,11 +6250,12 @@ d3 = function() { if (n < 2) delay = 0; if (n < 3) then = Date.now(); var time = then + delay, timer = { - callback: callback, - time: time, - next: null + c: callback, + t: time, + f: false, + n: null }; - if (d3_timer_queueTail) d3_timer_queueTail.next = timer; else d3_timer_queueHead = timer; + 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); @@ -5988,30 +6280,23 @@ d3 = function() { d3_timer_mark(); d3_timer_sweep(); }; - function d3_timer_replace(callback, delay, then) { - var n = arguments.length; - if (n < 2) delay = 0; - if (n < 3) then = Date.now(); - d3_timer_active.callback = callback; - d3_timer_active.time = then + delay; - } function d3_timer_mark() { var now = Date.now(); d3_timer_active = d3_timer_queueHead; while (d3_timer_active) { - if (now >= d3_timer_active.time) d3_timer_active.flush = d3_timer_active.callback(now - d3_timer_active.time); - d3_timer_active = d3_timer_active.next; + if (now >= d3_timer_active.t) d3_timer_active.f = d3_timer_active.c(now - d3_timer_active.t); + d3_timer_active = d3_timer_active.n; } return now; } function d3_timer_sweep() { var t0, t1 = d3_timer_queueHead, time = Infinity; while (t1) { - if (t1.flush) { - t1 = t0 ? t0.next = t1.next : d3_timer_queueHead = t1.next; + if (t1.f) { + t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n; } else { - if (t1.time < time) time = t1.time; - t1 = (t0 = t1).next; + if (t1.t < time) time = t1.t; + t1 = (t0 = t1).n; } } d3_timer_queueTail = t0; @@ -6030,7 +6315,7 @@ d3 = function() { return d3_formatPrefixes[8 + i / 3]; }; function d3_formatPrefix(d, i) { - var k = Math.pow(10, Math.abs(8 - i) * 3); + var k = Math.pow(10, abs(8 - i) * 3); return { scale: i > 8 ? function(d) { return d / k; @@ -6209,12 +6494,12 @@ d3 = function() { listener.sphere(); }, Point: function(object, listener) { - var coordinate = object.coordinates; - listener.point(coordinate[0], coordinate[1]); + object = object.coordinates; + listener.point(object[0], object[1], object[2]); }, MultiPoint: function(object, listener) { - var coordinates = object.coordinates, i = -1, n = coordinates.length, coordinate; - while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1]); + 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); @@ -6238,7 +6523,7 @@ d3 = function() { 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]); + while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]); listener.lineEnd(); } function d3_geo_streamPolygon(coordinates, listener) { @@ -6316,7 +6601,7 @@ d3 = function() { return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ]; } function d3_geo_sphericalEqual(a, b) { - return Math.abs(a[0] - b[0]) < ε && Math.abs(a[1] - b[1]) < ε; + 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; @@ -6351,7 +6636,7 @@ d3 = function() { 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 = Math.abs(dλ) > 180; + 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; @@ -6396,7 +6681,7 @@ d3 = function() { function ringPoint(λ, φ) { if (p0) { var dλ = λ - λ_; - dλSum += Math.abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ; + dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ; } else λ__ = λ, φ__ = φ; d3_geo_area.point(λ, φ); linePoint(λ, φ); @@ -6407,7 +6692,7 @@ d3 = function() { function ringEnd() { ringPoint(λ__, φ__); d3_geo_area.lineEnd(); - if (Math.abs(dλSum) > ε) λ0 = -(λ1 = 180); + if (abs(dλSum) > ε) λ0 = -(λ1 = 180); range[0] = λ0, range[1] = λ1; p0 = null; } @@ -6539,7 +6824,7 @@ d3 = function() { function d3_true() { return true; } - function d3_geo_clipPolygon(segments, compare, inside, interpolate, listener) { + function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) { var subject = [], clip = []; segments.forEach(function(segment) { if ((n = segment.length - 1) <= 0) return; @@ -6550,41 +6835,13 @@ d3 = function() { listener.lineEnd(); return; } - var a = { - point: p0, - points: segment, - other: null, - visited: false, - entry: true, - subject: true - }, b = { - point: p0, - points: [ p0 ], - other: a, - visited: false, - entry: false, - subject: false - }; - a.other = b; + 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 = { - point: p1, - points: [ p1 ], - other: null, - visited: false, - entry: false, - subject: true - }; - b = { - point: p1, - points: [ p1 ], - other: a, - visited: false, - entry: true, - subject: false - }; - a.other = 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); }); @@ -6592,36 +6849,37 @@ d3 = function() { d3_geo_clipPolygonLinkCircular(subject); d3_geo_clipPolygonLinkCircular(clip); if (!subject.length) return; - if (inside) for (var i = 1, e = !inside(clip[0].point), n = clip.length; i < n; ++i) { - clip[i].entry = e = !e; + for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) { + clip[i].e = entry = !entry; } - var start = subject[0], current, points, point; + var start = subject[0], points, point; while (1) { - current = start; - while (current.visited) if ((current = current.next) === start) return; - points = current.points; + var current = start, isSubject = true; + while (current.v) if ((current = current.n) === start) return; + points = current.z; listener.lineStart(); do { - current.visited = current.other.visited = true; - if (current.entry) { - if (current.subject) { - for (var i = 0; i < points.length; i++) listener.point((point = points[i])[0], point[1]); + 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.point, current.next.point, 1, listener); + interpolate(current.x, current.n.x, 1, listener); } - current = current.next; + current = current.n; } else { - if (current.subject) { - points = current.prev.points; - for (var i = points.length; --i >= 0; ) listener.point((point = points[i])[0], point[1]); + 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.point, current.prev.point, -1, listener); + interpolate(current.x, current.p.x, -1, listener); } - current = current.prev; + current = current.p; } - current = current.other; - points = current.points; - } while (!current.visited); + current = current.o; + points = current.z; + isSubject = !isSubject; + } while (!current.v); listener.lineEnd(); } } @@ -6629,16 +6887,24 @@ d3 = function() { if (!(n = array.length)) return; var n, i = 0, a = array[0], b; while (++i < n) { - a.next = b = array[i]; - b.prev = a; + a.n = b = array[i]; + b.p = a; a = b; } - a.next = b = array[0]; - b.prev = a; + a.n = b = array[0]; + b.p = a; } - function d3_geo_clip(pointVisible, clipLine, interpolate, polygonContains) { - return function(listener) { - var line = clipLine(listener); + 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, @@ -6656,9 +6922,10 @@ d3 = function() { clip.lineStart = lineStart; clip.lineEnd = lineEnd; segments = d3.merge(segments); + var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon); if (segments.length) { - d3_geo_clipPolygon(segments, d3_geo_clipSort, null, interpolate, listener); - } else if (polygonContains(polygon)) { + d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener); + } else if (clipStartInside) { listener.lineStart(); interpolate(null, null, 1, listener); listener.lineEnd(); @@ -6675,10 +6942,12 @@ d3 = function() { } }; function point(λ, φ) { - if (pointVisible(λ, φ)) listener.point(λ, φ); + var point = rotate(λ, φ); + if (pointVisible(λ = point[0], φ = point[1])) listener.point(λ, φ); } function pointLine(λ, φ) { - line.point(λ, φ); + var point = rotate(λ, φ); + line.point(point[0], point[1]); } function lineStart() { clip.point = pointLine; @@ -6691,8 +6960,9 @@ d3 = function() { var segments; var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygon, ring; function pointRing(λ, φ) { - ringListener.point(λ, φ); ring.push([ λ, φ ]); + var point = rotate(λ, φ); + ringListener.point(point[0], point[1]); } function ringStart() { ringListener.lineStart(); @@ -6745,10 +7015,10 @@ d3 = function() { }; } function d3_geo_clipSort(a, b) { - return ((a = a.point)[0] < 0 ? a[1] - π / 2 - ε : π / 2 - a[1]) - ((b = b.point)[0] < 0 ? b[1] - π / 2 - ε : π / 2 - b[1]); + return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]); } function d3_geo_pointInPolygon(point, polygon) { - var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, polar = false, southPole = false, winding = 0; + 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; @@ -6757,28 +7027,26 @@ d3 = function() { 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, antimeridian = Math.abs(dλ) > π, k = sinφ0 * sinφ; + var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, antimeridian = abs(dλ) > π, k = sinφ0 * sinφ; d3_geo_areaRingSum.add(Math.atan2(k * Math.sin(dλ), cosφ0 * cosφ + k * Math.cos(dλ))); - if (Math.abs(φ) < ε) southPole = true; - polarAngle += antimeridian ? dλ + (dλ >= 0 ? 2 : -2) * π : dλ; + polarAngle += antimeridian ? dλ + (dλ >= 0 ? τ : -τ) : 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) { + 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; } - if (Math.abs(polarAngle) > ε) polar = true; } - return (!southPole && !polar && d3_geo_areaRingSum < 0 || polarAngle < -ε) ^ winding & 1; + return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < 0) ^ winding & 1; } - var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, d3_geo_clipAntimeridianPolygonContains); + 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 { @@ -6787,9 +7055,9 @@ d3 = function() { clean = 1; }, point: function(λ1, φ1) { - var sλ1 = λ1 > 0 ? π : -π, dλ = Math.abs(λ1 - λ0); - if (Math.abs(dλ - π) < ε) { - listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? π / 2 : -π / 2); + 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(); @@ -6797,8 +7065,8 @@ d3 = function() { listener.point(λ1, φ0); clean = 0; } else if (sλ0 !== sλ1 && dλ >= π) { - if (Math.abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε; - if (Math.abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε; + 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(); @@ -6820,12 +7088,12 @@ d3 = function() { } function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) { var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1); - return Math.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; + 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 * π / 2; + φ = direction * halfπ; listener.point(-π, φ); listener.point(0, φ); listener.point(π, φ); @@ -6835,8 +7103,8 @@ d3 = function() { listener.point(-π, -φ); listener.point(-π, 0); listener.point(-π, φ); - } else if (Math.abs(from[0] - to[0]) > ε) { - var s = (from[0] < to[0] ? 1 : -1) * π; + } else if (abs(from[0] - to[0]) > ε) { + var s = from[0] < to[0] ? π : -π; φ = direction * s / 2; listener.point(-s, φ); listener.point(0, φ); @@ -6845,13 +7113,9 @@ d3 = function() { listener.point(to[0], to[1]); } } - var d3_geo_clipAntimeridianPoint = [ -π, 0 ]; - function d3_geo_clipAntimeridianPolygonContains(polygon) { - return d3_geo_pointInPolygon(d3_geo_clipAntimeridianPoint, polygon); - } function d3_geo_clipCircle(radius) { - var cr = Math.cos(radius), smallRadius = cr > 0, point = [ radius, 0 ], notHemisphere = Math.abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians); - return d3_geo_clip(visible, clipLine, interpolate, polygonContains); + 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; } @@ -6930,9 +7194,9 @@ d3 = function() { 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 = Math.abs(δλ - π) < ε, meridian = polar || δλ < ε; + 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] < (Math.abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) { + 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) ]; @@ -6944,14 +7208,82 @@ d3 = function() { if (φ < -r) code |= 4; else if (φ > r) code |= 8; return code; } - function polygonContains(polygon) { - return d3_geo_pointInPolygon(point, polygon); - } } - var d3_geo_clipViewMAX = 1e9; - function d3_geo_clipView(x0, y0, x1, y1) { + 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(), segments, polygon, ring; + var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring; var clip = { point: point, lineStart: lineStart, @@ -6960,25 +7292,27 @@ d3 = function() { listener = bufferListener; segments = []; polygon = []; + clean = true; }, polygonEnd: function() { listener = listener_; - if ((segments = d3.merge(segments)).length) { + segments = d3.merge(segments); + var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length; + if (inside || visible) { listener.polygonStart(); - d3_geo_clipPolygon(segments, compare, inside, interpolate, listener); + if (inside) { + listener.lineStart(); + interpolate(null, null, 1, listener); + listener.lineEnd(); + } + if (visible) { + d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener); + } listener.polygonEnd(); - } else if (insidePolygon([ x0, y0 ])) { - listener.polygonStart(), listener.lineStart(); - interpolate(null, null, 1, listener); - listener.lineEnd(), listener.polygonEnd(); } segments = polygon = ring = null; } }; - function inside(point) { - var a = corner(point, -1), i = insidePolygon([ a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0 ]); - return i; - } function insidePolygon(p) { var wn = 0, n = polygon.length, y = p[1]; for (var i = 0; i < n; ++i) { @@ -7007,13 +7341,13 @@ d3 = function() { listener.point(to[0], to[1]); } } - function visible(x, y) { + function pointVisible(x, y) { return x0 <= x && x <= x1 && y0 <= y && y <= y1; } function point(x, y) { - if (visible(x, y)) listener.point(x, y); + if (pointVisible(x, y)) listener.point(x, y); } - var x__, y__, v__, x_, y_, v_, first; + var x__, y__, v__, x_, y_, v_, first, clean; function lineStart() { clip.point = linePoint; if (polygon) polygon.push(ring = []); @@ -7031,9 +7365,9 @@ d3 = function() { if (v_) listener.lineEnd(); } function linePoint(x, y) { - x = Math.max(-d3_geo_clipViewMAX, Math.min(d3_geo_clipViewMAX, x)); - y = Math.max(-d3_geo_clipViewMAX, Math.min(d3_geo_clipViewMAX, y)); - var v = visible(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; @@ -7044,17 +7378,28 @@ d3 = function() { } } else { if (v && v_) listener.point(x, y); else { - var a = [ x_, y_ ], b = [ x, y ]; - if (clipLine(a, b)) { + var l = { + a: { + x: x_, + y: y_ + }, + b: { + x: x, + y: y + } + }; + if (clipLine(l)) { if (!v_) { listener.lineStart(); - listener.point(a[0], a[1]); + listener.point(l.a.x, l.a.y); } - listener.point(b[0], b[1]); + 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; } } } @@ -7063,43 +7408,15 @@ d3 = function() { return clip; }; function corner(p, direction) { - return Math.abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : Math.abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : Math.abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2; + 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.point, b.point); + 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 clipLine(a, b) { - var dx = b[0] - a[0], dy = b[1] - a[1], t = [ 0, 1 ]; - if (Math.abs(dx) < ε && Math.abs(dy) < ε) return x0 <= a[0] && a[0] <= x1 && y0 <= a[1] && a[1] <= y1; - if (d3_geo_clipViewT(x0 - a[0], dx, t) && d3_geo_clipViewT(a[0] - x1, -dx, t) && d3_geo_clipViewT(y0 - a[1], dy, t) && d3_geo_clipViewT(a[1] - y1, -dy, t)) { - if (t[1] < 1) { - b[0] = a[0] + t[1] * dx; - b[1] = a[1] + t[1] * dy; - } - if (t[0] > 0) { - a[0] += t[0] * dx; - a[1] += t[0] * dy; - } - return true; - } - return false; - } - } - function d3_geo_clipViewT(num, denominator, t) { - if (Math.abs(denominator) < ε) return num <= 0; - var u = num / denominator; - if (denominator > 0) { - if (u > t[1]) return false; - if (u > t[0]) t[0] = u; - } else { - if (u < t[0]) return false; - if (u < t[1]) t[1] = u; - } - return true; } function d3_geo_compose(a, b) { function compose(x, y) { @@ -7224,7 +7541,7 @@ d3 = function() { }, polygonEnd: function() { d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop; - d3_geo_pathAreaSum += Math.abs(d3_geo_pathAreaPolygon / 2); + d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2); } }; function d3_geo_pathAreaRingStart() { @@ -7382,7 +7699,7 @@ d3 = function() { }; function point(x, y) { context.moveTo(x, y); - context.arc(x, y, pointRadius, 0, 2 * π); + context.arc(x, y, pointRadius, 0, τ); } function pointLineStart(x, y) { context.moveTo(x, y); @@ -7402,6 +7719,15 @@ d3 = function() { 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, @@ -7453,8 +7779,8 @@ d3 = function() { 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 = Math.abs(Math.abs(c) - 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 || Math.abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { + 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); @@ -7516,46 +7842,78 @@ d3 = function() { return path.projection(d3.geo.albersUsa()).context(null); }; function d3_geo_pathProjectStream(project) { - var resample = d3_geo_resample(function(λ, φ) { - return project([ λ * d3_degrees, φ * d3_degrees ]); + var resample = d3_geo_resample(function(x, y) { + return project([ x * d3_degrees, y * d3_degrees ]); }); return function(stream) { - stream = resample(stream); - return { - point: function(λ, φ) { - stream.point(λ * d3_radians, φ * d3_radians); - }, - sphere: function() { - stream.sphere(); - }, - lineStart: function() { - stream.lineStart(); - }, - lineEnd: function() { - stream.lineEnd(); - }, - polygonStart: function() { - stream.polygonStart(); - }, - polygonEnd: function() { - stream.polygonEnd(); - } - }; + return d3_geo_projectionRadians(resample(stream)); }; } - d3.geo.projection = d3_geo_projection; - d3.geo.projectionMutator = d3_geo_projectionMutator; - function d3_geo_projection(project) { - return d3_geo_projectionMutator(function() { - return project; - })(); + 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; } - 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) { + 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 ]; } @@ -7565,7 +7923,7 @@ d3 = function() { } projection.stream = function(output) { if (stream) stream.valid = false; - stream = d3_geo_projectionRadiansRotate(rotate, preclip(projectResample(postclip(output)))); + stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output)))); stream.valid = true; return stream; }; @@ -7577,7 +7935,7 @@ d3 = function() { projection.clipExtent = function(_) { if (!arguments.length) return clipExtent; clipExtent = _; - postclip = _ == null ? d3_identity : d3_geo_clipView(_[0][0], _[0][1], _[1][0], _[1][1]); + postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity; return invalidate(); }; projection.scale = function(_) { @@ -7613,10 +7971,7 @@ d3 = function() { return invalidate(); } function invalidate() { - if (stream) { - stream.valid = false; - stream = null; - } + if (stream) stream.valid = false, stream = null; return projection; } return function() { @@ -7625,28 +7980,10 @@ d3 = function() { return reset(); }; } - function d3_geo_projectionRadiansRotate(rotate, stream) { - return { - point: function(x, y) { - y = rotate(x * d3_radians, y * d3_radians), x = y[0]; - stream.point(x > π ? x - 2 * π : x < -π ? x + 2 * π : x, y[1]); - }, - sphere: function() { - stream.sphere(); - }, - lineStart: function() { - stream.lineStart(); - }, - lineEnd: function() { - stream.lineEnd(); - }, - polygonStart: function() { - stream.polygonStart(); - }, - polygonEnd: function() { - stream.polygonEnd(); - } - }; + 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 [ λ, φ ]; @@ -7666,12 +8003,16 @@ d3 = function() { }; 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_equirectangular; + 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 λ += δλ, [ λ > π ? λ - 2 * π : λ < -π ? λ + 2 * π : λ, φ ]; + return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; }; } function d3_geo_rotationλ(δλ) { @@ -7726,16 +8067,16 @@ d3 = function() { 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 * 2 * π; + if (direction > 0 ? from < to : from > to) from += direction * τ; } else { - from = radius + direction * 2 * π; - to = radius; + from = radius + direction * τ; + to = radius - .5 * step; } - var point; - for (var step = direction * precision, t = from; direction > 0 ? t > to : t < to; t -= 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]); } }; @@ -7761,9 +8102,9 @@ d3 = function() { } 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 Math.abs(x % DX) > ε; + return abs(x % DX) > ε; }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) { - return Math.abs(y % DY) > ε; + return abs(y % DY) > ε; }).map(y)); } graticule.lines = function() { @@ -7911,7 +8252,7 @@ d3 = function() { d3_geo_length.point = d3_geo_length.lineEnd = d3_noop; }; function nextPoint(λ, φ) { - var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = Math.abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t); + 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φ; } @@ -7948,12 +8289,12 @@ d3 = function() { }, 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(λ, φ) { - var ρ = Math.abs(Math.abs(φ) - π / 2) < ε ? 0 : F / Math.pow(t(φ), n); + var ρ = abs(abs(φ) - halfπ) < ε ? 0 : 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)) - π / 2 ]; + return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ]; }; return forward; } @@ -7962,7 +8303,7 @@ d3 = function() { }).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 (Math.abs(n) < ε) return d3_geo_equirectangular; + if (abs(n) < ε) return d3_geo_equirectangular; function forward(λ, φ) { var ρ = G - φ; return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ]; @@ -7986,7 +8327,7 @@ d3 = function() { return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ]; } d3_geo_mercator.invert = function(x, y) { - return [ x, 2 * Math.atan(Math.exp(y)) - π / 2 ]; + 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; @@ -8030,840 +8371,827 @@ d3 = function() { return d3_geo_projection(d3_geo_stereographic); }).raw = d3_geo_stereographic; function d3_geo_transverseMercator(λ, φ) { - var B = Math.cos(φ) * Math.sin(λ); - return [ Math.log((1 + B) / (1 - B)) / 2, Math.atan2(Math.tan(φ), Math.cos(λ)) ]; + return [ Math.log(Math.tan(π / 4 + φ / 2)), -λ ]; } d3_geo_transverseMercator.invert = function(x, y) { - return [ Math.atan2(d3_sinh(x), Math.cos(y)), d3_asin(Math.sin(y) / d3_cosh(x)) ]; + return [ -y, 2 * Math.atan(Math.exp(x)) - halfπ ]; }; (d3.geo.transverseMercator = function() { - return d3_geo_mercatorProjection(d3_geo_transverseMercator); + 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 projection.rotate([ 0, 0 ]); }).raw = d3_geo_transverseMercator; d3.geom = {}; - d3.svg = {}; - function d3_svg_line(projection) { - var x = d3_svg_lineX, y = d3_svg_lineY, 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)); + 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), n = data.length, vertices, plen = n - 1, points = [], stack = [], d, i, j, h = 0, x1, y1, x2, y2, u, v, a, sp; + if (fx === d3_geom_pointX && y === d3_geom_pointY) vertices = data; else for (i = 0, + vertices = []; i < n; ++i) { + vertices.push([ +fx.call(this, d = data[i], i), +fy.call(this, d, i) ]); } - 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 = []; + for (i = 1; i < n; ++i) { + if (vertices[i][1] < vertices[h][1] || vertices[i][1] == vertices[h][1] && vertices[i][0] < vertices[h][0]) h = i; + } + for (i = 0; i < n; ++i) { + if (i === h) continue; + y1 = vertices[i][1] - vertices[h][1]; + x1 = vertices[i][0] - vertices[h][0]; + points.push({ + angle: Math.atan2(y1, x1), + index: i + }); + } + points.sort(function(a, b) { + return a.angle - b.angle; + }); + a = points[0].angle; + v = points[0].index; + u = 0; + for (i = 1; i < plen; ++i) { + j = points[i].index; + if (a == points[i].angle) { + x1 = vertices[v][0] - vertices[h][0]; + y1 = vertices[v][1] - vertices[h][1]; + x2 = vertices[j][0] - vertices[h][0]; + y2 = vertices[j][1] - vertices[h][1]; + if (x1 * x1 + y1 * y1 >= x2 * x2 + y2 * y2) { + points[i].index = -1; + continue; + } else { + points[u].index = -1; + } } + a = points[i].angle; + u = i; + v = j; } - if (points.length) segment(); - return segments.length ? segments.join("") : null; + stack.push(h); + for (i = 0, j = 0; i < 2; ++j) { + if (points[j].index > -1) { + stack.push(points[j].index); + i++; + } + } + sp = stack.length; + for (;j < plen; ++j) { + if (points[j].index < 0) continue; + while (!d3_geom_hullCCW(stack[sp - 2], stack[sp - 1], points[j].index, vertices)) { + --sp; + } + stack[sp++] = points[j].index; + } + var poly = []; + for (i = sp - 1; i >= 0; --i) poly.push(data[stack[i]]); + return poly; } - 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; + hull.x = function(_) { + return arguments.length ? (x = _, hull) : x; }; - line.tension = function(_) { - if (!arguments.length) return tension; - tension = _; - return line; + hull.y = function(_) { + return arguments.length ? (y = _, hull) : y; }; - return line; + return hull; + }; + function d3_geom_hullCCW(i1, i2, i3, v) { + var t, a, b, c, d, e, f; + t = v[i1]; + a = t[0]; + b = t[1]; + t = v[i2]; + c = t[0]; + d = t[1]; + t = v[i3]; + e = t[0]; + f = t[1]; + return (f - b) * (c - a) - (d - b) * (e - a) > 0; } - d3.svg.line = function() { - return d3_svg_line(d3_identity); + d3.geom.polygon = function(coordinates) { + d3_subclass(coordinates, d3_geom_polygonPrototype); + return coordinates; }; - function d3_svg_lineX(d) { - return d[0]; + 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_svg_lineY(d) { - return d[1]; + 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 ]; } - var d3_svg_lineInterpolators = d3.map({ - linear: d3_svg_lineLinear, - "linear-closed": d3_svg_lineLinearClosed, - step: d3_svg_lineStep, - "step-before": d3_svg_lineStepBefore, - "step-after": d3_svg_lineStepAfter, - basis: d3_svg_lineBasis, - "basis-open": d3_svg_lineBasisOpen, - "basis-closed": d3_svg_lineBasisClosed, - bundle: d3_svg_lineBundle, - cardinal: d3_svg_lineCardinal, - "cardinal-open": d3_svg_lineCardinalOpen, - "cardinal-closed": d3_svg_lineCardinalClosed, - monotone: d3_svg_lineMonotone - }); - d3_svg_lineInterpolators.forEach(function(key, value) { - value.key = key; - value.closed = /-closed$/.test(key); - }); - function d3_svg_lineLinear(points) { - return points.join("L"); - } - function d3_svg_lineLinearClosed(points) { - return d3_svg_lineLinear(points) + "Z"; - } - function d3_svg_lineStep(points) { - var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; - while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]); - if (n > 1) path.push("H", p[0]); - return path.join(""); - } - function d3_svg_lineStepBefore(points) { - var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; - while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]); - return path.join(""); - } - function d3_svg_lineStepAfter(points) { - var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; - while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]); - return path.join(""); + function d3_geom_polygonClosed(coordinates) { + var a = coordinates[0], b = coordinates[coordinates.length - 1]; + return !(a[0] - b[0] || a[1] - b[1]); } - function d3_svg_lineCardinalOpen(points, tension) { - return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, points.length - 1), d3_svg_lineCardinalTangents(points, tension)); + 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_svg_lineCardinalClosed(points, tension) { - return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), - points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension)); + function d3_geom_voronoiCreateBeach(site) { + var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach(); + beach.site = site; + return beach; } - 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_geom_voronoiDetachBeach(beach) { + d3_geom_voronoiDetachCircle(beach); + d3_geom_voronoiBeaches.remove(beach); + d3_geom_voronoiBeachPool.push(beach); + d3_geom_voronoiRedBlackNode(beach); } - function d3_svg_lineHermite(points, tangents) { - if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) { - return d3_svg_lineLinear(points); + 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 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; + 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 (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 (!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; + } } } - if (quad) { - var lp = points[pi]; - path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1]; + 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 + }; + } + } } - return path; + edge.a = va; + edge.b = vb; + return true; } - 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]) ]); + 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; } - 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_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); } - 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]); + 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; } - 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); + }; + 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; } - return path.join(""); + q.U = parent; + p.U = q; + p.L = q.R; + if (p.L) p.L.U = p; + q.R = p; } - 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_geom_voronoiRedBlackFirst(node) { + while (node.L) node = node.L; + return node; } - 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); + 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; } } - 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]); + 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_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_geom_voronoiVertexOrder(a, b) { + return b.y - a.y || b.x - a.x; } - 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 (Math.abs(d) < 1e-6) { - 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; - } - } + 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; } - 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 ]); + function sites(data) { + return data.map(function(d, i) { + return { + x: Math.round(fx(d, i) / ε) * ε, + y: Math.round(fy(d, i) / ε) * ε, + i: i + }; + }); } - 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.geom.hull = function(vertices) { - var x = d3_svg_lineX, y = d3_svg_lineY; - if (arguments.length) return hull(vertices); - function hull(data) { - if (data.length < 3) return []; - var fx = d3_functor(x), fy = d3_functor(y), n = data.length, vertices, plen = n - 1, points = [], stack = [], d, i, j, h = 0, x1, y1, x2, y2, u, v, a, sp; - if (fx === d3_svg_lineX && y === d3_svg_lineY) vertices = data; else for (i = 0, - vertices = []; i < n; ++i) { - vertices.push([ +fx.call(this, d = data[i], i), +fy.call(this, d, i) ]); - } - for (i = 1; i < n; ++i) { - if (vertices[i][1] < vertices[h][1] || vertices[i][1] == vertices[h][1] && vertices[i][0] < vertices[h][0]) h = i; - } - for (i = 0; i < n; ++i) { - if (i === h) continue; - y1 = vertices[i][1] - vertices[h][1]; - x1 = vertices[i][0] - vertices[h][0]; - points.push({ - angle: Math.atan2(y1, x1), - index: i - }); - } - points.sort(function(a, b) { - return a.angle - b.angle; + 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] + }; }); - a = points[0].angle; - v = points[0].index; - u = 0; - for (i = 1; i < plen; ++i) { - j = points[i].index; - if (a == points[i].angle) { - x1 = vertices[v][0] - vertices[h][0]; - y1 = vertices[v][1] - vertices[h][1]; - x2 = vertices[j][0] - vertices[h][0]; - y2 = vertices[j][1] - vertices[h][1]; - if (x1 * x1 + y1 * y1 >= x2 * x2 + y2 * y2) { - points[i].index = -1; - continue; - } else { - points[u].index = -1; - } - } - a = points[i].angle; - u = i; - v = j; - } - stack.push(h); - for (i = 0, j = 0; i < 2; ++j) { - if (points[j].index > -1) { - stack.push(points[j].index); - i++; - } - } - sp = stack.length; - for (;j < plen; ++j) { - if (points[j].index < 0) continue; - while (!d3_geom_hullCCW(stack[sp - 2], stack[sp - 1], points[j].index, vertices)) { - --sp; - } - stack[sp++] = points[j].index; - } - var poly = []; - for (i = sp - 1; i >= 0; --i) poly.push(data[stack[i]]); - return poly; - } - hull.x = function(_) { - return arguments.length ? (x = _, hull) : x; - }; - hull.y = function(_) { - return arguments.length ? (y = _, hull) : y; }; - return hull; - }; - function d3_geom_hullCCW(i1, i2, i3, v) { - var t, a, b, c, d, e, f; - t = v[i1]; - a = t[0]; - b = t[1]; - t = v[i2]; - c = t[0]; - d = t[1]; - t = v[i3]; - e = t[0]; - f = t[1]; - return (f - b) * (c - a) - (d - b) * (e - a) > 0; - } - 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]); - } - d3.geom.delaunay = function(vertices) { - var edges = vertices.map(function() { - return []; - }), triangles = []; - d3_geom_voronoiTessellate(vertices, function(e) { - edges[e.region.l.index].push(vertices[e.region.r.index]); - }); - edges.forEach(function(edge, i) { - var v = vertices[i], cx = v[0], cy = v[1]; - edge.forEach(function(v) { - v.angle = Math.atan2(v[0] - cx, v[1] - cy); - }); - edge.sort(function(a, b) { - return a.angle - b.angle; - }); - for (var j = 0, m = edge.length - 1; j < m; j++) { - triangles.push([ v, edge[j], edge[j + 1] ]); - } - }); - return triangles; - }; - d3.geom.voronoi = function(points) { - var x = d3_svg_lineX, y = d3_svg_lineY, clipPolygon = null; - if (arguments.length) return voronoi(points); - function voronoi(data) { - var points, polygons = data.map(function() { - return []; - }), fx = d3_functor(x), fy = d3_functor(y), d, i, n = data.length, Z = 1e6; - if (fx === d3_svg_lineX && fy === d3_svg_lineY) points = data; else for (points = new Array(n), - i = 0; i < n; ++i) { - points[i] = [ +fx.call(this, d = data[i], i), +fy.call(this, d, i) ]; - } - d3_geom_voronoiTessellate(points, function(e) { - var s1, s2, x1, x2, y1, y2; - if (e.a === 1 && e.b >= 0) { - s1 = e.ep.r; - s2 = e.ep.l; - } else { - s1 = e.ep.l; - s2 = e.ep.r; - } - if (e.a === 1) { - y1 = s1 ? s1.y : -Z; - x1 = e.c - e.b * y1; - y2 = s2 ? s2.y : Z; - x2 = e.c - e.b * y2; - } else { - x1 = s1 ? s1.x : -Z; - y1 = e.c - e.a * x1; - x2 = s2 ? s2.x : Z; - y2 = e.c - e.a * x2; - } - var v1 = [ x1, y1 ], v2 = [ x2, y2 ]; - polygons[e.region.l.index].push(v1, v2); - polygons[e.region.r.index].push(v1, v2); - }); - polygons = polygons.map(function(polygon, i) { - var cx = points[i][0], cy = points[i][1], angle = polygon.map(function(v) { - return Math.atan2(v[0] - cx, v[1] - cy); - }), order = d3.range(polygon.length).sort(function(a, b) { - return angle[a] - angle[b]; - }); - return order.filter(function(d, i) { - return !i || angle[d] - angle[order[i - 1]] > ε; - }).map(function(d) { - return polygon[d]; - }); - }); - polygons.forEach(function(polygon, i) { - var n = polygon.length; - if (!n) return polygon.push([ -Z, -Z ], [ -Z, Z ], [ Z, Z ], [ Z, -Z ]); - if (n > 2) return; - var p0 = points[i], p1 = polygon[0], p2 = polygon[1], x0 = p0[0], y0 = p0[1], x1 = p1[0], y1 = p1[1], x2 = p2[0], y2 = p2[1], dx = Math.abs(x2 - x1), dy = y2 - y1; - if (Math.abs(dy) < ε) { - var y = y0 < y1 ? -Z : Z; - polygon.push([ -Z, y ], [ Z, y ]); - } else if (dx < ε) { - var x = x0 < x1 ? -Z : Z; - polygon.push([ x, -Z ], [ x, Z ]); - } else { - var y = (x2 - x1) * (y1 - y0) < (x1 - x0) * (y2 - y1) ? Z : -Z, z = Math.abs(dy) - dx; - if (Math.abs(z) < ε) { - polygon.push([ dy < 0 ? y : -y, y ]); - } else { - if (z > 0) y *= -1; - polygon.push([ -Z, y ], [ Z, y ]); + 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] ]); } } }); - if (clipPolygon) for (i = 0; i < n; ++i) clipPolygon.clip(polygons[i]); - for (i = 0; i < n; ++i) polygons[i].point = data[i]; - return polygons; - } + return triangles; + }; voronoi.x = function(_) { - return arguments.length ? (x = _, voronoi) : x; + return arguments.length ? (fx = d3_functor(x = _), voronoi) : x; }; voronoi.y = function(_) { - return arguments.length ? (y = _, voronoi) : y; + return arguments.length ? (fy = d3_functor(y = _), voronoi) : y; }; voronoi.clipExtent = function(_) { - if (!arguments.length) return clipPolygon && [ clipPolygon[0], clipPolygon[2] ]; - if (_ == null) clipPolygon = null; else { - var x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], y2 = +_[1][1]; - clipPolygon = d3.geom.polygon([ [ x1, y1 ], [ x1, y2 ], [ x2, y2 ], [ x2, y1 ] ]); - } + if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent; + clipExtent = _ == null ? d3_geom_voronoiClipExtent : _; return voronoi; }; voronoi.size = function(_) { - if (!arguments.length) return clipPolygon && clipPolygon[2]; + if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1]; return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]); }; - voronoi.links = function(data) { - var points, graph = data.map(function() { - return []; - }), links = [], fx = d3_functor(x), fy = d3_functor(y), d, i, n = data.length; - if (fx === d3_svg_lineX && fy === d3_svg_lineY) points = data; else for (points = new Array(n), - i = 0; i < n; ++i) { - points[i] = [ +fx.call(this, d = data[i], i), +fy.call(this, d, i) ]; - } - d3_geom_voronoiTessellate(points, function(e) { - var l = e.region.l.index, r = e.region.r.index; - if (graph[l][r]) return; - graph[l][r] = graph[r][l] = true; - links.push({ - source: data[l], - target: data[r] - }); - }); - return links; - }; - voronoi.triangles = function(data) { - if (x === d3_svg_lineX && y === d3_svg_lineY) return d3.geom.delaunay(data); - var points = new Array(n), fx = d3_functor(x), fy = d3_functor(y), d, i = -1, n = data.length; - while (++i < n) { - (points[i] = [ +fx.call(this, d = data[i], i), +fy.call(this, d, i) ]).data = d; - } - return d3.geom.delaunay(points).map(function(triangle) { - return triangle.map(function(point) { - return point.data; - }); - }); - }; return voronoi; }; - var d3_geom_voronoiOpposite = { - l: "r", - r: "l" - }; - function d3_geom_voronoiTessellate(points, callback) { - var Sites = { - list: points.map(function(v, i) { - return { - index: i, - x: v[0], - y: v[1] - }; - }).sort(function(a, b) { - return a.y < b.y ? -1 : a.y > b.y ? 1 : a.x < b.x ? -1 : a.x > b.x ? 1 : 0; - }), - bottomSite: null - }; - var EdgeList = { - list: [], - leftEnd: null, - rightEnd: null, - init: function() { - EdgeList.leftEnd = EdgeList.createHalfEdge(null, "l"); - EdgeList.rightEnd = EdgeList.createHalfEdge(null, "l"); - EdgeList.leftEnd.r = EdgeList.rightEnd; - EdgeList.rightEnd.l = EdgeList.leftEnd; - EdgeList.list.unshift(EdgeList.leftEnd, EdgeList.rightEnd); - }, - createHalfEdge: function(edge, side) { - return { - edge: edge, - side: side, - vertex: null, - l: null, - r: null - }; - }, - insert: function(lb, he) { - he.l = lb; - he.r = lb.r; - lb.r.l = he; - lb.r = he; - }, - leftBound: function(p) { - var he = EdgeList.leftEnd; - do { - he = he.r; - } while (he != EdgeList.rightEnd && Geom.rightOf(he, p)); - he = he.l; - return he; - }, - del: function(he) { - he.l.r = he.r; - he.r.l = he.l; - he.edge = null; - }, - right: function(he) { - return he.r; - }, - left: function(he) { - return he.l; - }, - leftRegion: function(he) { - return he.edge == null ? Sites.bottomSite : he.edge.region[he.side]; - }, - rightRegion: function(he) { - return he.edge == null ? Sites.bottomSite : he.edge.region[d3_geom_voronoiOpposite[he.side]]; - } - }; - var Geom = { - bisect: function(s1, s2) { - var newEdge = { - region: { - l: s1, - r: s2 - }, - ep: { - l: null, - r: null - } - }; - var dx = s2.x - s1.x, dy = s2.y - s1.y, adx = dx > 0 ? dx : -dx, ady = dy > 0 ? dy : -dy; - newEdge.c = s1.x * dx + s1.y * dy + (dx * dx + dy * dy) * .5; - if (adx > ady) { - newEdge.a = 1; - newEdge.b = dy / dx; - newEdge.c /= dx; - } else { - newEdge.b = 1; - newEdge.a = dx / dy; - newEdge.c /= dy; - } - return newEdge; - }, - intersect: function(el1, el2) { - var e1 = el1.edge, e2 = el2.edge; - if (!e1 || !e2 || e1.region.r == e2.region.r) { - return null; - } - var d = e1.a * e2.b - e1.b * e2.a; - if (Math.abs(d) < 1e-10) { - return null; - } - var xint = (e1.c * e2.b - e2.c * e1.b) / d, yint = (e2.c * e1.a - e1.c * e2.a) / d, e1r = e1.region.r, e2r = e2.region.r, el, e; - if (e1r.y < e2r.y || e1r.y == e2r.y && e1r.x < e2r.x) { - el = el1; - e = e1; - } else { - el = el2; - e = e2; - } - var rightOfSite = xint >= e.region.r.x; - if (rightOfSite && el.side === "l" || !rightOfSite && el.side === "r") { - return null; - } - return { - x: xint, - y: yint - }; - }, - rightOf: function(he, p) { - var e = he.edge, topsite = e.region.r, rightOfSite = p.x > topsite.x; - if (rightOfSite && he.side === "l") { - return 1; - } - if (!rightOfSite && he.side === "r") { - return 0; - } - if (e.a === 1) { - var dyp = p.y - topsite.y, dxp = p.x - topsite.x, fast = 0, above = 0; - if (!rightOfSite && e.b < 0 || rightOfSite && e.b >= 0) { - above = fast = dyp >= e.b * dxp; - } else { - above = p.x + p.y * e.b > e.c; - if (e.b < 0) { - above = !above; - } - if (!above) { - fast = 1; - } - } - if (!fast) { - var dxs = topsite.x - e.region.l.x; - above = e.b * (dxp * dxp - dyp * dyp) < dxs * dyp * (1 + 2 * dxp / dxs + e.b * e.b); - if (e.b < 0) { - above = !above; - } - } - } else { - var yl = e.c - e.a * p.x, t1 = p.y - yl, t2 = p.x - topsite.x, t3 = yl - topsite.y; - above = t1 * t1 > t2 * t2 + t3 * t3; - } - return he.side === "l" ? above : !above; - }, - endPoint: function(edge, side, site) { - edge.ep[side] = site; - if (!edge.ep[d3_geom_voronoiOpposite[side]]) return; - callback(edge); - }, - distance: function(s, t) { - var dx = s.x - t.x, dy = s.y - t.y; - return Math.sqrt(dx * dx + dy * dy); - } - }; - var EventQueue = { - list: [], - insert: function(he, site, offset) { - he.vertex = site; - he.ystar = site.y + offset; - for (var i = 0, list = EventQueue.list, l = list.length; i < l; i++) { - var next = list[i]; - if (he.ystar > next.ystar || he.ystar == next.ystar && site.x > next.vertex.x) { - continue; - } else { - break; - } - } - list.splice(i, 0, he); - }, - del: function(he) { - for (var i = 0, ls = EventQueue.list, l = ls.length; i < l && ls[i] != he; ++i) {} - ls.splice(i, 1); - }, - empty: function() { - return EventQueue.list.length === 0; - }, - nextEvent: function(he) { - for (var i = 0, ls = EventQueue.list, l = ls.length; i < l; ++i) { - if (ls[i] == he) return ls[i + 1]; - } - return null; - }, - min: function() { - var elem = EventQueue.list[0]; - return { - x: elem.vertex.x, - y: elem.ystar - }; - }, - extractMin: function() { - return EventQueue.list.shift(); - } - }; - EdgeList.init(); - Sites.bottomSite = Sites.list.shift(); - var newSite = Sites.list.shift(), newIntStar; - var lbnd, rbnd, llbnd, rrbnd, bisector; - var bot, top, temp, p, v; - var e, pm; - while (true) { - if (!EventQueue.empty()) { - newIntStar = EventQueue.min(); - } - if (newSite && (EventQueue.empty() || newSite.y < newIntStar.y || newSite.y == newIntStar.y && newSite.x < newIntStar.x)) { - lbnd = EdgeList.leftBound(newSite); - rbnd = EdgeList.right(lbnd); - bot = EdgeList.rightRegion(lbnd); - e = Geom.bisect(bot, newSite); - bisector = EdgeList.createHalfEdge(e, "l"); - EdgeList.insert(lbnd, bisector); - p = Geom.intersect(lbnd, bisector); - if (p) { - EventQueue.del(lbnd); - EventQueue.insert(lbnd, p, Geom.distance(p, newSite)); - } - lbnd = bisector; - bisector = EdgeList.createHalfEdge(e, "r"); - EdgeList.insert(lbnd, bisector); - p = Geom.intersect(bisector, rbnd); - if (p) { - EventQueue.insert(bisector, p, Geom.distance(p, newSite)); - } - newSite = Sites.list.shift(); - } else if (!EventQueue.empty()) { - lbnd = EventQueue.extractMin(); - llbnd = EdgeList.left(lbnd); - rbnd = EdgeList.right(lbnd); - rrbnd = EdgeList.right(rbnd); - bot = EdgeList.leftRegion(lbnd); - top = EdgeList.rightRegion(rbnd); - v = lbnd.vertex; - Geom.endPoint(lbnd.edge, lbnd.side, v); - Geom.endPoint(rbnd.edge, rbnd.side, v); - EdgeList.del(lbnd); - EventQueue.del(rbnd); - EdgeList.del(rbnd); - pm = "l"; - if (bot.y > top.y) { - temp = bot; - bot = top; - top = temp; - pm = "r"; - } - e = Geom.bisect(bot, top); - bisector = EdgeList.createHalfEdge(e, pm); - EdgeList.insert(llbnd, bisector); - Geom.endPoint(e, d3_geom_voronoiOpposite[pm], v); - p = Geom.intersect(llbnd, bisector); - if (p) { - EventQueue.del(llbnd); - EventQueue.insert(llbnd, p, Geom.distance(p, bot)); - } - p = Geom.intersect(bisector, rrbnd); - if (p) { - EventQueue.insert(bisector, p, Geom.distance(p, bot)); - } - } else { - break; - } - } - for (lbnd = EdgeList.right(EdgeList.leftEnd); lbnd != EdgeList.rightEnd; lbnd = EdgeList.right(lbnd)) { - callback(lbnd.edge); - } + 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_svg_lineX, y = d3_svg_lineY, compat; + var x = d3_geom_pointX, y = d3_geom_pointY, compat; if (compat = arguments.length) { x = d3_geom_quadtreeCompatX; y = d3_geom_quadtreeCompatY; @@ -8907,7 +9235,7 @@ d3 = function() { if (n.leaf) { var nx = n.x, ny = n.y; if (nx != null) { - if (Math.abs(nx - x) + Math.abs(ny - y) < .01) { + if (abs(nx - x) + abs(ny - y) < .01) { insertChild(n, d, x, y, x1, y1, x2, y2); } else { var nPoint = n.point; @@ -9153,7 +9481,7 @@ d3 = function() { var i = name.indexOf("-"), t = i >= 0 ? name.substring(0, i) : name, m = i >= 0 ? name.substring(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, Array.prototype.slice.call(arguments, 1)))); + return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1)))); }; function d3_ease_clamp(f) { return function(t) { @@ -9188,7 +9516,7 @@ d3 = function() { }; } function d3_ease_sin(t) { - return 1 - Math.cos(t * π / 2); + return 1 - Math.cos(t * halfπ); } function d3_ease_exp(t) { return Math.pow(2, 10 * (t - 1)); @@ -9199,9 +9527,9 @@ d3 = function() { function d3_ease_elastic(a, p) { var s; if (arguments.length < 2) p = .45; - if (arguments.length) s = p / (2 * π) * Math.asin(1 / a); else a = 1, s = p / 4; + 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) * 2 * π / p); + return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p); }; } function d3_ease_back(s) { @@ -9435,7 +9763,7 @@ d3 = function() { }); }); } - k = (2 * π - padding * n) / k; + k = (τ - padding * n) / k; x = 0, i = -1; while (++i < n) { x0 = x, j = -1; @@ -9662,7 +9990,7 @@ d3 = function() { return force; }; force.start = function() { - var i, j, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o; + 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; @@ -9688,13 +10016,8 @@ d3 = function() { 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) { - var neighbors = neighbor(i), j = -1, m = neighbors.length, x; - while (++j < m) if (!isNaN(x = neighbors[j][dimension])) return x; - return Math.random() * size; - } - function neighbor() { if (!neighbors) { - neighbors = []; + neighbors = new Array(n); for (j = 0; j < n; ++j) { neighbors[j] = []; } @@ -9704,7 +10027,9 @@ d3 = function() { neighbors[o.target.index].push(o.source); } } - return neighbors[i]; + var candidates = neighbors[i], j = -1, m = candidates.length, x; + while (++j < m) if (!isNaN(x = candidates[j][dimension])) return x; + return Math.random() * size; } return force.resume(); }; @@ -9773,17 +10098,19 @@ d3 = function() { node.depth = depth; nodes.push(node); if (childs && (n = childs.length)) { - var i = -1, n, c = node.children = [], v = 0, j = depth + 1, d; + var i = -1, n, c = node.children = new Array(n), v = 0, j = depth + 1, d; while (++i < n) { - d = recurse(childs[i], j, nodes); + d = c[i] = recurse(childs[i], j, nodes); d.parent = node; - c.push(d); v += d.value; } if (sort) c.sort(sort); if (value) node.value = v; - } else if (value) { - node.value = +value.call(hierarchy, node, depth) || 0; + } else { + delete node.children; + if (value) { + node.value = +value.call(hierarchy, node, depth) || 0; + } } return node; } @@ -9887,7 +10214,7 @@ d3 = function() { return d3_layout_hierarchyRebind(partition, hierarchy); }; d3.layout.pie = function() { - var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = 2 * π; + var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ; function pie(data) { var values = data.map(function(d, i) { return +value.call(pie, d, i); @@ -10732,10 +11059,16 @@ d3 = 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 / m; + return s; }; } }; @@ -10851,13 +11184,10 @@ d3 = function() { return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp"); } function d3_scale_linearNice(domain, m) { - return d3_scale_nice(domain, d3_scale_niceStep(m ? d3_scale_linearTickRange(domain, m)[2] : d3_scale_linearNiceStep(domain))); - } - function d3_scale_linearNiceStep(domain) { - var extent = d3_scaleExtent(domain), span = extent[1] - extent[0]; - return Math.pow(10, Math.round(Math.log(span) / Math.LN10) - 1); + return d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); } function d3_scale_linearTickRange(domain, m) { + if (m == null) m = 10; var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step; if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2; extent[0] = Math.ceil(extent[0] / step) * step; @@ -10869,12 +11199,26 @@ d3 = function() { return d3.range.apply(d3, d3_scale_linearTickRange(domain, m)); } function d3_scale_linearTickFormat(domain, m, format) { - var precision = -Math.floor(Math.log(d3_scale_linearTickRange(domain, m)[2]) / Math.LN10 + .01); + var range = d3_scale_linearTickRange(domain, m); return d3.format(format ? format.replace(d3_format_re, function(a, b, c, d, e, f, g, h, i, j) { - return [ b, c, d, e, f, g, h, i || "." + (precision - (j === "%") * 2), j ].join(""); - }) : ",." + precision + "f"); + return [ b, c, d, e, f, g, h, i || "." + d3_scale_linearFormatPrecision(j, range), j ].join(""); + }) : ",." + d3_scale_linearPrecision(range[2]) + "f"); } - d3.scale.log = function() { + 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(Math.abs(range[0]), Math.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) { @@ -10909,9 +11253,8 @@ d3 = function() { return scale; }; scale.ticks = function() { - var extent = d3_scaleExtent(domain), ticks = []; - if (extent.every(isFinite)) { - var u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base; + 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)); @@ -11001,7 +11344,7 @@ d3 = function() { function d3_scale_ordinal(domain, ranger) { var index, range, rangeBand; function scale(x) { - return range[((index.get(x) || index.set(x, domain.push(x))) - 1) % range.length]; + return range[((index.get(x) || ranger.t === "range" && index.set(x, domain.push(x))) - 1) % range.length]; } function steps(start, step) { return d3.range(domain.length).map(function(i) { @@ -11136,127 +11479,377 @@ d3 = function() { 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; + 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 = {}; + d3.svg.arc = function() { + var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; + function arc() { + var r0 = innerRadius.apply(this, arguments), r1 = outerRadius.apply(this, arguments), a0 = startAngle.apply(this, arguments) + d3_svg_arcOffset, a1 = endAngle.apply(this, arguments) + d3_svg_arcOffset, da = (a1 < a0 && (da = a0, + a0 = a1, a1 = da), a1 - a0), df = da < π ? "0" : "1", c0 = Math.cos(a0), s0 = Math.sin(a0), c1 = Math.cos(a1), s1 = Math.sin(a1); + return da >= d3_svg_arcMax ? r0 ? "M0," + r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + -r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + r1 + "M0," + r0 + "A" + r0 + "," + r0 + " 0 1,0 0," + -r0 + "A" + r0 + "," + r0 + " 0 1,0 0," + r0 + "Z" : "M0," + r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + -r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + r1 + "Z" : r0 ? "M" + r1 * c0 + "," + r1 * s0 + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1 + "L" + r0 * c1 + "," + r0 * s1 + "A" + r0 + "," + r0 + " 0 " + df + ",0 " + r0 * c0 + "," + r0 * s0 + "Z" : "M" + r1 * c0 + "," + r1 * s0 + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1 + "L0,0" + "Z"; + } + 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.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.centroid = function() { + var r = (innerRadius.apply(this, arguments) + outerRadius.apply(this, arguments)) / 2, a = (startAngle.apply(this, arguments) + endAngle.apply(this, arguments)) / 2 + d3_svg_arcOffset; + return [ Math.cos(a) * r, Math.sin(a) * r ]; + }; + return arc; + }; + var d3_svg_arcOffset = -halfπ, d3_svg_arcMax = τ - ε; + 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_line(projection) { + var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7; + function line(data) { + var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y); + function segment() { + segments.push("M", interpolate(projection(points), tension)); + } + while (++i < n) { + if (defined.call(this, d = data[i], i)) { + points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]); + } else if (points.length) { + segment(); + points = []; + } + } + if (points.length) segment(); + return segments.length ? segments.join("") : null; + } + line.x = function(_) { + if (!arguments.length) return x; + x = _; + return line; + }; + line.y = function(_) { + if (!arguments.length) return y; + y = _; + return line; + }; + line.defined = function(_) { + if (!arguments.length) return defined; + defined = _; + return line; + }; + line.interpolate = function(_) { + if (!arguments.length) return interpolateKey; + if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; + return line; + }; + line.tension = function(_) { + if (!arguments.length) return tension; + tension = _; + return line; + }; + return line; + } + d3.svg.line = function() { + return d3_svg_line(d3_identity); + }; + var d3_svg_lineInterpolators = d3.map({ + linear: d3_svg_lineLinear, + "linear-closed": d3_svg_lineLinearClosed, + step: d3_svg_lineStep, + "step-before": d3_svg_lineStepBefore, + "step-after": d3_svg_lineStepAfter, + basis: d3_svg_lineBasis, + "basis-open": d3_svg_lineBasisOpen, + "basis-closed": d3_svg_lineBasisClosed, + bundle: d3_svg_lineBundle, + cardinal: d3_svg_lineCardinal, + "cardinal-open": d3_svg_lineCardinalOpen, + "cardinal-closed": d3_svg_lineCardinalClosed, + monotone: d3_svg_lineMonotone + }); + d3_svg_lineInterpolators.forEach(function(key, value) { + value.key = key; + value.closed = /-closed$/.test(key); + }); + function d3_svg_lineLinear(points) { + return points.join("L"); + } + function d3_svg_lineLinearClosed(points) { + return d3_svg_lineLinear(points) + "Z"; + } + function d3_svg_lineStep(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]); + if (n > 1) path.push("H", p[0]); + return path.join(""); + } + function d3_svg_lineStepBefore(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]); + return path.join(""); + } + function d3_svg_lineStepAfter(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]); + return path.join(""); + } + function d3_svg_lineCardinalOpen(points, tension) { + return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, points.length - 1), d3_svg_lineCardinalTangents(points, tension)); + } + function d3_svg_lineCardinalClosed(points, tension) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), + points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension)); + } + function d3_svg_lineCardinal(points, tension) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension)); + } + function d3_svg_lineHermite(points, tangents) { + if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) { + return d3_svg_lineLinear(points); + } + var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1; + if (quad) { + path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1]; + p0 = points[1]; + pi = 2; + } + if (tangents.length > 1) { + t = tangents[1]; + p = points[pi]; + pi++; + path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; + for (var i = 2; i < tangents.length; i++, pi++) { + p = points[pi]; + t = tangents[i]; + path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; + } + } + if (quad) { + var lp = points[pi]; + path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1]; + } + return path; + } + function d3_svg_lineCardinalTangents(points, tension) { + var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length; + while (++i < n) { + p0 = p1; + p1 = p2; + p2 = points[i]; + tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]); + } + return tangents; + } + function d3_svg_lineBasis(points) { + if (points.length < 3) return d3_svg_lineLinear(points); + var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; + points.push(points[n - 1]); + while (++i <= n) { + pi = points[i]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + points.pop(); + path.push("L", pi); + return path.join(""); + } + function d3_svg_lineBasisOpen(points) { + if (points.length < 4) return d3_svg_lineLinear(points); + var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ]; + while (++i < 3) { + pi = points[i]; + px.push(pi[0]); + py.push(pi[1]); + } + path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)); + --i; + while (++i < n) { + pi = points[i]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); } - 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(); + return path.join(""); } - 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)]; + 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]); } - 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; + 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); } - 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; + return path.join(""); } - d3.svg.arc = function() { - var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; - function arc() { - var r0 = innerRadius.apply(this, arguments), r1 = outerRadius.apply(this, arguments), a0 = startAngle.apply(this, arguments) + d3_svg_arcOffset, a1 = endAngle.apply(this, arguments) + d3_svg_arcOffset, da = (a1 < a0 && (da = a0, - a0 = a1, a1 = da), a1 - a0), df = da < π ? "0" : "1", c0 = Math.cos(a0), s0 = Math.sin(a0), c1 = Math.cos(a1), s1 = Math.sin(a1); - return da >= d3_svg_arcMax ? r0 ? "M0," + r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + -r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + r1 + "M0," + r0 + "A" + r0 + "," + r0 + " 0 1,0 0," + -r0 + "A" + r0 + "," + r0 + " 0 1,0 0," + r0 + "Z" : "M0," + r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + -r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + r1 + "Z" : r0 ? "M" + r1 * c0 + "," + r1 * s0 + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1 + "L" + r0 * c1 + "," + r0 * s1 + "A" + r0 + "," + r0 + " 0 " + df + ",0 " + r0 * c0 + "," + r0 * s0 + "Z" : "M" + r1 * c0 + "," + r1 * s0 + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1 + "L0,0" + "Z"; + 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); + } } - 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.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.centroid = function() { - var r = (innerRadius.apply(this, arguments) + outerRadius.apply(this, arguments)) / 2, a = (startAngle.apply(this, arguments) + endAngle.apply(this, arguments)) / 2 + d3_svg_arcOffset; - return [ Math.cos(a) * r, Math.sin(a) * r ]; - }; - return arc; - }; - var d3_svg_arcOffset = -π / 2, d3_svg_arcMax = 2 * π - 1e-6; - function d3_svg_arcInnerRadius(d) { - return d.innerRadius; + return d3_svg_lineBasis(points); } - function d3_svg_arcOuterRadius(d) { - return d.outerRadius; + function d3_svg_lineDot4(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; } - function d3_svg_arcStartAngle(d) { - return d.startAngle; + 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_arcEndAngle(d) { - return d.endAngle; + 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); @@ -11276,7 +11869,7 @@ d3 = function() { return points; } function d3_svg_area(projection) { - var x0 = d3_svg_lineX, x1 = d3_svg_lineX, y0 = 0, y1 = d3_svg_lineY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7; + 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; @@ -11571,7 +12164,7 @@ d3 = function() { 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)) { + if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { subgroup.push(node); } } @@ -11686,7 +12279,7 @@ d3 = function() { d3_transitionPrototype.remove = function() { return this.each("end.transition", function() { var p; - if (!this.__transition__ && (p = this.parentNode)) p.removeChild(this); + if (this.__transition__.count < 2 && (p = this.parentNode)) p.removeChild(this); }); }; d3_transitionPrototype.ease = function(value) { @@ -11700,16 +12293,16 @@ d3 = function() { d3_transitionPrototype.delay = function(value) { var id = this.id; return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { - node.__transition__[id].delay = value.call(node, node.__data__, i, j) | 0; - } : (value |= 0, function(node) { + node.__transition__[id].delay = +value.call(node, node.__data__, i, j); + } : (value = +value, function(node) { node.__transition__[id].delay = value; })); }; d3_transitionPrototype.duration = function(value) { var id = this.id; return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { - node.__transition__[id].duration = Math.max(1, value.call(node, node.__data__, i, j) | 0); - } : (value = Math.max(1, value | 0), function(node) { + node.__transition__[id].duration = Math.max(1, value.call(node, node.__data__, i, j)); + } : (value = Math.max(1, value), function(node) { node.__transition__[id].duration = value; })); }; @@ -11763,9 +12356,10 @@ d3 = function() { }; ++lock.count; d3.timer(function(elapsed) { - var d = node.__data__, ease = transition.ease, delay = transition.delay, duration = transition.duration, tweened = []; - if (delay <= elapsed) return start(elapsed); - d3_timer_replace(start, delay, time); + var d = node.__data__, ease = transition.ease, delay = transition.delay, duration = transition.duration, timer = d3_timer_active, tweened = []; + timer.t = delay + time; + if (delay <= elapsed) return start(elapsed - delay); + timer.c = start; function start(elapsed) { if (lock.active > id) return stop(); lock.active = id; @@ -11775,19 +12369,20 @@ d3 = function() { tweened.push(value); } }); - if (tick(elapsed)) return 1; - d3_timer_replace(tick, 0, time); + d3.timer(function() { + timer.c = tick(elapsed || 1) ? d3_true : tick; + return 1; + }, 0, time); } function tick(elapsed) { if (lock.active !== id) return stop(); - var t = (elapsed - delay) / duration, e = ease(t), n = tweened.length; + var t = elapsed / duration, e = ease(t), n = tweened.length; while (n > 0) { tweened[--n].call(node, e); } if (t >= 1) { - stop(); transition.event && transition.event.end.call(node, d, i); - return 1; + return stop(); } } function stop() { @@ -11798,17 +12393,14 @@ d3 = function() { } } d3.svg.axis = function() { - var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, tickMajorSize = 6, tickMinorSize = 6, tickEndSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_, tickSubdivide = 0; + 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 ticks = tickValues == null ? scale.ticks ? scale.ticks.apply(scale, tickArguments_) : scale.domain() : tickValues, tickFormat = tickFormat_ == null ? scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments_) : String : tickFormat_; - var subticks = d3_svg_axisSubdivide(scale, ticks, tickSubdivide), subtick = g.selectAll(".tick.minor").data(subticks, String), subtickEnter = subtick.enter().insert("line", ".tick").attr("class", "tick minor").style("opacity", 1e-6), subtickExit = d3.transition(subtick.exit()).style("opacity", 1e-6).remove(), subtickUpdate = d3.transition(subtick).style("opacity", 1); - var tick = g.selectAll(".tick.major").data(ticks, String), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick major").style("opacity", 1e-6), tickExit = d3.transition(tick.exit()).style("opacity", 1e-6).remove(), tickUpdate = d3.transition(tick).style("opacity", 1), tickTransform; - var range = d3_scaleRange(scale), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), + 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).style("opacity", 1), tickTransform; + var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), d3.transition(path)); - var scale1 = scale.copy(), scale0 = this.__chart__ || scale1; - this.__chart__ = scale1; 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"); @@ -11816,73 +12408,63 @@ d3 = function() { case "bottom": { tickTransform = d3_svg_axisX; - subtickEnter.attr("y2", tickMinorSize); - subtickUpdate.attr("x2", 0).attr("y2", tickMinorSize); - lineEnter.attr("y2", tickMajorSize); - textEnter.attr("y", Math.max(tickMajorSize, 0) + tickPadding); - lineUpdate.attr("x2", 0).attr("y2", tickMajorSize); - textUpdate.attr("x", 0).attr("y", Math.max(tickMajorSize, 0) + tickPadding); + lineEnter.attr("y2", innerTickSize); + textEnter.attr("y", Math.max(innerTickSize, 0) + tickPadding); + lineUpdate.attr("x2", 0).attr("y2", innerTickSize); + textUpdate.attr("x", 0).attr("y", Math.max(innerTickSize, 0) + tickPadding); text.attr("dy", ".71em").style("text-anchor", "middle"); - pathUpdate.attr("d", "M" + range[0] + "," + tickEndSize + "V0H" + range[1] + "V" + tickEndSize); + pathUpdate.attr("d", "M" + range[0] + "," + outerTickSize + "V0H" + range[1] + "V" + outerTickSize); break; } case "top": { tickTransform = d3_svg_axisX; - subtickEnter.attr("y2", -tickMinorSize); - subtickUpdate.attr("x2", 0).attr("y2", -tickMinorSize); - lineEnter.attr("y2", -tickMajorSize); - textEnter.attr("y", -(Math.max(tickMajorSize, 0) + tickPadding)); - lineUpdate.attr("x2", 0).attr("y2", -tickMajorSize); - textUpdate.attr("x", 0).attr("y", -(Math.max(tickMajorSize, 0) + tickPadding)); + lineEnter.attr("y2", -innerTickSize); + textEnter.attr("y", -(Math.max(innerTickSize, 0) + tickPadding)); + lineUpdate.attr("x2", 0).attr("y2", -innerTickSize); + textUpdate.attr("x", 0).attr("y", -(Math.max(innerTickSize, 0) + tickPadding)); text.attr("dy", "0em").style("text-anchor", "middle"); - pathUpdate.attr("d", "M" + range[0] + "," + -tickEndSize + "V0H" + range[1] + "V" + -tickEndSize); + pathUpdate.attr("d", "M" + range[0] + "," + -outerTickSize + "V0H" + range[1] + "V" + -outerTickSize); break; } case "left": { tickTransform = d3_svg_axisY; - subtickEnter.attr("x2", -tickMinorSize); - subtickUpdate.attr("x2", -tickMinorSize).attr("y2", 0); - lineEnter.attr("x2", -tickMajorSize); - textEnter.attr("x", -(Math.max(tickMajorSize, 0) + tickPadding)); - lineUpdate.attr("x2", -tickMajorSize).attr("y2", 0); - textUpdate.attr("x", -(Math.max(tickMajorSize, 0) + tickPadding)).attr("y", 0); + lineEnter.attr("x2", -innerTickSize); + textEnter.attr("x", -(Math.max(innerTickSize, 0) + tickPadding)); + lineUpdate.attr("x2", -innerTickSize).attr("y2", 0); + textUpdate.attr("x", -(Math.max(innerTickSize, 0) + tickPadding)).attr("y", 0); text.attr("dy", ".32em").style("text-anchor", "end"); - pathUpdate.attr("d", "M" + -tickEndSize + "," + range[0] + "H0V" + range[1] + "H" + -tickEndSize); + pathUpdate.attr("d", "M" + -outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + -outerTickSize); break; } case "right": { tickTransform = d3_svg_axisY; - subtickEnter.attr("x2", tickMinorSize); - subtickUpdate.attr("x2", tickMinorSize).attr("y2", 0); - lineEnter.attr("x2", tickMajorSize); - textEnter.attr("x", Math.max(tickMajorSize, 0) + tickPadding); - lineUpdate.attr("x2", tickMajorSize).attr("y2", 0); - textUpdate.attr("x", Math.max(tickMajorSize, 0) + tickPadding).attr("y", 0); + lineEnter.attr("x2", innerTickSize); + textEnter.attr("x", Math.max(innerTickSize, 0) + tickPadding); + lineUpdate.attr("x2", innerTickSize).attr("y2", 0); + textUpdate.attr("x", Math.max(innerTickSize, 0) + tickPadding).attr("y", 0); text.attr("dy", ".32em").style("text-anchor", "start"); - pathUpdate.attr("d", "M" + tickEndSize + "," + range[0] + "H0V" + range[1] + "H" + tickEndSize); + pathUpdate.attr("d", "M" + outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + outerTickSize); break; } } - if (scale.rangeBand) { - var dx = scale1.rangeBand() / 2, x = function(d) { - return scale1(d) + dx; + if (scale1.rangeBand) { + var x = scale1, dx = x.rangeBand() / 2; + scale0 = scale1 = function(d) { + return x(d) + dx; }; - tickEnter.call(tickTransform, x); - tickUpdate.call(tickTransform, x); + } else if (scale0.rangeBand) { + scale0 = scale1; } else { - tickEnter.call(tickTransform, scale0); - tickUpdate.call(tickTransform, scale1); tickExit.call(tickTransform, scale1); - subtickEnter.call(tickTransform, scale0); - subtickUpdate.call(tickTransform, scale1); - subtickExit.call(tickTransform, scale1); } + tickEnter.call(tickTransform, scale0); + tickUpdate.call(tickTransform, scale1); }); } axis.scale = function(x) { @@ -11910,12 +12492,21 @@ d3 = function() { tickFormat_ = x; return axis; }; - axis.tickSize = function(x, y) { - if (!arguments.length) return tickMajorSize; - var n = arguments.length - 1; - tickMajorSize = +x; - tickMinorSize = n > 1 ? +y : tickMajorSize; - tickEndSize = n > 0 ? +arguments[n] : tickMajorSize; + 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) { @@ -11923,10 +12514,8 @@ d3 = function() { tickPadding = +x; return axis; }; - axis.tickSubdivide = function(x) { - if (!arguments.length) return tickSubdivide; - tickSubdivide = +x; - return axis; + axis.tickSubdivide = function() { + return arguments.length && axis; }; return axis; }; @@ -11946,32 +12535,17 @@ d3 = function() { return "translate(0," + y(d) + ")"; }); } - function d3_svg_axisSubdivide(scale, ticks, m) { - subticks = []; - if (m && ticks.length > 1) { - var extent = d3_scaleExtent(scale.domain()), subticks, i = -1, n = ticks.length, d = (ticks[1] - ticks[0]) / ++m, j, v; - while (++i < n) { - for (j = m; --j > 0; ) { - if ((v = +ticks[i] - j * d) >= extent[0]) { - subticks.push(v); - } - } - } - for (--i, j = 0; ++j < m && (v = +ticks[i] + j * d) < extent[1]; ) { - subticks.push(v); - } - } - return subticks; - } d3.svg.brush = function() { - var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, resizes = d3_svg_brushResizes[0], extent = [ [ 0, 0 ], [ 0, 0 ] ], clamp = [ true, true ], extentDomain; + 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), bg = g.selectAll(".background").data([ 0 ]), fg = g.selectAll(".extent").data([ 0 ]), tz = g.selectAll(".resize").data(resizes, String), e; - g.style("pointer-events", "all").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart); - bg.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair"); - fg.enter().append("rect").attr("class", "extent").style("cursor", "move"); - tz.enter().append("g").attr("class", function(d) { + 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]; @@ -11980,50 +12554,105 @@ d3 = function() { }).attr("y", function(d) { return /^[ns]/.test(d) ? -3 : null; }).attr("width", 6).attr("height", 6).style("visibility", "hidden"); - tz.style("display", brush.empty() ? "none" : null); - tz.exit().remove(); + resize.style("display", brush.empty() ? "none" : null); + var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range; if (x) { - e = d3_scaleRange(x); - bg.attr("x", e[0]).attr("width", e[1] - e[0]); - redrawX(g); + range = d3_scaleRange(x); + backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]); + redrawX(gUpdate); } if (y) { - e = d3_scaleRange(y); - bg.attr("y", e[0]).attr("height", e[1] - e[0]); - redrawY(g); + range = d3_scaleRange(y); + backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]); + redrawY(gUpdate); } - redraw(g); + 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(" + extent[+/e$/.test(d)][0] + "," + extent[+/^s/.test(d)][1] + ")"; + return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")"; }); } function redrawX(g) { - g.select(".extent").attr("x", extent[0][0]); - g.selectAll(".extent,.n>rect,.s>rect").attr("width", extent[1][0] - extent[0][0]); + 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", extent[0][1]); - g.selectAll(".extent,.e>rect,.w>rect").attr("height", extent[1][1] - extent[0][1]); + 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(), center, origin = mouse(), offset; + 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(), center, origin = d3.mouse(target), offset; var w = d3.select(d3_window).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] = extent[0][0] - origin[0]; - origin[1] = extent[0][1] - origin[1]; + 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 = [ extent[1 - ex][0] - origin[0], extent[1 - ey][1] - origin[1] ]; - origin[0] = extent[ex][0]; - origin[1] = extent[ey][1]; + 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")); @@ -12031,16 +12660,12 @@ d3 = function() { type: "brushstart" }); brushmove(); - function mouse() { - var touches = d3.event.changedTouches; - return touches ? d3.touches(target, touches)[0] : d3.mouse(target); - } function keydown() { if (d3.event.keyCode == 32) { if (!dragging) { center = null; - origin[0] -= extent[1][0]; - origin[1] -= extent[1][1]; + origin[0] -= xExtent[1]; + origin[1] -= yExtent[1]; dragging = 2; } d3_eventPreventDefault(); @@ -12048,23 +12673,23 @@ d3 = function() { } function keyup() { if (d3.event.keyCode == 32 && dragging == 2) { - origin[0] += extent[1][0]; - origin[1] += extent[1][1]; + origin[0] += xExtent[1]; + origin[1] += yExtent[1]; dragging = 0; d3_eventPreventDefault(); } } function brushmove() { - var point = mouse(), moved = false; + 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 = [ (extent[0][0] + extent[1][0]) / 2, (extent[0][1] + extent[1][1]) / 2 ]; - origin[0] = extent[+(point[0] < center[0])][0]; - origin[1] = extent[+(point[1] < center[1])][1]; + 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)) { @@ -12084,12 +12709,12 @@ d3 = function() { } } function move1(point, scale, i) { - var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], size = extent[1][i] - extent[0][i], min, max; + 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 = clamp[i] ? Math.max(r0, Math.min(r1, point[i])) : point[i]; + min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i]; if (dragging) { max = (min += position) + size; } else { @@ -12101,10 +12726,10 @@ d3 = function() { max = position; } } - if (extent[0][i] !== min || extent[1][i] !== max) { - extentDomain = null; - extent[0][i] = min; - extent[1][i] = max; + if (extent[0] != min || extent[1] != max) { + if (i) yExtentDomain = null; else xExtentDomain = null; + extent[0] = min; + extent[1] = max; return true; } } @@ -12132,58 +12757,60 @@ d3 = function() { return brush; }; brush.clamp = function(z) { - if (!arguments.length) return x && y ? clamp : x || y ? clamp[+!x] : null; - if (x && y) clamp = [ !!z[0], !!z[1] ]; else if (x || y) clamp[+!x] = !!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) { - z = extentDomain || extent; if (x) { - x0 = z[0][0], x1 = z[1][0]; - if (!extentDomain) { - x0 = extent[0][0], x1 = extent[1][0]; + 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) { - y0 = z[0][1], y1 = z[1][1]; - if (!extentDomain) { - y0 = extent[0][1], y1 = extent[1][1]; + 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 ]; } - extentDomain = [ [ 0, 0 ], [ 0, 0 ] ]; if (x) { x0 = z[0], x1 = z[1]; if (y) x0 = x0[0], x1 = x1[0]; - extentDomain[0][0] = x0, extentDomain[1][0] = x1; + xExtentDomain = [ x0, x1 ]; if (x.invert) x0 = x(x0), x1 = x(x1); if (x1 < x0) t = x0, x0 = x1, x1 = t; - extent[0][0] = x0 | 0, extent[1][0] = x1 | 0; + 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]; - extentDomain[0][1] = y0, extentDomain[1][1] = y1; + yExtentDomain = [ y0, y1 ]; if (y.invert) y0 = y(y0), y1 = y(y1); if (y1 < y0) t = y0, y0 = y1, y1 = t; - extent[0][1] = y0 | 0, extent[1][1] = y1 | 0; + if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ]; } return brush; }; brush.clear = function() { - extentDomain = null; - extent[0][0] = extent[0][1] = extent[1][0] = extent[1][1] = 0; + if (!brush.empty()) { + xExtent = [ 0, 0 ], yExtent = [ 0, 0 ]; + xExtentDomain = yExtentDomain = null; + } return brush; }; brush.empty = function() { - return x && extent[0][0] === extent[1][0] || y && extent[0][1] === extent[1][1]; + return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1]; }; return d3.rebind(brush, event, "on"); }; @@ -12198,12 +12825,11 @@ d3 = function() { sw: "nesw-resize" }; var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ]; - d3.time = {}; - var d3_time = Date, d3_time_daySymbols = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]; - function d3_time_utc() { + var d3_time = d3.time = {}, d3_date = Date, d3_time_daySymbols = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]; + function d3_date_utc() { this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]); } - d3_time_utc.prototype = { + d3_date_utc.prototype = { getDate: function() { return this._.getUTCDate(); }, @@ -12274,11 +12900,11 @@ d3 = function() { return date - d0 < d1 - date ? d0 : d1; } function ceil(date) { - step(date = local(new d3_time(date - 1)), 1); + step(date = local(new d3_date(date - 1)), 1); return date; } function offset(date, k) { - step(date = new d3_time(+date), k); + step(date = new d3_date(+date), k); return date; } function range(t0, t1, dt) { @@ -12295,12 +12921,12 @@ d3 = function() { } function range_utc(t0, t1, dt) { try { - d3_time = d3_time_utc; - var utc = new d3_time_utc(); + d3_date = d3_date_utc; + var utc = new d3_date_utc(); utc._ = t0; return range(utc, t1, dt); } finally { - d3_time = Date; + d3_date = Date; } } local.floor = local; @@ -12319,17 +12945,17 @@ d3 = function() { function d3_time_interval_utc(method) { return function(date, k) { try { - d3_time = d3_time_utc; - var utc = new d3_time_utc(); + d3_date = d3_date_utc; + var utc = new d3_date_utc(); utc._ = date; return method(utc, k)._; } finally { - d3_time = Date; + d3_date = Date; } }; } - d3.time.year = d3_time_interval(function(date) { - date = d3.time.day(date); + d3_time.year = d3_time_interval(function(date) { + date = d3_time.day(date); date.setMonth(0, 1); return date; }, function(date, offset) { @@ -12337,10 +12963,10 @@ d3 = function() { }, 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_time(2e3, 0); + 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) { @@ -12348,36 +12974,37 @@ d3 = function() { }, 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); + 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); }; d3_time_daySymbols.forEach(function(day, i) { day = day.toLowerCase(); 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); + 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); + 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[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; - d3.time.format = function(template) { + 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; + d3_time.format = d3_time_format; + function d3_time_format(template) { var n = template.length; function format(date) { var string = [], i = -1, j = 0, c, p, f; @@ -12401,30 +13028,32 @@ d3 = function() { H: 0, M: 0, S: 0, - L: 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 date = new d3_time(); + var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)(); if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("w" in d && ("W" in d || "U" in d)) { date.setFullYear(d.y, 0, 1); date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7); } else date.setFullYear(d.y, d.m, d.d); - date.setHours(d.H, d.M, d.S, d.L); - return date; + date.setHours(d.H + Math.floor(d.Z / 100), 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, i = 0, n = template.length, m = string.length; + 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) { - p = d3_time_parsers[template.charAt(i++)]; + 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; @@ -12463,7 +13092,7 @@ d3 = function() { B: function(d) { return d3_time_months[d.getMonth()]; }, - c: d3.time.format(d3_time_formatDateTime), + c: d3_time_format(d3_time_formatDateTime), d: function(d, p) { return d3_time_formatPad(d.getDate(), p, 2); }, @@ -12477,7 +13106,7 @@ d3 = function() { 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); + return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3); }, L: function(d, p) { return d3_time_formatPad(d.getMilliseconds(), p, 3); @@ -12495,16 +13124,16 @@ d3 = function() { return d3_time_formatPad(d.getSeconds(), p, 2); }, U: function(d, p) { - return d3_time_formatPad(d3.time.sundayOfYear(d), p, 2); + 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); + return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2); }, - x: d3.time.format(d3_time_formatDate), - X: d3.time.format(d3_time_formatTime), + x: d3_time_format(d3_time_formatDate), + X: d3_time_format(d3_time_formatTime), y: function(d, p) { return d3_time_formatPad(d.getFullYear() % 100, p, 2); }, @@ -12539,6 +13168,7 @@ d3 = function() { 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) { @@ -12595,6 +13225,10 @@ d3 = function() { var n = d3_time_numberRe.exec(string.substring(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.substring(i, i + 5)) ? (date.Z = +string, + i + 5) : -1; + } function d3_time_expandYear(d) { return d + (d > 68 ? 1900 : 2e3); } @@ -12643,7 +13277,7 @@ d3 = function() { pm: 1 }); function d3_time_zone(d) { - var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = ~~(Math.abs(z) / 60), zm = Math.abs(z) % 60; + var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = ~~(abs(z) / 60), 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) { @@ -12651,32 +13285,33 @@ d3 = function() { var n = d3_time_percentRe.exec(string.substring(i, i + 1)); return n ? i + n[0].length : -1; } - d3.time.format.utc = function(template) { - var local = d3.time.format(template); + d3_time_format.utc = d3_time_formatUtc; + function d3_time_formatUtc(template) { + var local = d3_time_format(template); function format(date) { try { - d3_time = d3_time_utc; - var utc = new d3_time(); + d3_date = d3_date_utc; + var utc = new d3_date(); utc._ = date; return local(utc); } finally { - d3_time = Date; + d3_date = Date; } } format.parse = function(string) { try { - d3_time = d3_time_utc; + d3_date = d3_date_utc; var date = local.parse(string); return date && date._; } finally { - d3_time = Date; + d3_date = Date; } }; format.toString = local.toString; return format; - }; - var d3_time_formatIso = d3.time.format.utc("%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; + } + 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(); } @@ -12685,36 +13320,36 @@ d3 = function() { return isNaN(date) ? null : date; }; d3_time_formatIsoNative.toString = d3_time_formatIso.toString; - d3.time.second = d3_time_interval(function(date) { - return new d3_time(Math.floor(date / 1e3) * 1e3); + 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_time(Math.floor(date / 6e4) * 6e4); + 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) { + 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_time((Math.floor(date / 36e5 - timezone) + timezone) * 36e5); + 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); + 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) { @@ -12722,8 +13357,8 @@ d3 = function() { }, function(date) { return date.getMonth(); }); - d3.time.months = d3.time.month.range; - d3.time.months.utc = d3.time.month.utc.range; + 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); @@ -12736,21 +13371,35 @@ d3 = function() { linear.domain(x); return scale; }; - scale.nice = function(m) { - return scale.domain(d3_scale_nice(scale.domain(), m)); + 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(m, k) { - var extent = d3_scaleExtent(scale.domain()); - if (typeof m !== "function") { - var span = extent[1] - extent[0], target = span / m, i = d3.bisect(d3_time_scaleSteps, target); - if (i == d3_time_scaleSteps.length) return methods.year(extent, m); - if (!i) return linear.ticks(m).map(d3_time_scaleDate); - if (target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target) --i; - m = methods[i]; - k = m[1]; - m = m[0].range; - } - return m(extent[0], new Date(+extent[1] + 1), k); + 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; @@ -12770,71 +13419,56 @@ d3 = function() { return f[0](date); }; } - function d3_time_scaleSetYear(y) { - var d = new Date(y, 0, 1); - d.setFullYear(y); - return d; - } - function d3_time_scaleGetYear(d) { - var y = d.getFullYear(), d0 = d3_time_scaleSetYear(y), d1 = d3_time_scaleSetYear(y + 1); - return y + (d - d0) / (d1 - d0); - } 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_scaleLocalFormats = [ [ d3.time.format("%Y"), d3_true ], [ d3.time.format("%B"), function(d) { + 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_scaleLocalFormats = [ [ d3_time_format("%Y"), d3_true ], [ d3_time_format("%B"), function(d) { return d.getMonth(); - } ], [ d3.time.format("%b %d"), function(d) { + } ], [ d3_time_format("%b %d"), function(d) { return d.getDate() != 1; - } ], [ d3.time.format("%a %d"), function(d) { + } ], [ d3_time_format("%a %d"), function(d) { return d.getDay() && d.getDate() != 1; - } ], [ d3.time.format("%I %p"), function(d) { + } ], [ d3_time_format("%I %p"), function(d) { return d.getHours(); - } ], [ d3.time.format("%I:%M"), function(d) { + } ], [ d3_time_format("%I:%M"), function(d) { return d.getMinutes(); - } ], [ d3.time.format(":%S"), function(d) { + } ], [ d3_time_format(":%S"), function(d) { return d.getSeconds(); - } ], [ d3.time.format(".%L"), function(d) { + } ], [ d3_time_format(".%L"), function(d) { return d.getMilliseconds(); } ] ]; - var d3_time_scaleLinear = d3.scale.linear(), d3_time_scaleLocalFormat = d3_time_scaleFormat(d3_time_scaleLocalFormats); - d3_time_scaleLocalMethods.year = function(extent, m) { - return d3_time_scaleLinear.domain(extent.map(d3_time_scaleGetYear)).ticks(m).map(d3_time_scaleSetYear); - }; - d3.time.scale = function() { + var d3_time_scaleLocalFormat = d3_time_scaleFormat(d3_time_scaleLocalFormats); + 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_scaleMilliseconds = { + range: function(start, stop, step) { + return d3.range(+start, +stop, step).map(d3_time_scaleDate); + }, + floor: d3_identity, + ceil: d3_identity + }; var d3_time_scaleUTCMethods = d3_time_scaleLocalMethods.map(function(m) { return [ m[0].utc, m[1] ]; }); - var d3_time_scaleUTCFormats = [ [ d3.time.format.utc("%Y"), d3_true ], [ d3.time.format.utc("%B"), function(d) { + var d3_time_scaleUTCFormats = [ [ d3_time_formatUtc("%Y"), d3_true ], [ d3_time_formatUtc("%B"), function(d) { return d.getUTCMonth(); - } ], [ d3.time.format.utc("%b %d"), function(d) { + } ], [ d3_time_formatUtc("%b %d"), function(d) { return d.getUTCDate() != 1; - } ], [ d3.time.format.utc("%a %d"), function(d) { + } ], [ d3_time_formatUtc("%a %d"), function(d) { return d.getUTCDay() && d.getUTCDate() != 1; - } ], [ d3.time.format.utc("%I %p"), function(d) { + } ], [ d3_time_formatUtc("%I %p"), function(d) { return d.getUTCHours(); - } ], [ d3.time.format.utc("%I:%M"), function(d) { + } ], [ d3_time_formatUtc("%I:%M"), function(d) { return d.getUTCMinutes(); - } ], [ d3.time.format.utc(":%S"), function(d) { + } ], [ d3_time_formatUtc(":%S"), function(d) { return d.getUTCSeconds(); - } ], [ d3.time.format.utc(".%L"), function(d) { + } ], [ d3_time_formatUtc(".%L"), function(d) { return d.getUTCMilliseconds(); } ] ]; var d3_time_scaleUTCFormat = d3_time_scaleFormat(d3_time_scaleUTCFormats); - function d3_time_scaleUTCSetYear(y) { - var d = new Date(Date.UTC(y, 0, 1)); - d.setUTCFullYear(y); - return d; - } - function d3_time_scaleUTCGetYear(d) { - var y = d.getUTCFullYear(), d0 = d3_time_scaleUTCSetYear(y), d1 = d3_time_scaleUTCSetYear(y + 1); - return y + (d - d0) / (d1 - d0); - } - d3_time_scaleUTCMethods.year = function(extent, m) { - return d3_time_scaleLinear.domain(extent.map(d3_time_scaleUTCGetYear)).ticks(m).map(d3_time_scaleUTCSetYear); - }; - d3.time.scale.utc = function() { + 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) { diff --git a/src/bind.coffee b/src/bind.coffee index 8343881..330d8a4 100644 --- a/src/bind.coffee +++ b/src/bind.coffee @@ -66,7 +66,7 @@ bind = ({parent, self, data, join, attr, style, property, text, html, on:argsOn, out = dvl().name('selection') - dvl.register { + bindWorker = dvl.register { listen change: [out] fn: -> @@ -145,6 +145,11 @@ bind = ({parent, self, data, join, attr, style, property, text, html, on:argsOn, return } + bindWorker.on('discard', -> + out.value().remove() + out.value(null) + ) + return out @@ -210,7 +215,7 @@ bindSingle = ({parent, self, data, datum, attr, style, property, text, html, on: listen.push(v) onList[k] = v - dvl.register { + bindWorker = dvl.register { listen change: [self] fn: -> @@ -238,6 +243,12 @@ bindSingle = ({parent, self, data, datum, attr, style, property, text, html, on: return } + + bindWorker.on('discard', -> + self.value().remove() + self.value(null) + ) + return self diff --git a/src/collection.coffee b/src/collection.coffee new file mode 100644 index 0000000..472c288 --- /dev/null +++ b/src/collection.coffee @@ -0,0 +1,69 @@ +dvl = require './core' + +class DVLCollection + constructor: ({data, compare, fn}) -> + compare ?= false + + varBlocks = [] # { v: DVL(), block: DVLBlock() } + + adjust = -> + _data = data.value() + + dvl.group(-> + while _data.length > varBlocks.length + v = null + block = dvl.block -> + v = dvl().compare(compare) + fn(v) + + varBlocks.push({ + v + block + }) + + while varBlocks.length > _data.length + varBlock = varBlocks.pop() + varBlock.v.discard() + varBlock.block.discard() + + for d, i in _data + varBlocks[i].v.value(d) + )() + return + + + dvl.register { + listen: data + fn: -> + return unless Array.isArray(data.value()) + + process.nextTick(adjust) + } + + data.value(data.value()) + + toString: -> + return '[DVLCollection]' + + @factory: () -> + switch arguments.length + when 1 + {data, serialize, fn} = arguments[0] + when 2 + [data, fn] = arguments + else + throw ("incorect number of arguments") + + throw new Error('data should be dvl variable') unless dvl.knows(data) + throw new Error('function should be provided') unless typeof fn is 'function' + + serialize ?= (item) -> String(item).toString() + + return new DVLCollection { + data + fn + serialize + } + + +module.exports = DVLCollection.factory diff --git a/src/core.coffee b/src/core.coffee index a1ad44b..5b9dc20 100644 --- a/src/core.coffee +++ b/src/core.coffee @@ -172,12 +172,17 @@ class DVLVar notify: -> dvl.notify(this) - discard: -> - if @listeners.length > 0 - throw "Cannot remove variable #{@id} because it has listeners." - if @changers.length > 0 - throw "Cannot remove variable #{@id} because it has changers." + discard: (preventSortgraph) -> + for w in @changers + throw new Error("Cannot find variable #{@id} from its changer #{w.id}") if w.change.indexOf(this) < 0 + w.removeChange(this, preventSortgraph) + + for w in @listeners + throw new Error("Cannot find variable #{@id} from its listner #{w.id}") if w.listen.indexOf(this) < 0 + w.removeListen(this, preventSortgraph) + variables.splice(variables.indexOf(this), 1) + sortGraph() if preventSortgraph return null name: -> @@ -252,22 +257,17 @@ dvl.knows = (v) -> v instanceof DVLVar or v instanceof DVLConst class DVLWorker constructor: (@name, @ctx, @fn, @listen, @change) -> @id = nextObjId++ - @updates = new Set() + @eventArrays = {} @level = workers.length # place at the end workers.push(this) # Append listen and change to variables and dependency graph - hasPrev = false for v in @listen v.listeners.push(this) for prevWorker in v.changers prevWorker.updates.add(this) - hasPrev = true - for v in @change - v.changers.push(this) - for nextWorker in v.listeners - @updates.add(nextWorker) + @_redoUpdates() # the optimization is that if we are adding a sink worker then it's level is just the last level if @updates.length() @@ -306,7 +306,6 @@ class DVLWorker for prevWorker in v.changers prevWorker.updates.add(this) updatesChanged = true - hasPrev = false sortGraph() if updatesChanged @@ -322,6 +321,37 @@ class DVLWorker end_notify_collect() return this + removeChange: (v, preventSortgraph) -> + return this if variables.indexOf(v) < 0 + + throw new Error("Cannot find variable #{v.id} in worker #{@id}'s change") if @change.indexOf(v) < 0 + @change.splice(@change.indexOf(v), 1) + v.changers.splice(v.changers.indexOf(this), 1) + @_redoUpdates() + sortGraph() if not preventSortgraph + return this + + removeListen: (v, preventSortgraph) -> + return this if variables.indexOf(v) < 0 + + throw new Error("Cannot find variable #{v.id} in worker #{@id}'s listen") if @listen.indexOf(v) < 0 + @listen.splice(@listen.indexOf(v), 1) + v.listeners.splice(v.listeners.indexOf(this), 1) + + for prevWorker in v.changers + prevWorker._redoUpdates() + + sortGraph() if not preventSortgraph + return this + + _redoUpdates: -> + @updates = new Set() + for v in @change + v.changers.push(this) + for nextWorker in v.listeners + @updates.add(nextWorker) + return + discard: -> # Find the register object workers.splice(workers.indexOf(this), 1) @@ -331,15 +361,24 @@ class DVLWorker prevWorker.updates.remove(this) for v in @change - v.changers.splice(v.changers.indexOf(this), 1) + if v.changers.indexOf(this) > -1 + v.changers.splice(v.changers.indexOf(this), 1) for v in @listen - v.listeners.splice(v.listeners.indexOf(this), 1) + if v.listeners.indexOf(this) > -1 + v.listeners.splice(v.listeners.indexOf(this), 1) sortGraph() @change = @listen = @updates = null # cause an error if we hit these + @eventArrays.discard?.forEach((fn) -> fn()) + return + + on: (type, fn) -> + @eventArrays[type] ?= [] + @eventArrays[type].push fn return + dvl.register = ({ctx, fn, listen, change, name, noRun}) -> throw new Error('cannot call register from within a notify') if curNotifyListener throw new TypeError('fn must be a function') if typeof(fn) != 'function' @@ -397,10 +436,10 @@ class DVLBlock discard: -> @parent?.removeMemeber(this) - d.discard() for d in @owns + v.discard(true) for k, v of @owns + sortGraph() return - dvl.blockFn = -> switch arguments.length when 1 then [fn] = arguments @@ -408,7 +447,7 @@ dvl.blockFn = -> else throw "bad number of arguments" return (args...) -> - block = new DVLBlock(name, curBlock) + curBlock = block = new DVLBlock(name, curBlock) ret = fn.apply(this, args) curBlock = block.parent return ret @@ -419,7 +458,7 @@ dvl.block = -> when 2 then [name, fn] = arguments else throw "bad number of arguments" - block = new DVLBlock(name, curBlock) + curBlock = block = new DVLBlock(name, curBlock) fn.call(this) curBlock = block.parent return block diff --git a/src/index.coffee b/src/index.coffee index 182adca..a09fca0 100644 --- a/src/index.coffee +++ b/src/index.coffee @@ -8,5 +8,6 @@ dvl.svg = require './svg' dvl.snap = require './snap' dvl.misc = require './misc' dvl.util = require './util' +dvl.collection = require './collection' module.exports = dvl diff --git a/test/bind.coffee b/test/bind.coffee new file mode 100644 index 0000000..0b2db77 --- /dev/null +++ b/test/bind.coffee @@ -0,0 +1,277 @@ +{ expect } = require 'chai' +d3 = require 'd3' + +dvl = require '../src' + +nextTick = (fn) -> + setTimeout(fn, 0) + +verifyCleanState = -> throw new Error('Body is not empty') unless d3.select('body').selectAll('div').size() is 0 +cleanUp = -> d3.select('body').selectAll('div').remove() + +describe 'dvl.bind', -> + describe 'when data is an array', -> + beforeEach verifyCleanState + afterEach cleanUp + + it 'enters 1 elements for the array of length 1', (done) -> + data = dvl([0]) + boundSelections = dvl.bind { + parent: d3.select('body') + self: 'div' + data + text: String + } + + nextTick(-> + selections = boundSelections.value() + expect(selections).to.exist + expect(selections.size()).to.equal(1) + selections.each((d, i) -> + expect(d).to.equal(i) + expect(String(d)).to.equal(this.textContent) + ) + done() + ) + + it 'enters 5 elements for the array of length 5', (done) -> + data = dvl([0, 1, 2, 3, 4]) + boundSelections = dvl.bind { + parent: d3.select('body') + self: 'div' + data + text: String + } + + nextTick(-> + selections = boundSelections.value() + expect(selections).to.exist + expect(selections.size()).to.equal(5) + selections.each((d, i) -> + expect(d).to.equal(i) + expect(String(d)).to.equal(this.textContent) + ) + done() + ) + + describe 'when data is not array', -> + beforeEach verifyCleanState + afterEach cleanUp + + it 'does not enter the element', (done) -> + data = dvl(0) + boundSelections = dvl.bind { + parent: d3.select('body') + self: 'div' + data + text: String + } + + nextTick(-> + selections = boundSelections.value() + expect(selections).to.exist + expect(selections.size()).to.equal(0) + done() + ) + + + describe 'when data is null', -> + beforeEach verifyCleanState + afterEach cleanUp + + it 'does not enter the element', (done) -> + data = dvl(null) + boundSelections = dvl.bind { + parent: d3.select('body') + self: 'div' + data + text: String + } + + nextTick(-> + selections = boundSelections.value() + expect(selections).to.exist + expect(selections.size()).to.equal(0) + done() + ) + + describe 'when bind is gone', -> + beforeEach verifyCleanState + afterEach cleanUp + + it 'exits 1 element', (done) -> + data = dvl([0]) + boundSelections = null + block = dvl.block -> + boundSelections = dvl.bind { + parent: d3.select('body') + self: 'div' + data + text: String + } + + nextTick(-> + selections = boundSelections.value() + expect(selections).to.exist + expect(selections.size()).to.equal(1) + selections.each((d, i) -> + expect(d).to.equal(i) + expect(String(d)).to.equal(this.textContent) + ) + + block.discard() + nextTick(-> + selections = boundSelections.value() + expect(selections).to.not.exist + expect(d3.select('body').selectAll('div').size()).to.equal(0) + done() + ) + ) + + it 'exits multiple elements', (done) -> + data = dvl([0, 1, 2, 3, 4]) + boundSelections = null + block = dvl.block -> + boundSelections = dvl.bind { + parent: d3.select('body') + self: 'div' + data + text: String + } + + nextTick(-> + selections = boundSelections.value() + expect(selections).to.exist + expect(selections.size()).to.equal(5) + selections.each((d, i) -> + expect(d).to.equal(i) + expect(String(d)).to.equal(this.textContent) + ) + + block.discard() + nextTick(-> + selections = boundSelections.value() + expect(selections).to.not.exist + expect(d3.select('body').selectAll('div').size()).to.equal(0) + done() + ) + ) + + +describe 'dvl.bindSingle', -> + describe 'when datum is an array', -> + beforeEach verifyCleanState + afterEach cleanUp + + it 'enters 1 element for the array of length 1', (done) -> + datum = dvl([0]) + boundSelection = dvl.bindSingle { + parent: d3.select('body') + self: 'div' + datum + text: String + } + + nextTick(-> + selection = boundSelection.value() + expect(selection).to.exist + expect(selection.size()).to.equal(1) + expect(selection.data()).to.deep.equal([[0]]) + expect(selection.text()).to.equal('0') + done() + ) + + it 'enters 1 element for the array of length 5', (done) -> + datum = dvl([0, 1, 2, 3, 4]) + boundSelection = dvl.bindSingle { + parent: d3.select('body') + self: 'div' + datum + text: String + } + + nextTick(-> + selection = boundSelection.value() + expect(selection).to.exist + expect(selection.size()).to.equal(1) + expect(selection.data()).to.deep.equal([[0, 1, 2, 3, 4]]) + expect(selection.text()).to.equal('0,1,2,3,4') + done() + ) + + + describe 'when datum is not array', -> + beforeEach verifyCleanState + afterEach cleanUp + + it 'enter 1 element', (done) -> + datum = dvl(0) + boundSelection = dvl.bindSingle { + parent: d3.select('body') + self: 'div' + datum + text: String + } + + nextTick(-> + selection = boundSelection.value() + expect(selection).to.exist + expect(selection.size()).to.equal(1) + expect(selection.data()).to.deep.equal([0]) + expect(selection.text()).to.equal('0') + done() + ) + + + describe 'when datum is null', -> + beforeEach verifyCleanState + afterEach cleanUp + + it 'enters the element', (done) -> + datum = dvl(null) + boundSelection = dvl.bindSingle { + parent: d3.select('body') + self: 'div' + datum + text: String + } + + nextTick(-> + selection = boundSelection.value() + expect(selection).to.exist + expect(selection.size()).to.equal(1) + expect(selection.text()).to.equal('undefined') + done() + ) + + + describe 'when bind is gone', -> + beforeEach verifyCleanState + afterEach cleanUp + + it 'exits the element', (done) -> + datum = dvl(0) + boundSelection = null + block = dvl.block -> + boundSelection = dvl.bindSingle { + parent: d3.select('body') + self: 'div' + datum + text: String + } + + nextTick(-> + selection = boundSelection.value() + expect(selection).to.exist + expect(selection.size()).to.equal(1) + expect(selection.data()).to.deep.equal([0]) + expect(selection.text()).to.equal('0') + + block.discard() + nextTick(-> + selections = boundSelection.value() + expect(selections).to.not.exist + expect(d3.select('body').selectAll('div').size()).to.equal(0) + done() + ) + ) diff --git a/test/collection.coffee b/test/collection.coffee new file mode 100644 index 0000000..8c1b752 --- /dev/null +++ b/test/collection.coffee @@ -0,0 +1,167 @@ +{ expect } = require 'chai' +d3 = require 'd3' + +dvl = require '../src' + +verifyCleanState = -> throw new Error('Body is not empty') unless d3.select('body').selectAll('div').size() is 0 +cleanUp = -> + dvl.clearAll() + d3.select('body').selectAll('div').remove() + +describe 'dvl.collection', -> + beforeEach verifyCleanState + afterEach cleanUp + + it 'adds members without errors', (done) -> + data = dvl([0]) + counter = 0 + + collection = dvl.collection(data, (number) -> + dvl.bindSingle { + parent: d3.select('body') + self: 'div' + datum: number + text: String + } + counter += 1 + ) + + process.nextTick(-> + expect(counter).to.equal(1) + data.value([0, 1]) + + process.nextTick(-> + divs = d3.select('body').selectAll('div') + expect(divs.size()).to.equal(2) + divs.each((d, i) -> + expect(d).to.equal(i) + ) + done() + ) + ) + + it 'correctly executes the block', (done) -> + data = dvl([1]) + externalVariable = dvl() + collection = dvl.collection(data, (number) -> + dvl.register { + listen: number + change: externalVariable + fn: -> + externalVariable.value(number.value()) + } + ) + process.nextTick(-> + expect(externalVariable.value()).to.equal(1) + data.value([2]) + + process.nextTick(-> + expect(externalVariable.value()).to.equal(2) + data.value([10]) + + process.nextTick(-> + expect(externalVariable.value()).to.equal(10) + done() + ) + ) + ) + + it 'appends the element correctly without destroying original element', (done) -> + data = dvl([0, 1]) + collection = dvl.collection(data, (number) -> + dvl.bindSingle { + parent: d3.select('body') + self: 'div' + datum: number + text: String + attr: { + class: -> return Math.floor(Math.random() * 10000) + } + } + ) + process.nextTick(-> + firstDivs = {} + divs = d3.select('body').selectAll('div') + divs.each((d, i) -> + expect(d).to.equal(i) + firstDivs[i] = this + ) + expect(divs.size()).to.equal(2) + data.value([0, 1, 2]) + + process.nextTick(-> + divs = d3.select('body').selectAll('div') + divs.each((d, i) -> + expect(d).to.equal(i) + if i < 2 + expect(this).to.equal(firstDivs[i]) + ) + expect(divs.size()).to.equal(3) + done() + ) + ) + + it 'removes the element correctly without destroying original element', (done) -> + data = dvl([0, 1, 2]) + collection = dvl.collection(data, (number) -> + dvl.bindSingle { + parent: d3.select('body') + self: 'div' + datum: number + text: String + } + ) + process.nextTick(-> + firstDivs = {} + divs = d3.select('body').selectAll('div') + divs.each((d, i) -> + expect(d).to.equal(i) + firstDivs[i] = this + ) + expect(divs.size()).to.equal(3) + data.value([0, 1]) + + process.nextTick(-> + divs = d3.select('body').selectAll('div') + divs.each((d, i) -> + expect(d).to.equal(i) + expect(this).to.equal(firstDivs[i]) + ) + expect(divs.size()).to.equal(2) + done() + ) + ) + + + it 'order the element correctly', (done) -> + data = dvl([0, 1]) + collection = dvl.collection(data, (number) -> + dvl.bindSingle { + parent: d3.select('body') + self: 'div' + datum: number + text: String + } + ) + process.nextTick(-> + firstDivs = {} + divs = d3.select('body').selectAll('div') + expect(divs.size()).to.equal(2) + divs.each((d, i) -> + expect(d).to.equal(i) + firstDivs[i] = this + ) + data.value([1, 0]) + + process.nextTick(-> + divs = d3.select('body').selectAll('div') + expect(divs.size()).to.equal(2) + divs.each((d, i) -> + expect(d).to.equal(1 - i) + expect(this).to.equal(firstDivs[i]) + ) + done() + ) + ) + +