/
raster-chart.js
433 lines (356 loc) · 12.8 KB
/
raster-chart.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
import coordinateGridRasterMixin from "../mixins/coordinate-grid-raster-mixin"
import mapMixin from "../mixins/map-mixin"
import baseMixin from "../mixins/base-mixin"
import scatterMixin from "../mixins/scatter-mixin"
import {rasterDrawMixin} from "../mixins/raster-draw-mixin"
import {lastFilteredSize} from "../core/core-async"
export default function rasterChart (parent, useMap, chartGroup, _mapboxgl) {
let _chart = null
const _useMap = useMap !== undefined ? useMap : false
const parentDivId = parent.attributes.id.value
const browser = detectBrowser()
function detectBrowser () { // from SO: http://bit.ly/1Wd156O
const isOpera = (Boolean(window.opr) && Boolean(opr.addons)) || Boolean(window.opera) || navigator.userAgent.indexOf(" OPR/") >= 0
const isFirefox = typeof InstallTrigger !== "undefined"
const isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor") > 0
const isIE = /* @cc_on!@*/false || Boolean(document.documentMode)
const isEdge = !isIE && Boolean(window.StyleMedia)
const isChrome = Boolean(window.chrome) && Boolean(window.chrome.webstore)
return {isOpera, isFirefox, isSafari, isIE, isEdge, isChrome}
}
if (_useMap) {
_chart = mapMixin(baseMixin({}), parentDivId, _mapboxgl, true, false)
} else {
_chart = scatterMixin(coordinateGridRasterMixin({}, _mapboxgl, browser), _mapboxgl, true)
}
// unset predefined mandatory attributes
_chart._mandatoryAttributes([])
let _con = window.hasOwnProperty("con") ? con : null
const _imageOverlay = null
let _renderBoundsMap = {}
let _layerNames = {}
let _layers = []
let _hasBeenRendered = false
let _x = null
let _y = null
const _xScaleName = "x"
const _yScaleName = "y"
let _usePixelRatio = false
let _pixelRatio = 1
let _minPopupShapeBoundsArea = 16 * 16
let _popupSearchRadius = 2
const _popupDivClassName = "map-popup"
let _popupDisplayable = true
_chart.popupDisplayable = function (displayable) {
_popupDisplayable = Boolean(displayable)
}
_chart.x = function (x) {
if (!arguments.length) {
return _x
}
_x = x
return _chart
}
_chart.y = function (_) {
if (!arguments.length) {
return _y
}
_y = _
return _chart
}
_chart._resetRenderBounds = function () {
_renderBoundsMap = {}
}
_chart._resetLayers = function () {
_layers = []
_layerNames = {}
}
_chart.pushLayer = function (layerName, layer) {
if (_layerNames[layerName]) {
throw new Error("A layer with name \"" + layerName + "\" already exists.")
} else if (!layerName.match(/^\w+$/)) {
throw new Error("A layer name can only have alpha numeric characters (A-Z, a-z, 0-9, or _)")
}
_layers.push(layerName)
_layerNames[layerName] = layer
return _chart
}
_chart.popLayer = function () {
const layerName = _layers.pop()
const layer = _layerNames[layerName]
delete _layerNames[layerName]
return layer
}
_chart.getLayer = function (layerName) {
return _layerNames[layerName]
}
_chart.getLayerAt = function (idx) {
const layerName = _layers[idx]
return _layerNames[layerName]
}
_chart.getLayers = function () {
return _layers.map((layerName) => _layerNames[layerName])
}
_chart.getLayerNames = function () {
return _layers
}
_chart.xRangeFilter = function (filter) {
for (const layerName in _layerNames) {
const layer = _layerNames[layerName]
layer.yDim().filter(filter)
}
}
_chart.yRangeFilter = function (filter) {
for (const layerName in _layerNames) {
const layer = _layerNames[layerName]
layer.yDim().filter(filter)
}
}
_chart.destroyChart = function () {
for (const layerName in _layerNames) {
const layer = _layerNames[layerName]
layer.destroyLayer(_chart)
}
this.map().remove()
if (this.legend()) {
this.legend().removeLegend()
}
}
_chart.con = function (_) {
if (!arguments.length) { return _con }
_con = _
return _chart
}
// TODO(croot): pixel ratio should probably be configured on the backend
// rather than here to deal with scenarios where data is used directly
// in pixel-space.
_chart.usePixelRatio = function (usePixelRatio) {
if (!arguments.length) {
return _usePixelRatio
}
_usePixelRatio = Boolean(usePixelRatio)
if (_usePixelRatio) {
_pixelRatio = window.devicePixelRatio || 1
} else {
_pixelRatio = 1
}
return _chart
}
_chart._getPixelRatio = function () {
return _pixelRatio
}
_chart.setSample = function () {
_layers.forEach((layerName) => {
const layer = _layerNames[layerName]
if (layer && typeof layer.setSample === "function") {
layer.setSample()
}
})
}
_chart.setDataAsync((group, callbacks) => {
const bounds = _chart.getDataRenderBounds()
_chart._updateXAndYScales(bounds)
_chart._vegaSpec = genLayeredVega(_chart)
const nonce = _chart.con().renderVega(_chart.__dcFlag__, JSON.stringify(_chart._vegaSpec), {}, callbacks)
_renderBoundsMap[nonce] = bounds
})
_chart.data((group) => {
if (_chart.dataCache !== null) {
return _chart.dataCache
}
const bounds = _chart.getDataRenderBounds()
_chart._updateXAndYScales(bounds)
_chart._vegaSpec = genLayeredVega(_chart, group, lastFilteredSize(group.getCrossfilterId()))
const result = _chart.con().renderVega(_chart.__dcFlag__, JSON.stringify(_chart._vegaSpec))
_renderBoundsMap[result.nonce] = bounds
return result
})
_chart._getXScaleName = function () {
return _xScaleName
}
_chart._getYScaleName = function () {
return _yScaleName
}
_chart._updateXAndYScales = function (renderBounds) {
// renderBounds should be in this order - top left, top-right, bottom-right, bottom-left
const useRenderBounds = (renderBounds && renderBounds.length === 4 && renderBounds[0] instanceof Array && renderBounds[0].length === 2)
if (_x === null) {
_x = d3.scale.linear()
}
if (_y === null) {
_y = d3.scale.linear()
}
if (useRenderBounds) {
if (typeof _chart.useLonLat === "function" && _chart.useLonLat()) {
_x.domain([_chart.conv4326To900913X(renderBounds[0][0]), _chart.conv4326To900913X(renderBounds[1][0])])
_y.domain([_chart.conv4326To900913Y(renderBounds[2][1]), _chart.conv4326To900913Y(renderBounds[0][1])])
} else {
_x.domain([renderBounds[0][0], renderBounds[1][0]])
_y.domain([renderBounds[2][1], renderBounds[0][1]])
}
} else {
const layers = getLayers()
const xRanges = []
const yRanges = []
for (layer in layers) {
let xDim = layer.xDim(), yDim = layer.yDim()
if (xDim) {
var range = xDim.getFilter()
if (range !== null) {
xRanges.push(range)
}
}
if (yDim) {
var range = yDim.getFilter()
if (range !== null) {
yRanges.push(range)
}
}
}
if (xRanges.length) {
const xRange = xRanges.reduce((prevVal, currVal) => [Math.min(prevVal[0], currVal[0]), Math.max(prevVal[1], currVal[1])], [Number.MAX_VALUE, -Number.MAX_VALUE])
if (typeof _chart.useLonLat === "function" && _chart.useLonLat()) {
_x.domain([_chart.conv4326To900913X(xRange[0]), _chart.conv4326To900913X(xRange[1])])
} else {
_x.domain(xRange)
}
} else {
_x.domain([0.001, 0.999])
}
if (yRanges.length) {
const yRange = yRanges.reduce((prevVal, currVal) => [Math.min(prevVal[0], currVal[0]), Math.max(prevVal[1], currVal[1])], [Number.MAX_VALUE, -Number.MAX_VALUE])
if (typeof _chart.useLonLat === "function" && _chart.useLonLat()) {
_y.domain([_chart.conv4326To900913X(yRange[0]), _chart.conv4326To900913X(yRange[1])])
} else {
_y.domain(yRange)
}
} else {
_y.domain([0.001, 0.999])
}
}
}
_chart._determineScaleType = function (scale) {
const scaleType = null
if (scale.rangeBand !== undefined) { return "ordinal" }
if (scale.exponent !== undefined) { return "power" }
if (scale.base !== undefined) { return "log" }
if (scale.quantiles !== undefined) { return "quantiles" }
if (scale.interpolate !== undefined) { return "linear" }
return "quantize"
}
function removeOverlay (overlay) {
_chart._removeOverlay(overlay)
}
_chart._doRender = function (data, redraw, doNotForceData) {
if (!data && Boolean(!doNotForceData)) { data = _chart.data() }
if (_chart.isLoaded()) {
if (Object.keys(data).length) {
_chart._setOverlay(data.image, _renderBoundsMap[data.nonce], data.nonce, browser, Boolean(redraw))
_hasBeenRendered = true
} else {
_chart._setOverlay(null, null, null, browser, Boolean(redraw))
}
}
}
_chart._doRedraw = function () {
_chart._doRender(null, true)
}
_chart.minPopupShapeBoundsArea = function (minPopupShapeBoundsArea) {
if (!arguments.length) { return _minPopupShapeBoundsArea }
_minPopupShapeBoundsArea = minPopupShapeBoundsArea
return _chart
}
_chart.popupSearchRadius = function (popupSearchRadius) {
if (!arguments.length) { return _popupSearchRadius }
_popupSearchRadius = popupSearchRadius
return _chart
}
_chart.getClosestResult = function getClosestResult (point, callback) {
const height = (typeof _chart.effectiveHeight === "function" ? _chart.effectiveHeight() : _chart.height())
const pixelRatio = _chart._getPixelRatio() || 1
const pixel = new TPixel({x: Math.round(point.x * pixelRatio), y: Math.round((height - point.y) * pixelRatio)})
if (!point) {
return
}
let cnt = 0
const layerObj = {}
_layers.forEach((layerName) => {
const layer = _layerNames[layerName]
if (layer.getPopupAndRenderColumns && layer.hasPopupColumns && layer.hasPopupColumns()) {
layerObj[layerName] = layer.getPopupAndRenderColumns(_chart)
++cnt
}
})
// TODO best to fail, skip cb, or call cb wo args?
if (!cnt) {
return
}
return _chart.con().getResultRowForPixel(_chart.__dcFlag__, pixel, layerObj, [function (err, results) {
if (err) {
throw new Error(`getResultRowForPixel failed with message: ${err.message}`)
} else {
return callback(results[0])
}
}], Math.ceil(_popupSearchRadius * pixelRatio))
}
_chart.displayPopup = function displayPopup (result, animate) {
if (!_popupDisplayable || !result || !result.row_set || !result.row_set.length) { return }
if (_chart.select("." + _popupDivClassName).empty()) { // only one popup at a time
const layer = _layerNames[result.vega_table_name]
if (layer && layer.areResultsValidForPopup(result.row_set)) {
const mapPopup = _chart.root().append("div").attr("class", _popupDivClassName)
layer.displayPopup(_chart, mapPopup, result, _minPopupShapeBoundsArea, animate)
}
}
}
_chart.hidePopup = function hidePopup (animate) {
const popupElem = _chart.select("." + _popupDivClassName)
if (!popupElem.empty()) {
for (let i = 0; i < _layers.length; ++i) {
const layerName = _layers[i]
const layer = _layerNames[layerName]
if (layer && layer.isPopupDisplayed(_chart)) {
// TODO(croot): can this be improved? I presume only
// one popup can be shown at a time
if (animate) {
layer.hidePopup(_chart, () => {
_chart.select("." + _popupDivClassName).remove()
})
} else {
_chart.select("." + _popupDivClassName).remove()
}
break
}
}
}
}
return _chart.anchor(parent, chartGroup)
}
function valuesOb (obj) { return Object.keys(obj).map((key) => obj[key]) }
function genLayeredVega (chart) {
const pixelRatio = chart._getPixelRatio()
const width = (typeof chart.effectiveWidth === "function" ? chart.effectiveWidth() : chart.width()) * pixelRatio
const height = (typeof chart.effectiveHeight === "function" ? chart.effectiveHeight() : chart.height()) * pixelRatio
const xdom = chart.x().domain()
const ydom = chart.y().domain()
const data = []
let scales = [
{name: chart._getXScaleName(), type: chart._determineScaleType(chart.x()), domain: chart.x().domain(), range: "width"},
{name: chart._getYScaleName(), type: chart._determineScaleType(chart.y()), domain: chart.y().domain(), range: "height"}
]
const marks = []
chart.getLayerNames().forEach((layerName) => {
const layerVega = chart.getLayer(layerName).genVega(chart, layerName)
data.push(layerVega.data)
scales = scales.concat(layerVega.scales)
marks.push(layerVega.mark)
})
const vegaSpec = {
width: Math.round(width),
height: Math.round(height),
data,
scales,
marks
}
return vegaSpec
}