vega-functions 5.17.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1816 +1,791 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('vega-util'), require('vega-expression'), require('vega-scale'), require('vega-dataflow'), require('vega-scenegraph'), require('vega-selections'), require('vega-statistics'), require('vega-time')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'vega-util', 'vega-expression', 'vega-scale', 'vega-dataflow', 'vega-scenegraph', 'vega-selections', 'vega-statistics', 'vega-time'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.vega = {}, global.vega, global.vega, global.vega, global.vega, global.vega, global.vega, global.vega, global.vega));
5
- })(this, (function (exports, vegaUtil, vegaExpression, vegaScale, vegaDataflow, vegaScenegraph, vegaSelections, vegaStatistics, vegaTime) { 'use strict';
6
-
7
- function data(name) {
8
- const data = this.context.data[name];
9
- return data ? data.values.value : [];
10
- }
11
- function indata(name, field, value) {
12
- const index = this.context.data[name]['index:' + field],
13
- entry = index ? index.value.get(value) : undefined;
14
- return entry ? entry.count : entry;
15
- }
16
- function setdata(name, tuples) {
1
+ import { truthy, hasOwnProperty, error, stringValue, isString, isFunction, extend, isArray, isObject, field, ascending, isRegExp, peek, identity, array as array$1, zoomSymlog, zoomPow, zoomLog, zoomLinear, panSymlog, panPow, panLog, panLinear, clampRange, utcquarter, quarter, truncate, inrange, span, pad, lerp, flush, toString, toNumber, toBoolean, isNumber, isDate, isBoolean, extent, toDate } from 'vega-util';
2
+ import { Literal, codegenExpression, constants, functions, parseExpression, CallExpression } from 'vega-expression';
3
+ import { isRegisteredScale, bandSpace, scale as scale$1, scaleFraction } from 'vega-scale';
4
+ import { geoBounds as geoBounds$1, geoCentroid as geoCentroid$1, geoArea as geoArea$1 } from 'd3-geo';
5
+ import { rgb, hsl, hcl, lab } from 'd3-color';
6
+ import { isTuple } from 'vega-dataflow';
7
+ import { Gradient, pathRender, pathParse, Bounds, intersect as intersect$1 } from 'vega-scenegraph';
8
+ import { selectionVisitor, selectionTest, selectionIdTest, selectionResolve, selectionTuples } from 'vega-selections';
9
+ import { sampleUniform, sampleLogNormal, sampleNormal, quantileUniform, quantileLogNormal, quantileNormal, densityUniform, densityLogNormal, densityNormal, cumulativeUniform, cumulativeLogNormal, cumulativeNormal, random } from 'vega-statistics';
10
+ import { utcdayofyear, dayofyear, utcweek, week, timeUnitSpecifier, timeSequence, timeOffset, utcSequence, utcOffset } from 'vega-time';
11
+ import { range as range$1 } from 'd3-array';
12
+
13
+ function data(name) {
14
+ const data = this.context.data[name];
15
+ return data ? data.values.value : [];
16
+ }
17
+ function indata(name, field, value) {
18
+ const index = this.context.data[name]['index:' + field],
19
+ entry = index ? index.value.get(value) : undefined;
20
+ return entry ? entry.count : entry;
21
+ }
22
+ function setdata(name, tuples) {
23
+ const df = this.context.dataflow,
24
+ data = this.context.data[name],
25
+ input = data.input;
26
+ df.pulse(input, df.changeset().remove(truthy).insert(tuples));
27
+ return 1;
28
+ }
29
+
30
+ function encode (item, name, retval) {
31
+ if (item) {
17
32
  const df = this.context.dataflow,
18
- data = this.context.data[name],
19
- input = data.input;
20
- df.pulse(input, df.changeset().remove(vegaUtil.truthy).insert(tuples));
21
- return 1;
22
- }
23
-
24
- function encode (item, name, retval) {
25
- if (item) {
26
- const df = this.context.dataflow,
27
- target = item.mark.source;
28
- df.pulse(target, df.changeset().encode(item, name));
29
- }
30
- return retval !== undefined ? retval : item;
31
- }
32
-
33
- const wrap = method => function (value, spec) {
34
- const locale = this.context.dataflow.locale();
35
- return value === null ? 'null' : locale[method](spec)(value);
36
- };
37
- const format = wrap('format');
38
- const timeFormat = wrap('timeFormat');
39
- const utcFormat = wrap('utcFormat');
40
- const timeParse = wrap('timeParse');
41
- const utcParse = wrap('utcParse');
42
- const dateObj = new Date(2000, 0, 1);
43
- function time(month, day, specifier) {
44
- if (!Number.isInteger(month) || !Number.isInteger(day)) return '';
45
- dateObj.setYear(2000);
46
- dateObj.setMonth(month);
47
- dateObj.setDate(day);
48
- return timeFormat.call(this, dateObj, specifier);
49
- }
50
- function monthFormat(month) {
51
- return time.call(this, month, 1, '%B');
52
- }
53
- function monthAbbrevFormat(month) {
54
- return time.call(this, month, 1, '%b');
55
- }
56
- function dayFormat(day) {
57
- return time.call(this, 0, 2 + day, '%A');
58
- }
59
- function dayAbbrevFormat(day) {
60
- return time.call(this, 0, 2 + day, '%a');
61
- }
62
-
63
- const DataPrefix = ':';
64
- const IndexPrefix = '@';
65
- const ScalePrefix = '%';
66
- const SignalPrefix = '$';
67
-
68
- function dataVisitor(name, args, scope, params) {
69
- if (args[0].type !== vegaExpression.Literal) {
70
- vegaUtil.error('First argument to data functions must be a string literal.');
71
- }
72
- const data = args[0].value,
73
- dataName = DataPrefix + data;
74
- if (!vegaUtil.hasOwnProperty(dataName, params)) {
75
- try {
76
- params[dataName] = scope.getData(data).tuplesRef();
77
- } catch (err) {
78
- // if data set does not exist, there's nothing to track
79
- }
80
- }
81
- }
82
- function indataVisitor(name, args, scope, params) {
83
- if (args[0].type !== vegaExpression.Literal) vegaUtil.error('First argument to indata must be a string literal.');
84
- if (args[1].type !== vegaExpression.Literal) vegaUtil.error('Second argument to indata must be a string literal.');
85
- const data = args[0].value,
86
- field = args[1].value,
87
- indexName = IndexPrefix + field;
88
- if (!vegaUtil.hasOwnProperty(indexName, params)) {
89
- params[indexName] = scope.getData(data).indataRef(scope, field);
90
- }
91
- }
92
- function scaleVisitor(name, args, scope, params) {
93
- if (args[0].type === vegaExpression.Literal) {
94
- // add scale dependency
95
- addScaleDependency(scope, params, args[0].value);
96
- } else {
97
- // indirect scale lookup; add all scales as parameters
98
- for (name in scope.scales) {
99
- addScaleDependency(scope, params, name);
100
- }
101
- }
102
- }
103
- function addScaleDependency(scope, params, name) {
104
- const scaleName = ScalePrefix + name;
105
- if (!vegaUtil.hasOwnProperty(params, scaleName)) {
106
- try {
107
- params[scaleName] = scope.scaleRef(name);
108
- } catch (err) {
109
- // TODO: error handling? warning?
110
- }
111
- }
112
- }
113
-
114
- /**
115
- * Name must be a string. Return undefined if the scale is not registered.
116
- */
117
- function getScale(name, ctx) {
118
- if (vegaUtil.isString(name)) {
119
- const maybeScale = ctx.scales[name];
120
- return maybeScale && vegaScale.isRegisteredScale(maybeScale.value) ? maybeScale.value : undefined;
121
- }
122
- return undefined;
123
- }
124
- function internalScaleFunctions(codegen, fnctx, visitors) {
125
- // add helper method to the 'this' expression function context
126
- fnctx.__bandwidth = s => s && s.bandwidth ? s.bandwidth() : 0;
127
-
128
- // register AST visitors for internal scale functions
129
- visitors._bandwidth = scaleVisitor;
130
- visitors._range = scaleVisitor;
131
- visitors._scale = scaleVisitor;
132
-
133
- // resolve scale reference directly to the signal hash argument
134
- const ref = arg => '_[' + (arg.type === vegaExpression.Literal ? vegaUtil.stringValue(ScalePrefix + arg.value) : vegaUtil.stringValue(ScalePrefix) + '+' + codegen(arg)) + ']';
135
-
136
- // define and return internal scale function code generators
137
- // these internal functions are called by mark encoders
138
- return {
139
- _bandwidth: args => `this.__bandwidth(${ref(args[0])})`,
140
- _range: args => `${ref(args[0])}.range()`,
141
- _scale: args => `${ref(args[0])}(${codegen(args[1])})`
142
- };
143
- }
144
-
145
- // https://github.com/python/cpython/blob/a74eea238f5baba15797e2e8b570d153bc8690a7/Modules/mathmodule.c#L1423
146
- class Adder {
147
- constructor() {
148
- this._partials = new Float64Array(32);
149
- this._n = 0;
150
- }
151
- add(x) {
152
- const p = this._partials;
153
- let i = 0;
154
- for (let j = 0; j < this._n && j < 32; j++) {
155
- const y = p[j],
156
- hi = x + y,
157
- lo = Math.abs(x) < Math.abs(y) ? x - (hi - y) : y - (hi - x);
158
- if (lo) p[i++] = lo;
159
- x = hi;
160
- }
161
- p[i] = x;
162
- this._n = i + 1;
163
- return this;
164
- }
165
- valueOf() {
166
- const p = this._partials;
167
- let n = this._n,
168
- x,
169
- y,
170
- lo,
171
- hi = 0;
172
- if (n > 0) {
173
- hi = p[--n];
174
- while (n > 0) {
175
- x = hi;
176
- y = p[--n];
177
- hi = x + y;
178
- lo = y - (hi - x);
179
- if (lo) break;
180
- }
181
- if (n > 0 && (lo < 0 && p[n - 1] < 0 || lo > 0 && p[n - 1] > 0)) {
182
- y = lo * 2;
183
- x = hi + y;
184
- if (y == x - hi) hi = x;
185
- }
186
- }
187
- return hi;
188
- }
189
- }
190
-
191
- function range$2(start, stop, step) {
192
- start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;
193
- var i = -1,
194
- n = Math.max(0, Math.ceil((stop - start) / step)) | 0,
195
- range = new Array(n);
196
- while (++i < n) {
197
- range[i] = start + i * step;
198
- }
199
- return range;
200
- }
201
-
202
- var epsilon = 1e-6;
203
- var epsilon2 = 1e-12;
204
- var pi = Math.PI;
205
- var halfPi = pi / 2;
206
- var quarterPi = pi / 4;
207
- var tau = pi * 2;
208
- var degrees$1 = 180 / pi;
209
- var radians$1 = pi / 180;
210
- var abs = Math.abs;
211
- var atan2 = Math.atan2;
212
- var cos = Math.cos;
213
- var hypot = Math.hypot;
214
- var sin = Math.sin;
215
- var sqrt = Math.sqrt;
216
- function asin(x) {
217
- return x > 1 ? halfPi : x < -1 ? -halfPi : Math.asin(x);
218
- }
219
-
220
- function noop() {}
221
-
222
- function streamGeometry(geometry, stream) {
223
- if (geometry && streamGeometryType.hasOwnProperty(geometry.type)) {
224
- streamGeometryType[geometry.type](geometry, stream);
225
- }
226
- }
227
- var streamObjectType = {
228
- Feature: function (object, stream) {
229
- streamGeometry(object.geometry, stream);
230
- },
231
- FeatureCollection: function (object, stream) {
232
- var features = object.features,
233
- i = -1,
234
- n = features.length;
235
- while (++i < n) streamGeometry(features[i].geometry, stream);
236
- }
237
- };
238
- var streamGeometryType = {
239
- Sphere: function (object, stream) {
240
- stream.sphere();
241
- },
242
- Point: function (object, stream) {
243
- object = object.coordinates;
244
- stream.point(object[0], object[1], object[2]);
245
- },
246
- MultiPoint: function (object, stream) {
247
- var coordinates = object.coordinates,
248
- i = -1,
249
- n = coordinates.length;
250
- while (++i < n) object = coordinates[i], stream.point(object[0], object[1], object[2]);
251
- },
252
- LineString: function (object, stream) {
253
- streamLine(object.coordinates, stream, 0);
254
- },
255
- MultiLineString: function (object, stream) {
256
- var coordinates = object.coordinates,
257
- i = -1,
258
- n = coordinates.length;
259
- while (++i < n) streamLine(coordinates[i], stream, 0);
260
- },
261
- Polygon: function (object, stream) {
262
- streamPolygon(object.coordinates, stream);
263
- },
264
- MultiPolygon: function (object, stream) {
265
- var coordinates = object.coordinates,
266
- i = -1,
267
- n = coordinates.length;
268
- while (++i < n) streamPolygon(coordinates[i], stream);
269
- },
270
- GeometryCollection: function (object, stream) {
271
- var geometries = object.geometries,
272
- i = -1,
273
- n = geometries.length;
274
- while (++i < n) streamGeometry(geometries[i], stream);
275
- }
276
- };
277
- function streamLine(coordinates, stream, closed) {
278
- var i = -1,
279
- n = coordinates.length - closed,
280
- coordinate;
281
- stream.lineStart();
282
- while (++i < n) coordinate = coordinates[i], stream.point(coordinate[0], coordinate[1], coordinate[2]);
283
- stream.lineEnd();
284
- }
285
- function streamPolygon(coordinates, stream) {
286
- var i = -1,
287
- n = coordinates.length;
288
- stream.polygonStart();
289
- while (++i < n) streamLine(coordinates[i], stream, 1);
290
- stream.polygonEnd();
291
- }
292
- function geoStream (object, stream) {
293
- if (object && streamObjectType.hasOwnProperty(object.type)) {
294
- streamObjectType[object.type](object, stream);
295
- } else {
296
- streamGeometry(object, stream);
297
- }
298
- }
299
-
300
- var areaRingSum = new Adder();
301
-
302
- // hello?
303
-
304
- var areaSum = new Adder(),
305
- lambda00$2,
306
- phi00$2,
307
- lambda0$1,
308
- cosPhi0,
309
- sinPhi0;
310
- var areaStream = {
311
- point: noop,
312
- lineStart: noop,
313
- lineEnd: noop,
314
- polygonStart: function () {
315
- areaRingSum = new Adder();
316
- areaStream.lineStart = areaRingStart;
317
- areaStream.lineEnd = areaRingEnd;
318
- },
319
- polygonEnd: function () {
320
- var areaRing = +areaRingSum;
321
- areaSum.add(areaRing < 0 ? tau + areaRing : areaRing);
322
- this.lineStart = this.lineEnd = this.point = noop;
323
- },
324
- sphere: function () {
325
- areaSum.add(tau);
326
- }
327
- };
328
- function areaRingStart() {
329
- areaStream.point = areaPointFirst;
330
- }
331
- function areaRingEnd() {
332
- areaPoint(lambda00$2, phi00$2);
333
- }
334
- function areaPointFirst(lambda, phi) {
335
- areaStream.point = areaPoint;
336
- lambda00$2 = lambda, phi00$2 = phi;
337
- lambda *= radians$1, phi *= radians$1;
338
- lambda0$1 = lambda, cosPhi0 = cos(phi = phi / 2 + quarterPi), sinPhi0 = sin(phi);
339
- }
340
- function areaPoint(lambda, phi) {
341
- lambda *= radians$1, phi *= radians$1;
342
- phi = phi / 2 + quarterPi; // half the angular distance from south pole
343
-
344
- // Spherical excess E for a spherical triangle with vertices: south pole,
345
- // previous point, current point. Uses a formula derived from Cagnoli’s
346
- // theorem. See Todhunter, Spherical Trig. (1871), Sec. 103, Eq. (2).
347
- var dLambda = lambda - lambda0$1,
348
- sdLambda = dLambda >= 0 ? 1 : -1,
349
- adLambda = sdLambda * dLambda,
350
- cosPhi = cos(phi),
351
- sinPhi = sin(phi),
352
- k = sinPhi0 * sinPhi,
353
- u = cosPhi0 * cosPhi + k * cos(adLambda),
354
- v = k * sdLambda * sin(adLambda);
355
- areaRingSum.add(atan2(v, u));
356
-
357
- // Advance the previous points.
358
- lambda0$1 = lambda, cosPhi0 = cosPhi, sinPhi0 = sinPhi;
359
- }
360
- function area (object) {
361
- areaSum = new Adder();
362
- geoStream(object, areaStream);
363
- return areaSum * 2;
364
- }
365
-
366
- function spherical(cartesian) {
367
- return [atan2(cartesian[1], cartesian[0]), asin(cartesian[2])];
368
- }
369
- function cartesian(spherical) {
370
- var lambda = spherical[0],
371
- phi = spherical[1],
372
- cosPhi = cos(phi);
373
- return [cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi)];
374
- }
375
- function cartesianCross(a, b) {
376
- return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
377
- }
378
-
379
- // TODO return d
380
- function cartesianNormalizeInPlace(d) {
381
- var l = sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
382
- d[0] /= l, d[1] /= l, d[2] /= l;
383
- }
384
-
385
- var lambda0, phi0, lambda1, phi1,
386
- // bounds
387
- lambda2,
388
- // previous lambda-coordinate
389
- lambda00$1, phi00$1,
390
- // first point
391
- p0,
392
- // previous 3D point
393
- deltaSum, ranges, range$1;
394
- var boundsStream = {
395
- point: boundsPoint,
396
- lineStart: boundsLineStart,
397
- lineEnd: boundsLineEnd,
398
- polygonStart: function () {
399
- boundsStream.point = boundsRingPoint;
400
- boundsStream.lineStart = boundsRingStart;
401
- boundsStream.lineEnd = boundsRingEnd;
402
- deltaSum = new Adder();
403
- areaStream.polygonStart();
404
- },
405
- polygonEnd: function () {
406
- areaStream.polygonEnd();
407
- boundsStream.point = boundsPoint;
408
- boundsStream.lineStart = boundsLineStart;
409
- boundsStream.lineEnd = boundsLineEnd;
410
- if (areaRingSum < 0) lambda0 = -(lambda1 = 180), phi0 = -(phi1 = 90);else if (deltaSum > epsilon) phi1 = 90;else if (deltaSum < -1e-6) phi0 = -90;
411
- range$1[0] = lambda0, range$1[1] = lambda1;
412
- },
413
- sphere: function () {
414
- lambda0 = -(lambda1 = 180), phi0 = -(phi1 = 90);
415
- }
416
- };
417
- function boundsPoint(lambda, phi) {
418
- ranges.push(range$1 = [lambda0 = lambda, lambda1 = lambda]);
419
- if (phi < phi0) phi0 = phi;
420
- if (phi > phi1) phi1 = phi;
421
- }
422
- function linePoint(lambda, phi) {
423
- var p = cartesian([lambda * radians$1, phi * radians$1]);
424
- if (p0) {
425
- var normal = cartesianCross(p0, p),
426
- equatorial = [normal[1], -normal[0], 0],
427
- inflection = cartesianCross(equatorial, normal);
428
- cartesianNormalizeInPlace(inflection);
429
- inflection = spherical(inflection);
430
- var delta = lambda - lambda2,
431
- sign = delta > 0 ? 1 : -1,
432
- lambdai = inflection[0] * degrees$1 * sign,
433
- phii,
434
- antimeridian = abs(delta) > 180;
435
- if (antimeridian ^ (sign * lambda2 < lambdai && lambdai < sign * lambda)) {
436
- phii = inflection[1] * degrees$1;
437
- if (phii > phi1) phi1 = phii;
438
- } else if (lambdai = (lambdai + 360) % 360 - 180, antimeridian ^ (sign * lambda2 < lambdai && lambdai < sign * lambda)) {
439
- phii = -inflection[1] * degrees$1;
440
- if (phii < phi0) phi0 = phii;
441
- } else {
442
- if (phi < phi0) phi0 = phi;
443
- if (phi > phi1) phi1 = phi;
444
- }
445
- if (antimeridian) {
446
- if (lambda < lambda2) {
447
- if (angle(lambda0, lambda) > angle(lambda0, lambda1)) lambda1 = lambda;
448
- } else {
449
- if (angle(lambda, lambda1) > angle(lambda0, lambda1)) lambda0 = lambda;
450
- }
451
- } else {
452
- if (lambda1 >= lambda0) {
453
- if (lambda < lambda0) lambda0 = lambda;
454
- if (lambda > lambda1) lambda1 = lambda;
455
- } else {
456
- if (lambda > lambda2) {
457
- if (angle(lambda0, lambda) > angle(lambda0, lambda1)) lambda1 = lambda;
458
- } else {
459
- if (angle(lambda, lambda1) > angle(lambda0, lambda1)) lambda0 = lambda;
460
- }
461
- }
462
- }
463
- } else {
464
- ranges.push(range$1 = [lambda0 = lambda, lambda1 = lambda]);
465
- }
466
- if (phi < phi0) phi0 = phi;
467
- if (phi > phi1) phi1 = phi;
468
- p0 = p, lambda2 = lambda;
469
- }
470
- function boundsLineStart() {
471
- boundsStream.point = linePoint;
472
- }
473
- function boundsLineEnd() {
474
- range$1[0] = lambda0, range$1[1] = lambda1;
475
- boundsStream.point = boundsPoint;
476
- p0 = null;
477
- }
478
- function boundsRingPoint(lambda, phi) {
479
- if (p0) {
480
- var delta = lambda - lambda2;
481
- deltaSum.add(abs(delta) > 180 ? delta + (delta > 0 ? 360 : -360) : delta);
482
- } else {
483
- lambda00$1 = lambda, phi00$1 = phi;
484
- }
485
- areaStream.point(lambda, phi);
486
- linePoint(lambda, phi);
487
- }
488
- function boundsRingStart() {
489
- areaStream.lineStart();
490
- }
491
- function boundsRingEnd() {
492
- boundsRingPoint(lambda00$1, phi00$1);
493
- areaStream.lineEnd();
494
- if (abs(deltaSum) > epsilon) lambda0 = -(lambda1 = 180);
495
- range$1[0] = lambda0, range$1[1] = lambda1;
496
- p0 = null;
497
- }
498
-
499
- // Finds the left-right distance between two longitudes.
500
- // This is almost the same as (lambda1 - lambda0 + 360°) % 360°, except that we want
501
- // the distance between ±180° to be 360°.
502
- function angle(lambda0, lambda1) {
503
- return (lambda1 -= lambda0) < 0 ? lambda1 + 360 : lambda1;
504
- }
505
- function rangeCompare(a, b) {
506
- return a[0] - b[0];
507
- }
508
- function rangeContains(range, x) {
509
- return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x;
510
- }
511
- function bounds (feature) {
512
- var i, n, a, b, merged, deltaMax, delta;
513
- phi1 = lambda1 = -(lambda0 = phi0 = Infinity);
514
- ranges = [];
515
- geoStream(feature, boundsStream);
516
-
517
- // First, sort ranges by their minimum longitudes.
518
- if (n = ranges.length) {
519
- ranges.sort(rangeCompare);
520
-
521
- // Then, merge any ranges that overlap.
522
- for (i = 1, a = ranges[0], merged = [a]; i < n; ++i) {
523
- b = ranges[i];
524
- if (rangeContains(a, b[0]) || rangeContains(a, b[1])) {
525
- if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1];
526
- if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0];
527
- } else {
528
- merged.push(a = b);
529
- }
530
- }
531
-
532
- // Finally, find the largest gap between the merged ranges.
533
- // The final bounding box will be the inverse of this gap.
534
- for (deltaMax = -Infinity, n = merged.length - 1, i = 0, a = merged[n]; i <= n; a = b, ++i) {
535
- b = merged[i];
536
- if ((delta = angle(a[1], b[0])) > deltaMax) deltaMax = delta, lambda0 = b[0], lambda1 = a[1];
537
- }
538
- }
539
- ranges = range$1 = null;
540
- return lambda0 === Infinity || phi0 === Infinity ? [[NaN, NaN], [NaN, NaN]] : [[lambda0, phi0], [lambda1, phi1]];
541
- }
542
-
543
- var W0, W1, X0, Y0, Z0, X1, Y1, Z1, X2, Y2, Z2, lambda00, phi00,
544
- // first point
545
- x0, y0, z0; // previous point
546
-
547
- var centroidStream = {
548
- sphere: noop,
549
- point: centroidPoint,
550
- lineStart: centroidLineStart,
551
- lineEnd: centroidLineEnd,
552
- polygonStart: function () {
553
- centroidStream.lineStart = centroidRingStart;
554
- centroidStream.lineEnd = centroidRingEnd;
555
- },
556
- polygonEnd: function () {
557
- centroidStream.lineStart = centroidLineStart;
558
- centroidStream.lineEnd = centroidLineEnd;
559
- }
560
- };
561
-
562
- // Arithmetic mean of Cartesian vectors.
563
- function centroidPoint(lambda, phi) {
564
- lambda *= radians$1, phi *= radians$1;
565
- var cosPhi = cos(phi);
566
- centroidPointCartesian(cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi));
567
- }
568
- function centroidPointCartesian(x, y, z) {
569
- ++W0;
570
- X0 += (x - X0) / W0;
571
- Y0 += (y - Y0) / W0;
572
- Z0 += (z - Z0) / W0;
573
- }
574
- function centroidLineStart() {
575
- centroidStream.point = centroidLinePointFirst;
576
- }
577
- function centroidLinePointFirst(lambda, phi) {
578
- lambda *= radians$1, phi *= radians$1;
579
- var cosPhi = cos(phi);
580
- x0 = cosPhi * cos(lambda);
581
- y0 = cosPhi * sin(lambda);
582
- z0 = sin(phi);
583
- centroidStream.point = centroidLinePoint;
584
- centroidPointCartesian(x0, y0, z0);
585
- }
586
- function centroidLinePoint(lambda, phi) {
587
- lambda *= radians$1, phi *= radians$1;
588
- var cosPhi = cos(phi),
589
- x = cosPhi * cos(lambda),
590
- y = cosPhi * sin(lambda),
591
- z = sin(phi),
592
- w = atan2(sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z);
593
- W1 += w;
594
- X1 += w * (x0 + (x0 = x));
595
- Y1 += w * (y0 + (y0 = y));
596
- Z1 += w * (z0 + (z0 = z));
597
- centroidPointCartesian(x0, y0, z0);
598
- }
599
- function centroidLineEnd() {
600
- centroidStream.point = centroidPoint;
601
- }
602
-
603
- // See J. E. Brock, The Inertia Tensor for a Spherical Triangle,
604
- // J. Applied Mechanics 42, 239 (1975).
605
- function centroidRingStart() {
606
- centroidStream.point = centroidRingPointFirst;
607
- }
608
- function centroidRingEnd() {
609
- centroidRingPoint(lambda00, phi00);
610
- centroidStream.point = centroidPoint;
611
- }
612
- function centroidRingPointFirst(lambda, phi) {
613
- lambda00 = lambda, phi00 = phi;
614
- lambda *= radians$1, phi *= radians$1;
615
- centroidStream.point = centroidRingPoint;
616
- var cosPhi = cos(phi);
617
- x0 = cosPhi * cos(lambda);
618
- y0 = cosPhi * sin(lambda);
619
- z0 = sin(phi);
620
- centroidPointCartesian(x0, y0, z0);
621
- }
622
- function centroidRingPoint(lambda, phi) {
623
- lambda *= radians$1, phi *= radians$1;
624
- var cosPhi = cos(phi),
625
- x = cosPhi * cos(lambda),
626
- y = cosPhi * sin(lambda),
627
- z = sin(phi),
628
- cx = y0 * z - z0 * y,
629
- cy = z0 * x - x0 * z,
630
- cz = x0 * y - y0 * x,
631
- m = hypot(cx, cy, cz),
632
- w = asin(m),
633
- // line weight = angle
634
- v = m && -w / m; // area weight multiplier
635
- X2.add(v * cx);
636
- Y2.add(v * cy);
637
- Z2.add(v * cz);
638
- W1 += w;
639
- X1 += w * (x0 + (x0 = x));
640
- Y1 += w * (y0 + (y0 = y));
641
- Z1 += w * (z0 + (z0 = z));
642
- centroidPointCartesian(x0, y0, z0);
643
- }
644
- function centroid (object) {
645
- W0 = W1 = X0 = Y0 = Z0 = X1 = Y1 = Z1 = 0;
646
- X2 = new Adder();
647
- Y2 = new Adder();
648
- Z2 = new Adder();
649
- geoStream(object, centroidStream);
650
- var x = +X2,
651
- y = +Y2,
652
- z = +Z2,
653
- m = hypot(x, y, z);
654
-
655
- // If the area-weighted ccentroid is undefined, fall back to length-weighted ccentroid.
656
- if (m < epsilon2) {
657
- x = X1, y = Y1, z = Z1;
658
- // If the feature has zero length, fall back to arithmetic mean of point vectors.
659
- if (W1 < epsilon) x = X0, y = Y0, z = Z0;
660
- m = hypot(x, y, z);
661
- // If the feature still has an undefined ccentroid, then return.
662
- if (m < epsilon2) return [NaN, NaN];
663
- }
664
- return [atan2(y, x) * degrees$1, asin(z / m) * degrees$1];
665
- }
666
-
667
- function geoMethod(methodName, globalMethod) {
668
- return function (projection, geojson, group) {
669
- if (projection) {
670
- // projection defined, use it
671
- const p = getScale(projection, (group || this).context);
672
- return p && p.path[methodName](geojson);
673
- } else {
674
- // projection undefined, use global method
675
- return globalMethod(geojson);
676
- }
677
- };
678
- }
679
- const geoArea = geoMethod('area', area);
680
- const geoBounds = geoMethod('bounds', bounds);
681
- const geoCentroid = geoMethod('centroid', centroid);
682
- function geoScale(projection, group) {
683
- const p = getScale(projection, (group || this).context);
684
- return p && p.scale();
685
- }
686
-
687
- function inScope (item) {
688
- const group = this.context.group;
689
- let value = false;
690
- if (group) while (item) {
691
- if (item === group) {
692
- value = true;
693
- break;
694
- }
695
- item = item.mark.group;
696
- }
697
- return value;
698
- }
699
-
700
- function log(df, method, args) {
33
+ target = item.mark.source;
34
+ df.pulse(target, df.changeset().encode(item, name));
35
+ }
36
+ return retval !== undefined ? retval : item;
37
+ }
38
+
39
+ const wrap = method => function (value, spec) {
40
+ const locale = this.context.dataflow.locale();
41
+ return value === null ? 'null' : locale[method](spec)(value);
42
+ };
43
+ const format = wrap('format');
44
+ const timeFormat = wrap('timeFormat');
45
+ const utcFormat = wrap('utcFormat');
46
+ const timeParse = wrap('timeParse');
47
+ const utcParse = wrap('utcParse');
48
+ const dateObj = new Date(2000, 0, 1);
49
+ function time(month, day, specifier) {
50
+ if (!Number.isInteger(month) || !Number.isInteger(day)) return '';
51
+ dateObj.setYear(2000);
52
+ dateObj.setMonth(month);
53
+ dateObj.setDate(day);
54
+ return timeFormat.call(this, dateObj, specifier);
55
+ }
56
+ function monthFormat(month) {
57
+ return time.call(this, month, 1, '%B');
58
+ }
59
+ function monthAbbrevFormat(month) {
60
+ return time.call(this, month, 1, '%b');
61
+ }
62
+ function dayFormat(day) {
63
+ return time.call(this, 0, 2 + day, '%A');
64
+ }
65
+ function dayAbbrevFormat(day) {
66
+ return time.call(this, 0, 2 + day, '%a');
67
+ }
68
+
69
+ const DataPrefix = ':';
70
+ const IndexPrefix = '@';
71
+ const ScalePrefix = '%';
72
+ const SignalPrefix = '$';
73
+
74
+ function dataVisitor(name, args, scope, params) {
75
+ if (args[0].type !== Literal) {
76
+ error('First argument to data functions must be a string literal.');
77
+ }
78
+ const data = args[0].value,
79
+ dataName = DataPrefix + data;
80
+ if (!hasOwnProperty(dataName, params)) {
701
81
  try {
702
- df[method].apply(df, ['EXPRESSION'].concat([].slice.call(args)));
82
+ params[dataName] = scope.getData(data).tuplesRef();
703
83
  } catch (err) {
704
- df.warn(err);
705
- }
706
- return args[args.length - 1];
707
- }
708
- function warn() {
709
- return log(this.context.dataflow, 'warn', arguments);
710
- }
711
- function info() {
712
- return log(this.context.dataflow, 'info', arguments);
713
- }
714
- function debug() {
715
- return log(this.context.dataflow, 'debug', arguments);
716
- }
717
-
718
- function define (constructor, factory, prototype) {
719
- constructor.prototype = factory.prototype = prototype;
720
- prototype.constructor = constructor;
721
- }
722
- function extend(parent, definition) {
723
- var prototype = Object.create(parent.prototype);
724
- for (var key in definition) prototype[key] = definition[key];
725
- return prototype;
726
- }
727
-
728
- function Color() {}
729
- var darker = 0.7;
730
- var brighter = 1 / darker;
731
- var reI = "\\s*([+-]?\\d+)\\s*",
732
- reN = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",
733
- reP = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",
734
- reHex = /^#([0-9a-f]{3,8})$/,
735
- reRgbInteger = new RegExp(`^rgb\\(${reI},${reI},${reI}\\)$`),
736
- reRgbPercent = new RegExp(`^rgb\\(${reP},${reP},${reP}\\)$`),
737
- reRgbaInteger = new RegExp(`^rgba\\(${reI},${reI},${reI},${reN}\\)$`),
738
- reRgbaPercent = new RegExp(`^rgba\\(${reP},${reP},${reP},${reN}\\)$`),
739
- reHslPercent = new RegExp(`^hsl\\(${reN},${reP},${reP}\\)$`),
740
- reHslaPercent = new RegExp(`^hsla\\(${reN},${reP},${reP},${reN}\\)$`);
741
- var named = {
742
- aliceblue: 0xf0f8ff,
743
- antiquewhite: 0xfaebd7,
744
- aqua: 0x00ffff,
745
- aquamarine: 0x7fffd4,
746
- azure: 0xf0ffff,
747
- beige: 0xf5f5dc,
748
- bisque: 0xffe4c4,
749
- black: 0x000000,
750
- blanchedalmond: 0xffebcd,
751
- blue: 0x0000ff,
752
- blueviolet: 0x8a2be2,
753
- brown: 0xa52a2a,
754
- burlywood: 0xdeb887,
755
- cadetblue: 0x5f9ea0,
756
- chartreuse: 0x7fff00,
757
- chocolate: 0xd2691e,
758
- coral: 0xff7f50,
759
- cornflowerblue: 0x6495ed,
760
- cornsilk: 0xfff8dc,
761
- crimson: 0xdc143c,
762
- cyan: 0x00ffff,
763
- darkblue: 0x00008b,
764
- darkcyan: 0x008b8b,
765
- darkgoldenrod: 0xb8860b,
766
- darkgray: 0xa9a9a9,
767
- darkgreen: 0x006400,
768
- darkgrey: 0xa9a9a9,
769
- darkkhaki: 0xbdb76b,
770
- darkmagenta: 0x8b008b,
771
- darkolivegreen: 0x556b2f,
772
- darkorange: 0xff8c00,
773
- darkorchid: 0x9932cc,
774
- darkred: 0x8b0000,
775
- darksalmon: 0xe9967a,
776
- darkseagreen: 0x8fbc8f,
777
- darkslateblue: 0x483d8b,
778
- darkslategray: 0x2f4f4f,
779
- darkslategrey: 0x2f4f4f,
780
- darkturquoise: 0x00ced1,
781
- darkviolet: 0x9400d3,
782
- deeppink: 0xff1493,
783
- deepskyblue: 0x00bfff,
784
- dimgray: 0x696969,
785
- dimgrey: 0x696969,
786
- dodgerblue: 0x1e90ff,
787
- firebrick: 0xb22222,
788
- floralwhite: 0xfffaf0,
789
- forestgreen: 0x228b22,
790
- fuchsia: 0xff00ff,
791
- gainsboro: 0xdcdcdc,
792
- ghostwhite: 0xf8f8ff,
793
- gold: 0xffd700,
794
- goldenrod: 0xdaa520,
795
- gray: 0x808080,
796
- green: 0x008000,
797
- greenyellow: 0xadff2f,
798
- grey: 0x808080,
799
- honeydew: 0xf0fff0,
800
- hotpink: 0xff69b4,
801
- indianred: 0xcd5c5c,
802
- indigo: 0x4b0082,
803
- ivory: 0xfffff0,
804
- khaki: 0xf0e68c,
805
- lavender: 0xe6e6fa,
806
- lavenderblush: 0xfff0f5,
807
- lawngreen: 0x7cfc00,
808
- lemonchiffon: 0xfffacd,
809
- lightblue: 0xadd8e6,
810
- lightcoral: 0xf08080,
811
- lightcyan: 0xe0ffff,
812
- lightgoldenrodyellow: 0xfafad2,
813
- lightgray: 0xd3d3d3,
814
- lightgreen: 0x90ee90,
815
- lightgrey: 0xd3d3d3,
816
- lightpink: 0xffb6c1,
817
- lightsalmon: 0xffa07a,
818
- lightseagreen: 0x20b2aa,
819
- lightskyblue: 0x87cefa,
820
- lightslategray: 0x778899,
821
- lightslategrey: 0x778899,
822
- lightsteelblue: 0xb0c4de,
823
- lightyellow: 0xffffe0,
824
- lime: 0x00ff00,
825
- limegreen: 0x32cd32,
826
- linen: 0xfaf0e6,
827
- magenta: 0xff00ff,
828
- maroon: 0x800000,
829
- mediumaquamarine: 0x66cdaa,
830
- mediumblue: 0x0000cd,
831
- mediumorchid: 0xba55d3,
832
- mediumpurple: 0x9370db,
833
- mediumseagreen: 0x3cb371,
834
- mediumslateblue: 0x7b68ee,
835
- mediumspringgreen: 0x00fa9a,
836
- mediumturquoise: 0x48d1cc,
837
- mediumvioletred: 0xc71585,
838
- midnightblue: 0x191970,
839
- mintcream: 0xf5fffa,
840
- mistyrose: 0xffe4e1,
841
- moccasin: 0xffe4b5,
842
- navajowhite: 0xffdead,
843
- navy: 0x000080,
844
- oldlace: 0xfdf5e6,
845
- olive: 0x808000,
846
- olivedrab: 0x6b8e23,
847
- orange: 0xffa500,
848
- orangered: 0xff4500,
849
- orchid: 0xda70d6,
850
- palegoldenrod: 0xeee8aa,
851
- palegreen: 0x98fb98,
852
- paleturquoise: 0xafeeee,
853
- palevioletred: 0xdb7093,
854
- papayawhip: 0xffefd5,
855
- peachpuff: 0xffdab9,
856
- peru: 0xcd853f,
857
- pink: 0xffc0cb,
858
- plum: 0xdda0dd,
859
- powderblue: 0xb0e0e6,
860
- purple: 0x800080,
861
- rebeccapurple: 0x663399,
862
- red: 0xff0000,
863
- rosybrown: 0xbc8f8f,
864
- royalblue: 0x4169e1,
865
- saddlebrown: 0x8b4513,
866
- salmon: 0xfa8072,
867
- sandybrown: 0xf4a460,
868
- seagreen: 0x2e8b57,
869
- seashell: 0xfff5ee,
870
- sienna: 0xa0522d,
871
- silver: 0xc0c0c0,
872
- skyblue: 0x87ceeb,
873
- slateblue: 0x6a5acd,
874
- slategray: 0x708090,
875
- slategrey: 0x708090,
876
- snow: 0xfffafa,
877
- springgreen: 0x00ff7f,
878
- steelblue: 0x4682b4,
879
- tan: 0xd2b48c,
880
- teal: 0x008080,
881
- thistle: 0xd8bfd8,
882
- tomato: 0xff6347,
883
- turquoise: 0x40e0d0,
884
- violet: 0xee82ee,
885
- wheat: 0xf5deb3,
886
- white: 0xffffff,
887
- whitesmoke: 0xf5f5f5,
888
- yellow: 0xffff00,
889
- yellowgreen: 0x9acd32
84
+ // if data set does not exist, there's nothing to track
85
+ }
86
+ }
87
+ }
88
+ function indataVisitor(name, args, scope, params) {
89
+ if (args[0].type !== Literal) error('First argument to indata must be a string literal.');
90
+ if (args[1].type !== Literal) error('Second argument to indata must be a string literal.');
91
+ const data = args[0].value,
92
+ field = args[1].value,
93
+ indexName = IndexPrefix + field;
94
+ if (!hasOwnProperty(indexName, params)) {
95
+ params[indexName] = scope.getData(data).indataRef(scope, field);
96
+ }
97
+ }
98
+ function scaleVisitor(name, args, scope, params) {
99
+ if (args[0].type === Literal) {
100
+ // add scale dependency
101
+ addScaleDependency(scope, params, args[0].value);
102
+ } else {
103
+ // indirect scale lookup; add all scales as parameters
104
+ for (name in scope.scales) {
105
+ addScaleDependency(scope, params, name);
106
+ }
107
+ }
108
+ }
109
+ function addScaleDependency(scope, params, name) {
110
+ const scaleName = ScalePrefix + name;
111
+ if (!hasOwnProperty(params, scaleName)) {
112
+ try {
113
+ params[scaleName] = scope.scaleRef(name);
114
+ } catch (err) {
115
+ // TODO: error handling? warning?
116
+ }
117
+ }
118
+ }
119
+
120
+ /**
121
+ * nameOrFunction must be a string or function that was registered.
122
+ * Return undefined if scale is not recognized.
123
+ */
124
+ function getScale(nameOrFunction, ctx) {
125
+ if (isString(nameOrFunction)) {
126
+ const maybeScale = ctx.scales[nameOrFunction];
127
+ return maybeScale && isRegisteredScale(maybeScale.value) ? maybeScale.value : undefined;
128
+ } else if (isFunction(nameOrFunction)) {
129
+ return isRegisteredScale(nameOrFunction) ? nameOrFunction : undefined;
130
+ }
131
+ return undefined;
132
+ }
133
+ function internalScaleFunctions(codegen, fnctx, visitors) {
134
+ // add helper method to the 'this' expression function context
135
+ fnctx.__bandwidth = s => s && s.bandwidth ? s.bandwidth() : 0;
136
+
137
+ // register AST visitors for internal scale functions
138
+ visitors._bandwidth = scaleVisitor;
139
+ visitors._range = scaleVisitor;
140
+ visitors._scale = scaleVisitor;
141
+
142
+ // resolve scale reference directly to the signal hash argument
143
+ const ref = arg => '_[' + (arg.type === Literal ? stringValue(ScalePrefix + arg.value) : stringValue(ScalePrefix) + '+' + codegen(arg)) + ']';
144
+
145
+ // define and return internal scale function code generators
146
+ // these internal functions are called by mark encoders
147
+ return {
148
+ _bandwidth: args => `this.__bandwidth(${ref(args[0])})`,
149
+ _range: args => `${ref(args[0])}.range()`,
150
+ _scale: args => `${ref(args[0])}(${codegen(args[1])})`
890
151
  };
891
- define(Color, color, {
892
- copy(channels) {
893
- return Object.assign(new this.constructor(), this, channels);
894
- },
895
- displayable() {
896
- return this.rgb().displayable();
897
- },
898
- hex: color_formatHex,
899
- // Deprecated! Use color.formatHex.
900
- formatHex: color_formatHex,
901
- formatHex8: color_formatHex8,
902
- formatHsl: color_formatHsl,
903
- formatRgb: color_formatRgb,
904
- toString: color_formatRgb
905
- });
906
- function color_formatHex() {
907
- return this.rgb().formatHex();
908
- }
909
- function color_formatHex8() {
910
- return this.rgb().formatHex8();
911
- }
912
- function color_formatHsl() {
913
- return hslConvert(this).formatHsl();
914
- }
915
- function color_formatRgb() {
916
- return this.rgb().formatRgb();
917
- }
918
- function color(format) {
919
- var m, l;
920
- format = (format + "").trim().toLowerCase();
921
- return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) // #ff0000
922
- : l === 3 ? new Rgb(m >> 8 & 0xf | m >> 4 & 0xf0, m >> 4 & 0xf | m & 0xf0, (m & 0xf) << 4 | m & 0xf, 1) // #f00
923
- : l === 8 ? rgba(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000
924
- : l === 4 ? rgba(m >> 12 & 0xf | m >> 8 & 0xf0, m >> 8 & 0xf | m >> 4 & 0xf0, m >> 4 & 0xf | m & 0xf0, ((m & 0xf) << 4 | m & 0xf) / 0xff) // #f000
925
- : null // invalid hex
926
- ) : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
927
- : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)
928
- : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
929
- : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)
930
- : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
931
- : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)
932
- : named.hasOwnProperty(format) ? rgbn(named[format]) // eslint-disable-line no-prototype-builtins
933
- : format === "transparent" ? new Rgb(NaN, NaN, NaN, 0) : null;
934
- }
935
- function rgbn(n) {
936
- return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);
937
- }
938
- function rgba(r, g, b, a) {
939
- if (a <= 0) r = g = b = NaN;
940
- return new Rgb(r, g, b, a);
941
- }
942
- function rgbConvert(o) {
943
- if (!(o instanceof Color)) o = color(o);
944
- if (!o) return new Rgb();
945
- o = o.rgb();
946
- return new Rgb(o.r, o.g, o.b, o.opacity);
947
- }
948
- function rgb(r, g, b, opacity) {
949
- return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
950
- }
951
- function Rgb(r, g, b, opacity) {
952
- this.r = +r;
953
- this.g = +g;
954
- this.b = +b;
955
- this.opacity = +opacity;
956
- }
957
- define(Rgb, rgb, extend(Color, {
958
- brighter(k) {
959
- k = k == null ? brighter : Math.pow(brighter, k);
960
- return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
961
- },
962
- darker(k) {
963
- k = k == null ? darker : Math.pow(darker, k);
964
- return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
965
- },
966
- rgb() {
967
- return this;
968
- },
969
- clamp() {
970
- return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity));
971
- },
972
- displayable() {
973
- return -0.5 <= this.r && this.r < 255.5 && -0.5 <= this.g && this.g < 255.5 && -0.5 <= this.b && this.b < 255.5 && 0 <= this.opacity && this.opacity <= 1;
974
- },
975
- hex: rgb_formatHex,
976
- // Deprecated! Use color.formatHex.
977
- formatHex: rgb_formatHex,
978
- formatHex8: rgb_formatHex8,
979
- formatRgb: rgb_formatRgb,
980
- toString: rgb_formatRgb
981
- }));
982
- function rgb_formatHex() {
983
- return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}`;
984
- }
985
- function rgb_formatHex8() {
986
- return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}${hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`;
987
- }
988
- function rgb_formatRgb() {
989
- const a = clampa(this.opacity);
990
- return `${a === 1 ? "rgb(" : "rgba("}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a === 1 ? ")" : `, ${a})`}`;
991
- }
992
- function clampa(opacity) {
993
- return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity));
994
- }
995
- function clampi(value) {
996
- return Math.max(0, Math.min(255, Math.round(value) || 0));
997
- }
998
- function hex(value) {
999
- value = clampi(value);
1000
- return (value < 16 ? "0" : "") + value.toString(16);
1001
- }
1002
- function hsla(h, s, l, a) {
1003
- if (a <= 0) h = s = l = NaN;else if (l <= 0 || l >= 1) h = s = NaN;else if (s <= 0) h = NaN;
1004
- return new Hsl(h, s, l, a);
1005
- }
1006
- function hslConvert(o) {
1007
- if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
1008
- if (!(o instanceof Color)) o = color(o);
1009
- if (!o) return new Hsl();
1010
- if (o instanceof Hsl) return o;
1011
- o = o.rgb();
1012
- var r = o.r / 255,
1013
- g = o.g / 255,
1014
- b = o.b / 255,
1015
- min = Math.min(r, g, b),
1016
- max = Math.max(r, g, b),
1017
- h = NaN,
1018
- s = max - min,
1019
- l = (max + min) / 2;
1020
- if (s) {
1021
- if (r === max) h = (g - b) / s + (g < b) * 6;else if (g === max) h = (b - r) / s + 2;else h = (r - g) / s + 4;
1022
- s /= l < 0.5 ? max + min : 2 - max - min;
1023
- h *= 60;
152
+ }
153
+
154
+ function geoMethod(methodName, globalMethod) {
155
+ return function (projection, geojson, group) {
156
+ if (projection) {
157
+ // projection defined, use it
158
+ const p = getScale(projection, (group || this).context);
159
+ return p && p.path[methodName](geojson);
1024
160
  } else {
1025
- s = l > 0 && l < 1 ? 0 : h;
1026
- }
1027
- return new Hsl(h, s, l, o.opacity);
1028
- }
1029
- function hsl(h, s, l, opacity) {
1030
- return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
1031
- }
1032
- function Hsl(h, s, l, opacity) {
1033
- this.h = +h;
1034
- this.s = +s;
1035
- this.l = +l;
1036
- this.opacity = +opacity;
1037
- }
1038
- define(Hsl, hsl, extend(Color, {
1039
- brighter(k) {
1040
- k = k == null ? brighter : Math.pow(brighter, k);
1041
- return new Hsl(this.h, this.s, this.l * k, this.opacity);
1042
- },
1043
- darker(k) {
1044
- k = k == null ? darker : Math.pow(darker, k);
1045
- return new Hsl(this.h, this.s, this.l * k, this.opacity);
1046
- },
1047
- rgb() {
1048
- var h = this.h % 360 + (this.h < 0) * 360,
1049
- s = isNaN(h) || isNaN(this.s) ? 0 : this.s,
1050
- l = this.l,
1051
- m2 = l + (l < 0.5 ? l : 1 - l) * s,
1052
- m1 = 2 * l - m2;
1053
- return new Rgb(hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2), hsl2rgb(h, m1, m2), hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2), this.opacity);
1054
- },
1055
- clamp() {
1056
- return new Hsl(clamph(this.h), clampt(this.s), clampt(this.l), clampa(this.opacity));
1057
- },
1058
- displayable() {
1059
- return (0 <= this.s && this.s <= 1 || isNaN(this.s)) && 0 <= this.l && this.l <= 1 && 0 <= this.opacity && this.opacity <= 1;
1060
- },
1061
- formatHsl() {
1062
- const a = clampa(this.opacity);
1063
- return `${a === 1 ? "hsl(" : "hsla("}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a === 1 ? ")" : `, ${a})`}`;
1064
- }
1065
- }));
1066
- function clamph(value) {
1067
- value = (value || 0) % 360;
1068
- return value < 0 ? value + 360 : value;
1069
- }
1070
- function clampt(value) {
1071
- return Math.max(0, Math.min(1, value || 0));
1072
- }
1073
-
1074
- /* From FvD 13.37, CSS Color Module Level 3 */
1075
- function hsl2rgb(h, m1, m2) {
1076
- return (h < 60 ? m1 + (m2 - m1) * h / 60 : h < 180 ? m2 : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60 : m1) * 255;
1077
- }
1078
-
1079
- const radians = Math.PI / 180;
1080
- const degrees = 180 / Math.PI;
1081
-
1082
- // https://observablehq.com/@mbostock/lab-and-rgb
1083
- const K = 18,
1084
- Xn = 0.96422,
1085
- Yn = 1,
1086
- Zn = 0.82521,
1087
- t0 = 4 / 29,
1088
- t1 = 6 / 29,
1089
- t2 = 3 * t1 * t1,
1090
- t3 = t1 * t1 * t1;
1091
- function labConvert(o) {
1092
- if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity);
1093
- if (o instanceof Hcl) return hcl2lab(o);
1094
- if (!(o instanceof Rgb)) o = rgbConvert(o);
1095
- var r = rgb2lrgb(o.r),
1096
- g = rgb2lrgb(o.g),
1097
- b = rgb2lrgb(o.b),
1098
- y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn),
1099
- x,
1100
- z;
1101
- if (r === g && g === b) x = z = y;else {
1102
- x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn);
1103
- z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn);
1104
- }
1105
- return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity);
1106
- }
1107
- function lab(l, a, b, opacity) {
1108
- return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity);
1109
- }
1110
- function Lab(l, a, b, opacity) {
1111
- this.l = +l;
1112
- this.a = +a;
1113
- this.b = +b;
1114
- this.opacity = +opacity;
1115
- }
1116
- define(Lab, lab, extend(Color, {
1117
- brighter(k) {
1118
- return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity);
1119
- },
1120
- darker(k) {
1121
- return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity);
1122
- },
1123
- rgb() {
1124
- var y = (this.l + 16) / 116,
1125
- x = isNaN(this.a) ? y : y + this.a / 500,
1126
- z = isNaN(this.b) ? y : y - this.b / 200;
1127
- x = Xn * lab2xyz(x);
1128
- y = Yn * lab2xyz(y);
1129
- z = Zn * lab2xyz(z);
1130
- return new Rgb(lrgb2rgb(3.1338561 * x - 1.6168667 * y - 0.4906146 * z), lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z), lrgb2rgb(0.0719453 * x - 0.2289914 * y + 1.4052427 * z), this.opacity);
1131
- }
1132
- }));
1133
- function xyz2lab(t) {
1134
- return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;
1135
- }
1136
- function lab2xyz(t) {
1137
- return t > t1 ? t * t * t : t2 * (t - t0);
1138
- }
1139
- function lrgb2rgb(x) {
1140
- return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
1141
- }
1142
- function rgb2lrgb(x) {
1143
- return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
1144
- }
1145
- function hclConvert(o) {
1146
- if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity);
1147
- if (!(o instanceof Lab)) o = labConvert(o);
1148
- if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity);
1149
- var h = Math.atan2(o.b, o.a) * degrees;
1150
- return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);
1151
- }
1152
- function hcl(h, c, l, opacity) {
1153
- return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity);
1154
- }
1155
- function Hcl(h, c, l, opacity) {
1156
- this.h = +h;
1157
- this.c = +c;
1158
- this.l = +l;
1159
- this.opacity = +opacity;
1160
- }
1161
- function hcl2lab(o) {
1162
- if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity);
1163
- var h = o.h * radians;
1164
- return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);
1165
- }
1166
- define(Hcl, hcl, extend(Color, {
1167
- brighter(k) {
1168
- return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity);
1169
- },
1170
- darker(k) {
1171
- return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity);
1172
- },
1173
- rgb() {
1174
- return hcl2lab(this).rgb();
161
+ // projection undefined, use global method
162
+ return globalMethod(geojson);
1175
163
  }
1176
- }));
1177
-
1178
- // https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
1179
- function channel_luminance_value(channelValue) {
1180
- const val = channelValue / 255;
1181
- if (val <= 0.03928) {
1182
- return val / 12.92;
1183
- }
1184
- return Math.pow((val + 0.055) / 1.055, 2.4);
1185
- }
1186
- function luminance(color) {
1187
- const c = rgb(color),
1188
- r = channel_luminance_value(c.r),
1189
- g = channel_luminance_value(c.g),
1190
- b = channel_luminance_value(c.b);
1191
- return 0.2126 * r + 0.7152 * g + 0.0722 * b;
1192
- }
1193
-
1194
- // https://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef
1195
- function contrast(color1, color2) {
1196
- const lum1 = luminance(color1),
1197
- lum2 = luminance(color2),
1198
- lumL = Math.max(lum1, lum2),
1199
- lumD = Math.min(lum1, lum2);
1200
- return (lumL + 0.05) / (lumD + 0.05);
1201
- }
1202
-
1203
- function merge () {
1204
- const args = [].slice.call(arguments);
1205
- args.unshift({});
1206
- return vegaUtil.extend(...args);
1207
- }
1208
-
1209
- function equal(a, b) {
1210
- return a === b || a !== a && b !== b ? true : vegaUtil.isArray(a) ? vegaUtil.isArray(b) && a.length === b.length ? equalArray(a, b) : false : vegaUtil.isObject(a) && vegaUtil.isObject(b) ? equalObject(a, b) : false;
1211
- }
1212
- function equalArray(a, b) {
1213
- for (let i = 0, n = a.length; i < n; ++i) {
1214
- if (!equal(a[i], b[i])) return false;
1215
- }
1216
- return true;
1217
- }
1218
- function equalObject(a, b) {
1219
- for (const key in a) {
1220
- if (!equal(a[key], b[key])) return false;
1221
- }
1222
- return true;
1223
- }
1224
- function removePredicate(props) {
1225
- return _ => equalObject(props, _);
1226
- }
1227
- function modify (name, insert, remove, toggle, modify, values) {
1228
- const df = this.context.dataflow,
1229
- data = this.context.data[name],
1230
- input = data.input,
1231
- stamp = df.stamp();
1232
- let changes = data.changes,
1233
- predicate,
1234
- key;
1235
- if (df._trigger === false || !(input.value.length || insert || toggle)) {
1236
- // nothing to do!
1237
- return 0;
1238
- }
1239
- if (!changes || changes.stamp < stamp) {
1240
- data.changes = changes = df.changeset();
1241
- changes.stamp = stamp;
1242
- df.runAfter(() => {
1243
- data.modified = true;
1244
- df.pulse(input, changes).run();
1245
- }, true, 1);
1246
- }
1247
- if (remove) {
1248
- predicate = remove === true ? vegaUtil.truthy : vegaUtil.isArray(remove) || vegaDataflow.isTuple(remove) ? remove : removePredicate(remove);
164
+ };
165
+ }
166
+ const geoArea = geoMethod('area', geoArea$1);
167
+ const geoBounds = geoMethod('bounds', geoBounds$1);
168
+ const geoCentroid = geoMethod('centroid', geoCentroid$1);
169
+ function geoScale(projection, group) {
170
+ const p = getScale(projection, (group || this).context);
171
+ return p && p.scale();
172
+ }
173
+
174
+ function inScope (item) {
175
+ const group = this.context.group;
176
+ let value = false;
177
+ if (group) while (item) {
178
+ if (item === group) {
179
+ value = true;
180
+ break;
181
+ }
182
+ item = item.mark.group;
183
+ }
184
+ return value;
185
+ }
186
+
187
+ function log(df, method, args) {
188
+ try {
189
+ df[method].apply(df, ['EXPRESSION'].concat([].slice.call(args)));
190
+ } catch (err) {
191
+ df.warn(err);
192
+ }
193
+ return args[args.length - 1];
194
+ }
195
+ function warn() {
196
+ return log(this.context.dataflow, 'warn', arguments);
197
+ }
198
+ function info() {
199
+ return log(this.context.dataflow, 'info', arguments);
200
+ }
201
+ function debug() {
202
+ return log(this.context.dataflow, 'debug', arguments);
203
+ }
204
+
205
+ // https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
206
+ function channel_luminance_value(channelValue) {
207
+ const val = channelValue / 255;
208
+ if (val <= 0.03928) {
209
+ return val / 12.92;
210
+ }
211
+ return Math.pow((val + 0.055) / 1.055, 2.4);
212
+ }
213
+ function luminance(color) {
214
+ const c = rgb(color),
215
+ r = channel_luminance_value(c.r),
216
+ g = channel_luminance_value(c.g),
217
+ b = channel_luminance_value(c.b);
218
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
219
+ }
220
+
221
+ // https://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef
222
+ function contrast(color1, color2) {
223
+ const lum1 = luminance(color1),
224
+ lum2 = luminance(color2),
225
+ lumL = Math.max(lum1, lum2),
226
+ lumD = Math.min(lum1, lum2);
227
+ return (lumL + 0.05) / (lumD + 0.05);
228
+ }
229
+
230
+ function merge () {
231
+ const args = [].slice.call(arguments);
232
+ args.unshift({});
233
+ return extend(...args);
234
+ }
235
+
236
+ function equal(a, b) {
237
+ return a === b || a !== a && b !== b ? true : isArray(a) ? isArray(b) && a.length === b.length ? equalArray(a, b) : false : isObject(a) && isObject(b) ? equalObject(a, b) : false;
238
+ }
239
+ function equalArray(a, b) {
240
+ for (let i = 0, n = a.length; i < n; ++i) {
241
+ if (!equal(a[i], b[i])) return false;
242
+ }
243
+ return true;
244
+ }
245
+ function equalObject(a, b) {
246
+ for (const key in a) {
247
+ if (!equal(a[key], b[key])) return false;
248
+ }
249
+ return true;
250
+ }
251
+ function removePredicate(props) {
252
+ return _ => equalObject(props, _);
253
+ }
254
+ function modify (name, insert, remove, toggle, modify, values) {
255
+ const df = this.context.dataflow,
256
+ data = this.context.data[name],
257
+ input = data.input,
258
+ stamp = df.stamp();
259
+ let changes = data.changes,
260
+ predicate,
261
+ key;
262
+ if (df._trigger === false || !(input.value.length || insert || toggle)) {
263
+ // nothing to do!
264
+ return 0;
265
+ }
266
+ if (!changes || changes.stamp < stamp) {
267
+ data.changes = changes = df.changeset();
268
+ changes.stamp = stamp;
269
+ df.runAfter(() => {
270
+ data.modified = true;
271
+ df.pulse(input, changes).run();
272
+ }, true, 1);
273
+ }
274
+ if (remove) {
275
+ predicate = remove === true ? truthy : isArray(remove) || isTuple(remove) ? remove : removePredicate(remove);
276
+ changes.remove(predicate);
277
+ }
278
+ if (insert) {
279
+ changes.insert(insert);
280
+ }
281
+ if (toggle) {
282
+ predicate = removePredicate(toggle);
283
+ if (input.value.some(predicate)) {
1249
284
  changes.remove(predicate);
1250
- }
1251
- if (insert) {
1252
- changes.insert(insert);
1253
- }
1254
- if (toggle) {
1255
- predicate = removePredicate(toggle);
1256
- if (input.value.some(predicate)) {
1257
- changes.remove(predicate);
1258
- } else {
1259
- changes.insert(toggle);
1260
- }
1261
- }
1262
- if (modify) {
1263
- for (key in values) {
1264
- changes.modify(modify, key, values[key]);
1265
- }
1266
- }
1267
- return 1;
1268
- }
1269
-
1270
- function pinchDistance(event) {
1271
- const t = event.touches,
1272
- dx = t[0].clientX - t[1].clientX,
1273
- dy = t[0].clientY - t[1].clientY;
1274
- return Math.hypot(dx, dy);
1275
- }
1276
- function pinchAngle(event) {
1277
- const t = event.touches;
1278
- return Math.atan2(t[0].clientY - t[1].clientY, t[0].clientX - t[1].clientX);
1279
- }
1280
-
1281
- // memoize accessor functions
1282
- const accessors = {};
1283
- function pluck (data, name) {
1284
- const accessor = accessors[name] || (accessors[name] = vegaUtil.field(name));
1285
- return vegaUtil.isArray(data) ? data.map(accessor) : accessor(data);
1286
- }
1287
-
1288
- function array(seq) {
1289
- return vegaUtil.isArray(seq) || ArrayBuffer.isView(seq) ? seq : null;
1290
- }
1291
- function sequence(seq) {
1292
- return array(seq) || (vegaUtil.isString(seq) ? seq : null);
1293
- }
1294
- function join(seq, ...args) {
1295
- return array(seq).join(...args);
1296
- }
1297
- function indexof(seq, ...args) {
1298
- return sequence(seq).indexOf(...args);
1299
- }
1300
- function lastindexof(seq, ...args) {
1301
- return sequence(seq).lastIndexOf(...args);
1302
- }
1303
- function slice(seq, ...args) {
1304
- return sequence(seq).slice(...args);
1305
- }
1306
- function replace(str, pattern, repl) {
1307
- if (vegaUtil.isFunction(repl)) vegaUtil.error('Function argument passed to replace.');
1308
- if (!vegaUtil.isString(pattern) && !vegaUtil.isRegExp(pattern)) vegaUtil.error('Please pass a string or RegExp argument to replace.');
1309
- return String(str).replace(pattern, repl);
1310
- }
1311
- function reverse(seq) {
1312
- return array(seq).slice().reverse();
1313
- }
1314
- function sort(seq) {
1315
- return array(seq).slice().sort(vegaUtil.ascending);
1316
- }
1317
-
1318
- function bandspace(count, paddingInner, paddingOuter) {
1319
- return vegaScale.bandSpace(count || 0, paddingInner || 0, paddingOuter || 0);
1320
- }
1321
- function bandwidth(name, group) {
1322
- const s = getScale(name, (group || this).context);
1323
- return s && s.bandwidth ? s.bandwidth() : 0;
1324
- }
1325
- function copy(name, group) {
1326
- const s = getScale(name, (group || this).context);
1327
- return s ? s.copy() : undefined;
1328
- }
1329
- function domain(name, group) {
1330
- const s = getScale(name, (group || this).context);
1331
- return s ? s.domain() : [];
1332
- }
1333
- function invert(name, range, group) {
1334
- const s = getScale(name, (group || this).context);
1335
- return !s ? undefined : vegaUtil.isArray(range) ? (s.invertRange || s.invert)(range) : (s.invert || s.invertExtent)(range);
1336
- }
1337
- function range(name, group) {
1338
- const s = getScale(name, (group || this).context);
1339
- return s && s.range ? s.range() : [];
1340
- }
1341
- function scale(name, value, group) {
1342
- const s = getScale(name, (group || this).context);
1343
- return s ? s(value) : undefined;
1344
- }
1345
-
1346
- /**
1347
- * Passing a function is only used for for testing.
1348
- * Outside of tests, the first argument should be a string.
1349
- */
1350
- function scaleGradient (scaleOrFunction, p0, p1, count, group) {
1351
- let scale = typeof scaleOrFunction === 'string' ? getScale(scaleOrFunction, (group || this).context) : scaleOrFunction;
1352
- const gradient = vegaScenegraph.Gradient(p0, p1);
1353
- let stops = scale.domain(),
1354
- min = stops[0],
1355
- max = vegaUtil.peek(stops),
1356
- fraction = vegaUtil.identity;
1357
- if (!(max - min)) {
1358
- // expand scale if domain has zero span, fix #1479
1359
- scale = (scale.interpolator ? vegaScale.scale('sequential')().interpolator(scale.interpolator()) : vegaScale.scale('linear')().interpolate(scale.interpolate()).range(scale.range())).domain([min = 0, max = 1]);
1360
285
  } else {
1361
- fraction = vegaScale.scaleFraction(scale, min, max);
1362
- }
1363
- if (scale.ticks) {
1364
- stops = scale.ticks(+count || 15);
1365
- if (min !== stops[0]) stops.unshift(min);
1366
- if (max !== vegaUtil.peek(stops)) stops.push(max);
1367
- }
1368
- stops.forEach(_ => gradient.stop(fraction(_), scale(_)));
1369
- return gradient;
1370
- }
1371
-
1372
- function geoShape(projection, geojson, group) {
1373
- const p = getScale(projection, (group || this).context);
1374
- return function (context) {
1375
- return p ? p.path.context(context)(geojson) : '';
1376
- };
1377
- }
1378
- function pathShape(path) {
1379
- let p = null;
1380
- return function (context) {
1381
- return context ? vegaScenegraph.pathRender(context, p = p || vegaScenegraph.pathParse(path)) : path;
1382
- };
1383
- }
1384
-
1385
- const datum = d => d.data;
1386
- function treeNodes(name, context) {
1387
- const tree = data.call(context, name);
1388
- return tree.root && tree.root.lookup || {};
1389
- }
1390
- function treePath(name, source, target) {
1391
- const nodes = treeNodes(name, this),
1392
- s = nodes[source],
1393
- t = nodes[target];
1394
- return s && t ? s.path(t).map(datum) : undefined;
1395
- }
1396
- function treeAncestors(name, node) {
1397
- const n = treeNodes(name, this)[node];
1398
- return n ? n.ancestors().map(datum) : undefined;
1399
- }
1400
-
1401
- const _window = () => typeof window !== 'undefined' && window || null;
1402
- function screen() {
1403
- const w = _window();
1404
- return w ? w.screen : {};
1405
- }
1406
- function windowSize() {
1407
- const w = _window();
1408
- return w ? [w.innerWidth, w.innerHeight] : [undefined, undefined];
1409
- }
1410
- function containerSize() {
1411
- const view = this.context.dataflow,
1412
- el = view.container && view.container();
1413
- return el ? [el.clientWidth, el.clientHeight] : [undefined, undefined];
1414
- }
1415
-
1416
- function intersect (b, opt, group) {
1417
- if (!b) return [];
1418
- const [u, v] = b,
1419
- box = new vegaScenegraph.Bounds().set(u[0], u[1], v[0], v[1]),
1420
- scene = group || this.context.dataflow.scenegraph().root;
1421
- return vegaScenegraph.intersect(scene, box, filter(opt));
1422
- }
1423
- function filter(opt) {
1424
- let p = null;
1425
- if (opt) {
1426
- const types = vegaUtil.array(opt.marktype),
1427
- names = vegaUtil.array(opt.markname);
1428
- p = _ => (!types.length || types.some(t => _.marktype === t)) && (!names.length || names.some(s => _.name === s));
1429
- }
1430
- return p;
1431
- }
1432
-
1433
- /**
1434
- * Appends a new point to the lasso
1435
- *
1436
- * @param {*} lasso the lasso in pixel space
1437
- * @param {*} x the x coordinate in pixel space
1438
- * @param {*} y the y coordinate in pixel space
1439
- * @param {*} minDist the minimum distance, in pixels, that thenew point needs to be apart from the last point
1440
- * @returns a new array containing the lasso with the new point
1441
- */
1442
- function lassoAppend(lasso, x, y, minDist = 5) {
1443
- lasso = vegaUtil.array(lasso);
1444
- const last = lasso[lasso.length - 1];
1445
-
1446
- // Add point to lasso if its the first point or distance to last point exceed minDist
1447
- return last === undefined || Math.hypot(last[0] - x, last[1] - y) > minDist ? [...lasso, [x, y]] : lasso;
1448
- }
1449
-
1450
- /**
1451
- * Generates a svg path command which draws a lasso
1452
- *
1453
- * @param {*} lasso the lasso in pixel space in the form [[x,y], [x,y], ...]
1454
- * @returns the svg path command that draws the lasso
1455
- */
1456
- function lassoPath(lasso) {
1457
- return vegaUtil.array(lasso).reduce((svg, [x, y], i) => {
1458
- return svg += i == 0 ? `M ${x},${y} ` : i === lasso.length - 1 ? ' Z' : `L ${x},${y} `;
1459
- }, '');
1460
- }
1461
-
1462
- /**
1463
- * Inverts the lasso from pixel space to an array of vega scenegraph tuples
1464
- *
1465
- * @param {*} data the dataset
1466
- * @param {*} pixelLasso the lasso in pixel space, [[x,y], [x,y], ...]
1467
- * @param {*} unit the unit where the lasso is defined
1468
- *
1469
- * @returns an array of vega scenegraph tuples
1470
- */
1471
- function intersectLasso(markname, pixelLasso, unit) {
1472
- const {
1473
- x,
1474
- y,
1475
- mark
1476
- } = unit;
1477
- const bb = new vegaScenegraph.Bounds().set(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER, Number.MIN_SAFE_INTEGER);
1478
-
1479
- // Get bounding box around lasso
1480
- for (const [px, py] of pixelLasso) {
1481
- if (px < bb.x1) bb.x1 = px;
1482
- if (px > bb.x2) bb.x2 = px;
1483
- if (py < bb.y1) bb.y1 = py;
1484
- if (py > bb.y2) bb.y2 = py;
1485
- }
1486
-
1487
- // Translate bb against unit coordinates
1488
- bb.translate(x, y);
1489
- const intersection = intersect([[bb.x1, bb.y1], [bb.x2, bb.y2]], markname, mark);
1490
-
1491
- // Check every point against the lasso
1492
- return intersection.filter(tuple => pointInPolygon(tuple.x, tuple.y, pixelLasso));
1493
- }
1494
-
1495
- /**
1496
- * Performs a test if a point is inside a polygon based on the idea from
1497
- * https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html
1498
- *
1499
- * This method will not need the same start/end point since it wraps around the edges of the array
1500
- *
1501
- * @param {*} test a point to test against
1502
- * @param {*} polygon a polygon in the form [[x,y], [x,y], ...]
1503
- * @returns true if the point lies inside the polygon, false otherwise
1504
- */
1505
- function pointInPolygon(testx, testy, polygon) {
1506
- let intersections = 0;
1507
- for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
1508
- const [prevX, prevY] = polygon[j];
1509
- const [x, y] = polygon[i];
1510
-
1511
- // count intersections
1512
- if (y > testy != prevY > testy && testx < (prevX - x) * (testy - y) / (prevY - y) + x) {
1513
- intersections++;
1514
- }
1515
- }
1516
-
1517
- // point is in polygon if intersection count is odd
1518
- return intersections & 1;
1519
- }
1520
-
1521
- // Expression function context object
1522
- const functionContext = {
1523
- random() {
1524
- return vegaStatistics.random();
1525
- },
1526
- // override default
1527
- cumulativeNormal: vegaStatistics.cumulativeNormal,
1528
- cumulativeLogNormal: vegaStatistics.cumulativeLogNormal,
1529
- cumulativeUniform: vegaStatistics.cumulativeUniform,
1530
- densityNormal: vegaStatistics.densityNormal,
1531
- densityLogNormal: vegaStatistics.densityLogNormal,
1532
- densityUniform: vegaStatistics.densityUniform,
1533
- quantileNormal: vegaStatistics.quantileNormal,
1534
- quantileLogNormal: vegaStatistics.quantileLogNormal,
1535
- quantileUniform: vegaStatistics.quantileUniform,
1536
- sampleNormal: vegaStatistics.sampleNormal,
1537
- sampleLogNormal: vegaStatistics.sampleLogNormal,
1538
- sampleUniform: vegaStatistics.sampleUniform,
1539
- isArray: vegaUtil.isArray,
1540
- isBoolean: vegaUtil.isBoolean,
1541
- isDate: vegaUtil.isDate,
1542
- isDefined(_) {
1543
- return _ !== undefined;
1544
- },
1545
- isNumber: vegaUtil.isNumber,
1546
- isObject: vegaUtil.isObject,
1547
- isRegExp: vegaUtil.isRegExp,
1548
- isString: vegaUtil.isString,
1549
- isTuple: vegaDataflow.isTuple,
1550
- isValid(_) {
1551
- return _ != null && _ === _;
1552
- },
1553
- toBoolean: vegaUtil.toBoolean,
1554
- toDate(_) {
1555
- return vegaUtil.toDate(_);
1556
- },
1557
- // suppress extra arguments
1558
- toNumber: vegaUtil.toNumber,
1559
- toString: vegaUtil.toString,
1560
- indexof,
1561
- join,
1562
- lastindexof,
1563
- replace,
1564
- reverse,
1565
- sort,
1566
- slice,
1567
- flush: vegaUtil.flush,
1568
- lerp: vegaUtil.lerp,
1569
- merge,
1570
- pad: vegaUtil.pad,
1571
- peek: vegaUtil.peek,
1572
- pluck,
1573
- span: vegaUtil.span,
1574
- inrange: vegaUtil.inrange,
1575
- truncate: vegaUtil.truncate,
1576
- rgb,
1577
- lab,
1578
- hcl,
1579
- hsl,
1580
- luminance,
1581
- contrast,
1582
- sequence: range$2,
1583
- format,
1584
- utcFormat,
1585
- utcParse,
1586
- utcOffset: vegaTime.utcOffset,
1587
- utcSequence: vegaTime.utcSequence,
1588
- timeFormat,
1589
- timeParse,
1590
- timeOffset: vegaTime.timeOffset,
1591
- timeSequence: vegaTime.timeSequence,
1592
- timeUnitSpecifier: vegaTime.timeUnitSpecifier,
1593
- monthFormat,
1594
- monthAbbrevFormat,
1595
- dayFormat,
1596
- dayAbbrevFormat,
1597
- quarter: vegaUtil.quarter,
1598
- utcquarter: vegaUtil.utcquarter,
1599
- week: vegaTime.week,
1600
- utcweek: vegaTime.utcweek,
1601
- dayofyear: vegaTime.dayofyear,
1602
- utcdayofyear: vegaTime.utcdayofyear,
1603
- warn,
1604
- info,
1605
- debug,
1606
- extent(_) {
1607
- return vegaUtil.extent(_);
1608
- },
1609
- // suppress extra arguments
1610
- inScope,
1611
- intersect,
1612
- clampRange: vegaUtil.clampRange,
1613
- pinchDistance,
1614
- pinchAngle,
1615
- screen,
1616
- containerSize,
1617
- windowSize,
1618
- bandspace,
1619
- setdata,
1620
- pathShape,
1621
- panLinear: vegaUtil.panLinear,
1622
- panLog: vegaUtil.panLog,
1623
- panPow: vegaUtil.panPow,
1624
- panSymlog: vegaUtil.panSymlog,
1625
- zoomLinear: vegaUtil.zoomLinear,
1626
- zoomLog: vegaUtil.zoomLog,
1627
- zoomPow: vegaUtil.zoomPow,
1628
- zoomSymlog: vegaUtil.zoomSymlog,
1629
- encode,
1630
- modify,
1631
- lassoAppend,
1632
- lassoPath,
1633
- intersectLasso
286
+ changes.insert(toggle);
287
+ }
288
+ }
289
+ if (modify) {
290
+ for (key in values) {
291
+ changes.modify(modify, key, values[key]);
292
+ }
293
+ }
294
+ return 1;
295
+ }
296
+
297
+ function pinchDistance(event) {
298
+ const t = event.touches,
299
+ dx = t[0].clientX - t[1].clientX,
300
+ dy = t[0].clientY - t[1].clientY;
301
+ return Math.hypot(dx, dy);
302
+ }
303
+ function pinchAngle(event) {
304
+ const t = event.touches;
305
+ return Math.atan2(t[0].clientY - t[1].clientY, t[0].clientX - t[1].clientX);
306
+ }
307
+
308
+ // memoize accessor functions
309
+ const accessors = {};
310
+ function pluck (data, name) {
311
+ const accessor = accessors[name] || (accessors[name] = field(name));
312
+ return isArray(data) ? data.map(accessor) : accessor(data);
313
+ }
314
+
315
+ function array(seq) {
316
+ return isArray(seq) || ArrayBuffer.isView(seq) ? seq : null;
317
+ }
318
+ function sequence(seq) {
319
+ return array(seq) || (isString(seq) ? seq : null);
320
+ }
321
+ function join(seq) {
322
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
323
+ args[_key - 1] = arguments[_key];
324
+ }
325
+ return array(seq).join(...args);
326
+ }
327
+ function indexof(seq) {
328
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
329
+ args[_key2 - 1] = arguments[_key2];
330
+ }
331
+ return sequence(seq).indexOf(...args);
332
+ }
333
+ function lastindexof(seq) {
334
+ for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
335
+ args[_key3 - 1] = arguments[_key3];
336
+ }
337
+ return sequence(seq).lastIndexOf(...args);
338
+ }
339
+ function slice(seq) {
340
+ for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
341
+ args[_key4 - 1] = arguments[_key4];
342
+ }
343
+ return sequence(seq).slice(...args);
344
+ }
345
+ function replace(str, pattern, repl) {
346
+ if (isFunction(repl)) error('Function argument passed to replace.');
347
+ if (!isString(pattern) && !isRegExp(pattern)) error('Please pass a string or RegExp argument to replace.');
348
+ return String(str).replace(pattern, repl);
349
+ }
350
+ function reverse(seq) {
351
+ return array(seq).slice().reverse();
352
+ }
353
+ function sort(seq) {
354
+ return array(seq).slice().sort(ascending);
355
+ }
356
+
357
+ function bandspace(count, paddingInner, paddingOuter) {
358
+ return bandSpace(count || 0, paddingInner || 0, paddingOuter || 0);
359
+ }
360
+ function bandwidth(name, group) {
361
+ const s = getScale(name, (group || this).context);
362
+ return s && s.bandwidth ? s.bandwidth() : 0;
363
+ }
364
+ function copy(name, group) {
365
+ const s = getScale(name, (group || this).context);
366
+ return s ? s.copy() : undefined;
367
+ }
368
+ function domain(name, group) {
369
+ const s = getScale(name, (group || this).context);
370
+ return s ? s.domain() : [];
371
+ }
372
+ function invert(name, range, group) {
373
+ const s = getScale(name, (group || this).context);
374
+ return !s ? undefined : isArray(range) ? (s.invertRange || s.invert)(range) : (s.invert || s.invertExtent)(range);
375
+ }
376
+ function range(name, group) {
377
+ const s = getScale(name, (group || this).context);
378
+ return s && s.range ? s.range() : [];
379
+ }
380
+ function scale(name, value, group) {
381
+ const s = getScale(name, (group || this).context);
382
+ return s ? s(value) : undefined;
383
+ }
384
+
385
+ function scaleGradient (scale, p0, p1, count, group) {
386
+ scale = getScale(scale, (group || this).context);
387
+ const gradient = Gradient(p0, p1);
388
+ let stops = scale.domain(),
389
+ min = stops[0],
390
+ max = peek(stops),
391
+ fraction = identity;
392
+ if (!(max - min)) {
393
+ // expand scale if domain has zero span, fix #1479
394
+ scale = (scale.interpolator ? scale$1('sequential')().interpolator(scale.interpolator()) : scale$1('linear')().interpolate(scale.interpolate()).range(scale.range())).domain([min = 0, max = 1]);
395
+ } else {
396
+ fraction = scaleFraction(scale, min, max);
397
+ }
398
+ if (scale.ticks) {
399
+ stops = scale.ticks(+count || 15);
400
+ if (min !== stops[0]) stops.unshift(min);
401
+ if (max !== peek(stops)) stops.push(max);
402
+ }
403
+ stops.forEach(_ => gradient.stop(fraction(_), scale(_)));
404
+ return gradient;
405
+ }
406
+
407
+ function geoShape(projection, geojson, group) {
408
+ const p = getScale(projection, (group || this).context);
409
+ return function (context) {
410
+ return p ? p.path.context(context)(geojson) : '';
1634
411
  };
1635
- const eventFunctions = ['view', 'item', 'group', 'xy', 'x', 'y'],
1636
- // event functions
1637
- eventPrefix = 'event.vega.',
1638
- // event function prefix
1639
- thisPrefix = 'this.',
1640
- // function context prefix
1641
- astVisitors = {}; // AST visitors for dependency analysis
1642
-
1643
- // export code generator parameters
1644
- const codegenParams = {
1645
- forbidden: ['_'],
1646
- allowed: ['datum', 'event', 'item'],
1647
- fieldvar: 'datum',
1648
- globalvar: id => `_[${vegaUtil.stringValue(SignalPrefix + id)}]`,
1649
- functions: buildFunctions,
1650
- constants: vegaExpression.constants,
1651
- visitors: astVisitors
412
+ }
413
+ function pathShape(path) {
414
+ let p = null;
415
+ return function (context) {
416
+ return context ? pathRender(context, p = p || pathParse(path)) : path;
1652
417
  };
418
+ }
419
+
420
+ const datum = d => d.data;
421
+ function treeNodes(name, context) {
422
+ const tree = data.call(context, name);
423
+ return tree.root && tree.root.lookup || {};
424
+ }
425
+ function treePath(name, source, target) {
426
+ const nodes = treeNodes(name, this),
427
+ s = nodes[source],
428
+ t = nodes[target];
429
+ return s && t ? s.path(t).map(datum) : undefined;
430
+ }
431
+ function treeAncestors(name, node) {
432
+ const n = treeNodes(name, this)[node];
433
+ return n ? n.ancestors().map(datum) : undefined;
434
+ }
435
+
436
+ const _window = () => typeof window !== 'undefined' && window || null;
437
+ function screen() {
438
+ const w = _window();
439
+ return w ? w.screen : {};
440
+ }
441
+ function windowSize() {
442
+ const w = _window();
443
+ return w ? [w.innerWidth, w.innerHeight] : [undefined, undefined];
444
+ }
445
+ function containerSize() {
446
+ const view = this.context.dataflow,
447
+ el = view.container && view.container();
448
+ return el ? [el.clientWidth, el.clientHeight] : [undefined, undefined];
449
+ }
450
+
451
+ function intersect (b, opt, group) {
452
+ if (!b) return [];
453
+ const [u, v] = b,
454
+ box = new Bounds().set(u[0], u[1], v[0], v[1]),
455
+ scene = group || this.context.dataflow.scenegraph().root;
456
+ return intersect$1(scene, box, filter(opt));
457
+ }
458
+ function filter(opt) {
459
+ let p = null;
460
+ if (opt) {
461
+ const types = array$1(opt.marktype),
462
+ names = array$1(opt.markname);
463
+ p = _ => (!types.length || types.some(t => _.marktype === t)) && (!names.length || names.some(s => _.name === s));
464
+ }
465
+ return p;
466
+ }
467
+
468
+ /**
469
+ * Appends a new point to the lasso
470
+ *
471
+ * @param {*} lasso the lasso in pixel space
472
+ * @param {*} x the x coordinate in pixel space
473
+ * @param {*} y the y coordinate in pixel space
474
+ * @param {*} minDist the minimum distance, in pixels, that thenew point needs to be apart from the last point
475
+ * @returns a new array containing the lasso with the new point
476
+ */
477
+ function lassoAppend(lasso, x, y) {
478
+ let minDist = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 5;
479
+ lasso = array$1(lasso);
480
+ const last = lasso[lasso.length - 1];
481
+
482
+ // Add point to lasso if its the first point or distance to last point exceed minDist
483
+ return last === undefined || Math.hypot(last[0] - x, last[1] - y) > minDist ? [...lasso, [x, y]] : lasso;
484
+ }
485
+
486
+ /**
487
+ * Generates a svg path command which draws a lasso
488
+ *
489
+ * @param {*} lasso the lasso in pixel space in the form [[x,y], [x,y], ...]
490
+ * @returns the svg path command that draws the lasso
491
+ */
492
+ function lassoPath(lasso) {
493
+ return array$1(lasso).reduce((svg, _ref, i) => {
494
+ let [x, y] = _ref;
495
+ return svg += i == 0 ? `M ${x},${y} ` : i === lasso.length - 1 ? ' Z' : `L ${x},${y} `;
496
+ }, '');
497
+ }
498
+
499
+ /**
500
+ * Inverts the lasso from pixel space to an array of vega scenegraph tuples
501
+ *
502
+ * @param {*} data the dataset
503
+ * @param {*} pixelLasso the lasso in pixel space, [[x,y], [x,y], ...]
504
+ * @param {*} unit the unit where the lasso is defined
505
+ *
506
+ * @returns an array of vega scenegraph tuples
507
+ */
508
+ function intersectLasso(markname, pixelLasso, unit) {
509
+ const {
510
+ x,
511
+ y,
512
+ mark
513
+ } = unit;
514
+ const bb = new Bounds().set(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER, Number.MIN_SAFE_INTEGER);
515
+
516
+ // Get bounding box around lasso
517
+ for (const [px, py] of pixelLasso) {
518
+ if (px < bb.x1) bb.x1 = px;
519
+ if (px > bb.x2) bb.x2 = px;
520
+ if (py < bb.y1) bb.y1 = py;
521
+ if (py > bb.y2) bb.y2 = py;
522
+ }
523
+
524
+ // Translate bb against unit coordinates
525
+ bb.translate(x, y);
526
+ const intersection = intersect([[bb.x1, bb.y1], [bb.x2, bb.y2]], markname, mark);
527
+
528
+ // Check every point against the lasso
529
+ return intersection.filter(tuple => pointInPolygon(tuple.x, tuple.y, pixelLasso));
530
+ }
531
+
532
+ /**
533
+ * Performs a test if a point is inside a polygon based on the idea from
534
+ * https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html
535
+ *
536
+ * This method will not need the same start/end point since it wraps around the edges of the array
537
+ *
538
+ * @param {*} test a point to test against
539
+ * @param {*} polygon a polygon in the form [[x,y], [x,y], ...]
540
+ * @returns true if the point lies inside the polygon, false otherwise
541
+ */
542
+ function pointInPolygon(testx, testy, polygon) {
543
+ let intersections = 0;
544
+ for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
545
+ const [prevX, prevY] = polygon[j];
546
+ const [x, y] = polygon[i];
547
+
548
+ // count intersections
549
+ if (y > testy != prevY > testy && testx < (prevX - x) * (testy - y) / (prevY - y) + x) {
550
+ intersections++;
551
+ }
552
+ }
553
+
554
+ // point is in polygon if intersection count is odd
555
+ return intersections & 1;
556
+ }
557
+
558
+ // Expression function context object
559
+ const functionContext = {
560
+ random() {
561
+ return random();
562
+ },
563
+ // override default
564
+ cumulativeNormal,
565
+ cumulativeLogNormal,
566
+ cumulativeUniform,
567
+ densityNormal,
568
+ densityLogNormal,
569
+ densityUniform,
570
+ quantileNormal,
571
+ quantileLogNormal,
572
+ quantileUniform,
573
+ sampleNormal,
574
+ sampleLogNormal,
575
+ sampleUniform,
576
+ isArray,
577
+ isBoolean,
578
+ isDate,
579
+ isDefined(_) {
580
+ return _ !== undefined;
581
+ },
582
+ isNumber,
583
+ isObject,
584
+ isRegExp,
585
+ isString,
586
+ isTuple,
587
+ isValid(_) {
588
+ return _ != null && _ === _;
589
+ },
590
+ toBoolean,
591
+ toDate(_) {
592
+ return toDate(_);
593
+ },
594
+ // suppress extra arguments
595
+ toNumber,
596
+ toString,
597
+ indexof,
598
+ join,
599
+ lastindexof,
600
+ replace,
601
+ reverse,
602
+ sort,
603
+ slice,
604
+ flush,
605
+ lerp,
606
+ merge,
607
+ pad,
608
+ peek,
609
+ pluck,
610
+ span,
611
+ inrange,
612
+ truncate,
613
+ rgb,
614
+ lab,
615
+ hcl,
616
+ hsl,
617
+ luminance,
618
+ contrast,
619
+ sequence: range$1,
620
+ format,
621
+ utcFormat,
622
+ utcParse,
623
+ utcOffset,
624
+ utcSequence,
625
+ timeFormat,
626
+ timeParse,
627
+ timeOffset,
628
+ timeSequence,
629
+ timeUnitSpecifier,
630
+ monthFormat,
631
+ monthAbbrevFormat,
632
+ dayFormat,
633
+ dayAbbrevFormat,
634
+ quarter,
635
+ utcquarter,
636
+ week,
637
+ utcweek,
638
+ dayofyear,
639
+ utcdayofyear,
640
+ warn,
641
+ info,
642
+ debug,
643
+ extent(_) {
644
+ return extent(_);
645
+ },
646
+ // suppress extra arguments
647
+ inScope,
648
+ intersect,
649
+ clampRange,
650
+ pinchDistance,
651
+ pinchAngle,
652
+ screen,
653
+ containerSize,
654
+ windowSize,
655
+ bandspace,
656
+ setdata,
657
+ pathShape,
658
+ panLinear,
659
+ panLog,
660
+ panPow,
661
+ panSymlog,
662
+ zoomLinear,
663
+ zoomLog,
664
+ zoomPow,
665
+ zoomSymlog,
666
+ encode,
667
+ modify,
668
+ lassoAppend,
669
+ lassoPath,
670
+ intersectLasso
671
+ };
672
+ const eventFunctions = ['view', 'item', 'group', 'xy', 'x', 'y'],
673
+ // event functions
674
+ eventPrefix = 'event.vega.',
675
+ // event function prefix
676
+ thisPrefix = 'this.',
677
+ // function context prefix
678
+ astVisitors = {}; // AST visitors for dependency analysis
679
+
680
+ // export code generator parameters
681
+ const codegenParams = {
682
+ forbidden: ['_'],
683
+ allowed: ['datum', 'event', 'item'],
684
+ fieldvar: 'datum',
685
+ globalvar: id => `_[${stringValue(SignalPrefix + id)}]`,
686
+ functions: buildFunctions,
687
+ constants: constants,
688
+ visitors: astVisitors
689
+ };
690
+
691
+ // export code generator
692
+ const codeGenerator = codegenExpression(codegenParams);
693
+
694
+ // Build expression function registry
695
+ function buildFunctions(codegen) {
696
+ const fn = functions(codegen);
697
+ eventFunctions.forEach(name => fn[name] = eventPrefix + name);
698
+ for (const name in functionContext) {
699
+ fn[name] = thisPrefix + name;
700
+ }
701
+ extend(fn, internalScaleFunctions(codegen, functionContext, astVisitors));
702
+ return fn;
703
+ }
704
+
705
+ // Register an expression function
706
+ function expressionFunction(name, fn, visitor) {
707
+ if (arguments.length === 1) {
708
+ return functionContext[name];
709
+ }
710
+
711
+ // register with the functionContext
712
+ functionContext[name] = fn;
713
+
714
+ // if there is an astVisitor register that, too
715
+ if (visitor) astVisitors[name] = visitor;
716
+
717
+ // if the code generator has already been initialized,
718
+ // we need to also register the function with it
719
+ if (codeGenerator) codeGenerator.functions[name] = thisPrefix + name;
720
+ return this;
721
+ }
722
+
723
+ // register expression functions with ast visitors
724
+ expressionFunction('bandwidth', bandwidth, scaleVisitor);
725
+ expressionFunction('copy', copy, scaleVisitor);
726
+ expressionFunction('domain', domain, scaleVisitor);
727
+ expressionFunction('range', range, scaleVisitor);
728
+ expressionFunction('invert', invert, scaleVisitor);
729
+ expressionFunction('scale', scale, scaleVisitor);
730
+ expressionFunction('gradient', scaleGradient, scaleVisitor);
731
+ expressionFunction('geoArea', geoArea, scaleVisitor);
732
+ expressionFunction('geoBounds', geoBounds, scaleVisitor);
733
+ expressionFunction('geoCentroid', geoCentroid, scaleVisitor);
734
+ expressionFunction('geoShape', geoShape, scaleVisitor);
735
+ expressionFunction('geoScale', geoScale, scaleVisitor);
736
+ expressionFunction('indata', indata, indataVisitor);
737
+ expressionFunction('data', data, dataVisitor);
738
+ expressionFunction('treePath', treePath, dataVisitor);
739
+ expressionFunction('treeAncestors', treeAncestors, dataVisitor);
740
+
741
+ // register Vega-Lite selection functions
742
+ expressionFunction('vlSelectionTest', selectionTest, selectionVisitor);
743
+ expressionFunction('vlSelectionIdTest', selectionIdTest, selectionVisitor);
744
+ expressionFunction('vlSelectionResolve', selectionResolve, selectionVisitor);
745
+ expressionFunction('vlSelectionTuples', selectionTuples);
746
+
747
+ function parser (expr, scope) {
748
+ const params = {};
749
+
750
+ // parse the expression to an abstract syntax tree (ast)
751
+ let ast;
752
+ try {
753
+ expr = isString(expr) ? expr : stringValue(expr) + '';
754
+ ast = parseExpression(expr);
755
+ } catch (err) {
756
+ error('Expression parse error: ' + expr);
757
+ }
758
+
759
+ // analyze ast function calls for dependencies
760
+ ast.visit(node => {
761
+ if (node.type !== CallExpression) return;
762
+ const name = node.callee.name,
763
+ visit = codegenParams.visitors[name];
764
+ if (visit) visit(name, node.arguments, scope, params);
765
+ });
1653
766
 
1654
- // export code generator
1655
- const codeGenerator = vegaExpression.codegenExpression(codegenParams);
1656
-
1657
- // Build expression function registry
1658
- function buildFunctions(codegen) {
1659
- const fn = vegaExpression.functions(codegen);
1660
- eventFunctions.forEach(name => fn[name] = eventPrefix + name);
1661
- for (const name in functionContext) {
1662
- fn[name] = thisPrefix + name;
1663
- }
1664
- vegaUtil.extend(fn, internalScaleFunctions(codegen, functionContext, astVisitors));
1665
- return fn;
1666
- }
1667
-
1668
- // Register an expression function
1669
- function expressionFunction(name, fn, visitor) {
1670
- if (arguments.length === 1) {
1671
- return functionContext[name];
1672
- }
1673
-
1674
- // register with the functionContext
1675
- functionContext[name] = fn;
1676
-
1677
- // if there is an astVisitor register that, too
1678
- if (visitor) astVisitors[name] = visitor;
1679
-
1680
- // if the code generator has already been initialized,
1681
- // we need to also register the function with it
1682
- if (codeGenerator) codeGenerator.functions[name] = thisPrefix + name;
1683
- return this;
1684
- }
1685
-
1686
- // register expression functions with ast visitors
1687
- expressionFunction('bandwidth', bandwidth, scaleVisitor);
1688
- expressionFunction('copy', copy, scaleVisitor);
1689
- expressionFunction('domain', domain, scaleVisitor);
1690
- expressionFunction('range', range, scaleVisitor);
1691
- expressionFunction('invert', invert, scaleVisitor);
1692
- expressionFunction('scale', scale, scaleVisitor);
1693
- expressionFunction('gradient', scaleGradient, scaleVisitor);
1694
- expressionFunction('geoArea', geoArea, scaleVisitor);
1695
- expressionFunction('geoBounds', geoBounds, scaleVisitor);
1696
- expressionFunction('geoCentroid', geoCentroid, scaleVisitor);
1697
- expressionFunction('geoShape', geoShape, scaleVisitor);
1698
- expressionFunction('geoScale', geoScale, scaleVisitor);
1699
- expressionFunction('indata', indata, indataVisitor);
1700
- expressionFunction('data', data, dataVisitor);
1701
- expressionFunction('treePath', treePath, dataVisitor);
1702
- expressionFunction('treeAncestors', treeAncestors, dataVisitor);
1703
-
1704
- // register Vega-Lite selection functions
1705
- expressionFunction('vlSelectionTest', vegaSelections.selectionTest, vegaSelections.selectionVisitor);
1706
- expressionFunction('vlSelectionIdTest', vegaSelections.selectionIdTest, vegaSelections.selectionVisitor);
1707
- expressionFunction('vlSelectionResolve', vegaSelections.selectionResolve, vegaSelections.selectionVisitor);
1708
- expressionFunction('vlSelectionTuples', vegaSelections.selectionTuples);
1709
-
1710
- function parser (expr, scope) {
1711
- const params = {};
767
+ // perform code generation
768
+ const gen = codeGenerator(ast);
1712
769
 
1713
- // parse the expression to an abstract syntax tree (ast)
1714
- let ast;
1715
- try {
1716
- expr = vegaUtil.isString(expr) ? expr : vegaUtil.stringValue(expr) + '';
1717
- ast = vegaExpression.parseExpression(expr);
1718
- } catch (err) {
1719
- vegaUtil.error('Expression parse error: ' + expr);
770
+ // collect signal dependencies
771
+ gen.globals.forEach(name => {
772
+ const signalName = SignalPrefix + name;
773
+ if (!hasOwnProperty(params, signalName) && scope.getSignal(name)) {
774
+ params[signalName] = scope.signalRef(name);
1720
775
  }
776
+ });
1721
777
 
1722
- // analyze ast function calls for dependencies
1723
- ast.visit(node => {
1724
- if (node.type !== vegaExpression.CallExpression) return;
1725
- const name = node.callee.name,
1726
- visit = codegenParams.visitors[name];
1727
- if (visit) visit(name, node.arguments, scope, params);
1728
- });
1729
-
1730
- // perform code generation
1731
- const gen = codeGenerator(ast);
1732
-
1733
- // collect signal dependencies
1734
- gen.globals.forEach(name => {
1735
- const signalName = SignalPrefix + name;
1736
- if (!vegaUtil.hasOwnProperty(params, signalName) && scope.getSignal(name)) {
1737
- params[signalName] = scope.signalRef(name);
1738
- }
1739
- });
1740
-
1741
- // return generated expression code and dependencies
1742
- return {
1743
- $expr: vegaUtil.extend({
1744
- code: gen.code
1745
- }, scope.options.ast ? {
1746
- ast
1747
- } : null),
1748
- $fields: gen.fields,
1749
- $params: params
1750
- };
1751
- }
1752
-
1753
- exports.DataPrefix = DataPrefix;
1754
- exports.IndexPrefix = IndexPrefix;
1755
- exports.ScalePrefix = ScalePrefix;
1756
- exports.SignalPrefix = SignalPrefix;
1757
- exports.bandspace = bandspace;
1758
- exports.bandwidth = bandwidth;
1759
- exports.codeGenerator = codeGenerator;
1760
- exports.codegenParams = codegenParams;
1761
- exports.containerSize = containerSize;
1762
- exports.contrast = contrast;
1763
- exports.copy = copy;
1764
- exports.data = data;
1765
- exports.dataVisitor = dataVisitor;
1766
- exports.dayAbbrevFormat = dayAbbrevFormat;
1767
- exports.dayFormat = dayFormat;
1768
- exports.debug = debug;
1769
- exports.domain = domain;
1770
- exports.encode = encode;
1771
- exports.expressionFunction = expressionFunction;
1772
- exports.format = format;
1773
- exports.functionContext = functionContext;
1774
- exports.geoArea = geoArea;
1775
- exports.geoBounds = geoBounds;
1776
- exports.geoCentroid = geoCentroid;
1777
- exports.geoScale = geoScale;
1778
- exports.geoShape = geoShape;
1779
- exports.inScope = inScope;
1780
- exports.indata = indata;
1781
- exports.indataVisitor = indataVisitor;
1782
- exports.indexof = indexof;
1783
- exports.info = info;
1784
- exports.invert = invert;
1785
- exports.join = join;
1786
- exports.lastindexof = lastindexof;
1787
- exports.luminance = luminance;
1788
- exports.merge = merge;
1789
- exports.modify = modify;
1790
- exports.monthAbbrevFormat = monthAbbrevFormat;
1791
- exports.monthFormat = monthFormat;
1792
- exports.parseExpression = parser;
1793
- exports.pathShape = pathShape;
1794
- exports.pinchAngle = pinchAngle;
1795
- exports.pinchDistance = pinchDistance;
1796
- exports.pluck = pluck;
1797
- exports.range = range;
1798
- exports.replace = replace;
1799
- exports.reverse = reverse;
1800
- exports.scale = scale;
1801
- exports.scaleGradient = scaleGradient;
1802
- exports.scaleVisitor = scaleVisitor;
1803
- exports.screen = screen;
1804
- exports.setdata = setdata;
1805
- exports.slice = slice;
1806
- exports.sort = sort;
1807
- exports.timeFormat = timeFormat;
1808
- exports.timeParse = timeParse;
1809
- exports.treeAncestors = treeAncestors;
1810
- exports.treePath = treePath;
1811
- exports.utcFormat = utcFormat;
1812
- exports.utcParse = utcParse;
1813
- exports.warn = warn;
1814
- exports.windowSize = windowSize;
778
+ // return generated expression code and dependencies
779
+ return {
780
+ $expr: extend({
781
+ code: gen.code
782
+ }, scope.options.ast ? {
783
+ ast
784
+ } : null),
785
+ $fields: gen.fields,
786
+ $params: params
787
+ };
788
+ }
1815
789
 
1816
- }));
790
+ export { DataPrefix, IndexPrefix, ScalePrefix, SignalPrefix, bandspace, bandwidth, codeGenerator, codegenParams, containerSize, contrast, copy, data, dataVisitor, dayAbbrevFormat, dayFormat, debug, domain, encode, expressionFunction, format, functionContext, geoArea, geoBounds, geoCentroid, geoScale, geoShape, inScope, indata, indataVisitor, indexof, info, invert, join, lastindexof, luminance, merge, modify, monthAbbrevFormat, monthFormat, parser as parseExpression, pathShape, pinchAngle, pinchDistance, pluck, range, replace, reverse, scale, scaleGradient, scaleVisitor, screen, setdata, slice, sort, timeFormat, timeParse, treeAncestors, treePath, utcFormat, utcParse, warn, windowSize };
791
+ //# sourceMappingURL=vega-functions.js.map