vendor/assets/javascripts/vega-lite.js in vega-0.2.4 vs vendor/assets/javascripts/vega-lite.js in vega-0.2.5
- old
+ new
@@ -1,14 +1,14 @@
(function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('vega-util'), require('vega')) :
- typeof define === 'function' && define.amd ? define(['exports', 'vega-util', 'vega'], factory) :
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.vegaLite = {}, global.vega, global.vega));
-}(this, (function (exports, vegaUtil, vega) { 'use strict';
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('vega')) :
+ typeof define === 'function' && define.amd ? define(['exports', 'vega'], factory) :
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.vegaLite = {}, global.vega));
+})(this, (function (exports, vega) { 'use strict';
var name = "vega-lite";
var author = "Dominik Moritz, Kanit \"Ham\" Wongsuphasawat, Arvind Satyanarayan, Jeffrey Heer";
- var version$1 = "5.1.1";
+ var version$1 = "5.2.0";
var collaborators = [
"Kanit Wongsuphasawat (http://kanitw.yellowpigz.com)",
"Dominik Moritz (https://www.domoritz.de)",
"Arvind Satyanarayan (https://arvindsatya.com)",
"Jeffrey Heer (https://jheer.org)"
@@ -81,55 +81,56 @@
var license = "BSD-3-Clause";
var bugs = {
url: "https://github.com/vega/vega-lite/issues"
};
var devDependencies = {
- "@babel/core": "^7.15.0",
- "@babel/preset-env": "^7.15.0",
- "@babel/preset-typescript": "^7.15.0",
+ "@babel/core": "^7.16.0",
+ "@babel/preset-env": "^7.16.0",
+ "@babel/preset-typescript": "^7.16.0",
+ "@rollup/plugin-alias": "^3.1.8",
"@rollup/plugin-babel": "^5.3.0",
- "@rollup/plugin-commonjs": "^20.0.0",
+ "@rollup/plugin-commonjs": "^21.0.1",
"@rollup/plugin-json": "^4.1.0",
- "@rollup/plugin-node-resolve": "^13.0.4",
- "@types/chai": "^4.2.21",
- "@types/d3": "^7.0.0",
- "@types/jest": "^27.0.1",
+ "@rollup/plugin-node-resolve": "^13.0.6",
+ "@types/chai": "^4.2.22",
+ "@types/d3": "^7.1.0",
+ "@types/jest": "^27.0.2",
"@types/mkdirp": "^1.0.2",
"@types/pako": "^1.0.2",
- "@typescript-eslint/eslint-plugin": "^4.29.2",
- "@typescript-eslint/parser": "^4.29.2",
- ajv: "^8.6.2",
+ "@typescript-eslint/eslint-plugin": "^5.4.0",
+ "@typescript-eslint/parser": "^5.4.0",
+ ajv: "^8.8.0",
"ajv-formats": "^2.1.1",
chai: "^4.3.4",
cheerio: "^1.0.0-rc.10",
"conventional-changelog-cli": "^2.1.1",
- d3: "^7.0.1",
+ d3: "^7.1.1",
"del-cli": "^4.0.1",
- eslint: "^7.32.0",
+ eslint: "^8.2.0",
"eslint-config-prettier": "^8.3.0",
- "eslint-plugin-jest": "^24.4.0",
+ "eslint-plugin-jest": "^25.2.4",
"eslint-plugin-prettier": "^4.0.0",
"gh-pages": "^3.2.3",
- "highlight.js": "^11.2.0",
- jest: "^27.0.6",
- "jest-dev-server": "^5.0.3",
+ "highlight.js": "^11.3.1",
+ jest: "^27.3.1",
+ "jest-dev-server": "^6.0.0",
mkdirp: "^1.0.4",
pako: "^2.0.4",
- prettier: "^2.3.2",
- puppeteer: "^10.2.0",
- rollup: "^2.56.3",
+ prettier: "^2.4.1",
+ puppeteer: "^11.0.0",
+ rollup: "^2.60.0",
"rollup-plugin-bundle-size": "^1.0.3",
"rollup-plugin-sourcemaps": "^0.6.3",
"rollup-plugin-terser": "^7.0.2",
- serve: "^12.0.0",
- terser: "^5.7.1",
- "ts-jest": "^27.0.5",
- "ts-json-schema-generator": "^0.95.0",
- typescript: "~4.4.2",
- "vega-cli": "^5.20.2",
+ serve: "^13.0.2",
+ terser: "^5.10.0",
+ "ts-jest": "^27.0.7",
+ "ts-json-schema-generator": "^0.97.0",
+ typescript: "~4.5.2",
+ "vega-cli": "^5.21.0",
"vega-datasets": "~2.2.0",
- "vega-embed": "^6.18.2",
+ "vega-embed": "^6.20.2",
"vega-tooltip": "^0.27.0",
"yaml-front-matter": "^4.1.1"
};
var dependencies = {
"@types/clone": "~2.1.1",
@@ -137,17 +138,17 @@
clone: "~2.1.2",
"fast-deep-equal": "~3.1.3",
"fast-json-stable-stringify": "~2.1.0",
"json-stringify-pretty-compact": "~3.0.0",
tslib: "~2.3.1",
- "vega-event-selector": "~2.0.6",
- "vega-expression": "~4.0.1",
- "vega-util": "~1.16.1",
- yargs: "~17.1.1"
+ "vega-event-selector": "~3.0.0",
+ "vega-expression": "~5.0.0",
+ "vega-util": "~1.17.0",
+ yargs: "~17.2.1"
};
var peerDependencies = {
- vega: "^5.20.2"
+ vega: "^5.21.0"
};
var engines = {
node: ">=12"
};
var pkg = {
@@ -602,10 +603,13 @@
}
}
const deepEqual = fastDeepEqual;
const duplicate = clone_;
+ function never(message) {
+ throw new Error(message);
+ }
/**
* Creates an object composed of the picked object properties.
*
* var object = {'a': 1, 'b': '2', 'c': 3};
* pick(object, ['a', 'c']);
@@ -615,11 +619,11 @@
function pick(obj, props) {
const copy = {};
for (const prop of props) {
- if (vegaUtil.hasOwnProperty(obj, prop)) {
+ if (vega.hasOwnProperty(obj, prop)) {
copy[prop] = obj[prop];
}
}
return copy;
@@ -643,11 +647,11 @@
/**
* Monkey patch Set so that `stringify` produces a string representation of sets.
*/
Set.prototype['toJSON'] = function () {
- return `Set(${[...this].map(x => fastJsonStableStringify(x)).join(',')})`;
+ return "Set(".concat([...this].map(x => fastJsonStableStringify(x)).join(','), ")");
};
/**
* Converts any object to a string representation that can be consumed by humans.
*/
@@ -656,15 +660,15 @@
/**
* Converts any object to a string of limited size, or a number.
*/
function hash(a) {
- if (vegaUtil.isNumber(a)) {
+ if (vega.isNumber(a)) {
return a;
}
- const str = vegaUtil.isString(a) ? a : fastJsonStableStringify(a); // short strings can be used as hash directly, longer strings are hashed to reduce memory usage
+ const str = vega.isString(a) ? a : fastJsonStableStringify(a); // short strings can be used as hash directly, longer strings are hashed to reduce memory usage
if (str.length < 250) {
return str;
} // from http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
@@ -720,21 +724,25 @@
*/
/**
* recursively merges src into dest
*/
- function mergeDeep(dest, ...src) {
+ function mergeDeep(dest) {
+ for (var _len = arguments.length, src = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ src[_key - 1] = arguments[_key];
+ }
+
for (const s of src) {
- deepMerge_(dest, s ?? {});
+ deepMerge_(dest, s !== null && s !== void 0 ? s : {});
}
return dest;
}
function deepMerge_(dest, src) {
for (const property of keys(src)) {
- vegaUtil.writeConfig(dest, property, src[property], true);
+ vega.writeConfig(dest, property, src[property], true);
}
}
function unique(values, f) {
const results = [];
@@ -798,13 +806,13 @@
}
function prefixGenerator(a) {
const prefixes = new Set();
for (const x of a) {
- const splitField = vegaUtil.splitAccessPath(x); // Wrap every element other than the first in `[]`
+ const splitField = vega.splitAccessPath(x); // Wrap every element other than the first in `[]`
- const wrappedWithAccessors = splitField.map((y, i) => i === 0 ? y : `[${y}]`);
+ const wrappedWithAccessors = splitField.map((y, i) => i === 0 ? y : "[".concat(y, "]"));
const computedPrefixes = wrappedWithAccessors.map((_, i) => wrappedWithAccessors.slice(0, i + 1).join(''));
for (const y of computedPrefixes) {
prefixes.add(y);
}
@@ -847,15 +855,15 @@
return (s.match(/^\d+/) ? '_' : '') + alphanumericS;
}
function logicalExpr(op, cb) {
if (isLogicalNot(op)) {
- return `!(${logicalExpr(op.not, cb)})`;
+ return "!(".concat(logicalExpr(op.not, cb), ")");
} else if (isLogicalAnd(op)) {
- return `(${op.and.map(and => logicalExpr(and, cb)).join(') && (')})`;
+ return "(".concat(op.and.map(and => logicalExpr(and, cb)).join(') && ('), ")");
} else if (isLogicalOr(op)) {
- return `(${op.or.map(or => logicalExpr(or, cb)).join(') || (')})`;
+ return "(".concat(op.or.map(or => logicalExpr(or, cb)).join(') || ('), ")");
} else {
return cb(op);
}
}
/**
@@ -882,17 +890,18 @@
* Converts a path to an access path with datum.
* @param path The field name.
* @param datum The string to use for `datum`.
*/
- function accessPathWithDatum(path, datum = 'datum') {
- const pieces = vegaUtil.splitAccessPath(path);
+ function accessPathWithDatum(path) {
+ let datum = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'datum';
+ const pieces = vega.splitAccessPath(path);
const prefixes = [];
for (let i = 1; i <= pieces.length; i++) {
- const prefix = `[${pieces.slice(0, i).map(vegaUtil.stringValue).join('][')}]`;
- prefixes.push(`${datum}${prefix}`);
+ const prefix = "[".concat(pieces.slice(0, i).map(vega.stringValue).join(']['), "]");
+ prefixes.push("".concat(datum).concat(prefix));
}
return prefixes.join(' && ');
}
/**
@@ -900,12 +909,13 @@
*
* @param path The field name.
* @param datum The string to use for `datum`.
*/
- function flatAccessWithDatum(path, datum = 'datum') {
- return `${datum}[${vegaUtil.stringValue(vegaUtil.splitAccessPath(path).join('.'))}]`;
+ function flatAccessWithDatum(path) {
+ let datum = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'datum';
+ return "".concat(datum, "[").concat(vega.stringValue(vega.splitAccessPath(path).join('.')), "]");
}
function escapePathAccess(string) {
return string.replace(/(\[|\]|\.|'|")/g, '\\$1');
}
@@ -914,11 +924,11 @@
* For example, `foo["bar"].baz` becomes `foo\\.bar\\.baz`.
*/
function replacePathInField(path) {
- return `${vegaUtil.splitAccessPath(path).map(escapePathAccess).join('\\.')}`;
+ return "".concat(vega.splitAccessPath(path).map(escapePathAccess).join('\\.'));
}
/**
* Replace all occurrences of a string with another string.
*
* @param string the string to replace in
@@ -933,28 +943,32 @@
* Remove path accesses with access from field.
* For example, `foo["bar"].baz` becomes `foo.bar.baz`.
*/
function removePathFromField(path) {
- return `${vegaUtil.splitAccessPath(path).join('.')}`;
+ return "".concat(vega.splitAccessPath(path).join('.'));
}
/**
* Count the depth of the path. Returns 1 for fields that are not nested.
*/
function accessPathDepth(path) {
if (!path) {
return 0;
}
- return vegaUtil.splitAccessPath(path).length;
+ return vega.splitAccessPath(path).length;
}
/**
* This is a replacement for chained || for numeric properties or properties that respect null so that 0 will be included.
*/
- function getFirstDefined(...args) {
+ function getFirstDefined() {
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
+ args[_key2] = arguments[_key2];
+ }
+
for (const arg of args) {
if (arg !== undefined) {
return arg;
}
}
@@ -979,11 +993,11 @@
function resetIdCounter() {
idCounter = 42;
}
function internalField(name) {
- return isInternalField(name) ? name : `__${name}`;
+ return isInternalField(name) ? name : "__".concat(name);
}
function isInternalField(name) {
return name.startsWith('__');
}
/**
@@ -1000,11 +1014,11 @@
/**
* Returns whether the passed in value is a valid number.
*/
function isNumeric(value) {
- if (vegaUtil.isNumber(value)) {
+ if (vega.isNumber(value)) {
return true;
}
return !isNaN(value) && !isNaN(parseFloat(value));
}
@@ -1019,12 +1033,15 @@
const FACET = 'facet'; // Position
const X = 'x';
const Y = 'y';
const X2 = 'x2';
- const Y2 = 'y2'; // Arc-Position
+ const Y2 = 'y2'; // Position Offset
+ const XOFFSET = 'xOffset';
+ const YOFFSET = 'yOffset'; // Arc-Position
+
const RADIUS = 'radius';
const RADIUS2 = 'radius2';
const THETA = 'theta';
const THETA2 = 'theta2'; // Geo Position
@@ -1094,10 +1111,12 @@
}
const GEOPOSITION_CHANNELS = keys(GEO_POSIITON_CHANNEL_INDEX);
const UNIT_CHANNEL_INDEX = { ...POSITION_CHANNEL_INDEX,
...POLAR_POSITION_CHANNEL_INDEX,
...GEO_POSIITON_CHANNEL_INDEX,
+ xOffset: 1,
+ yOffset: 1,
// color
color: 1,
fill: 1,
stroke: 1,
// other non-position with scale
@@ -1226,11 +1245,11 @@
return RADIUS2;
}
return undefined;
}
- function getSizeChannel$1(channel) {
+ function getSizeChannel(channel) {
switch (channel) {
case X:
case X2:
return 'width';
@@ -1271,18 +1290,47 @@
case RADIUS2:
return 'radius2Offset';
}
return undefined;
+ }
+ /**
+ * Get the main channel for a range channel. E.g. `x` for `x2`.
+ */
+
+ function getOffsetScaleChannel(channel) {
+ switch (channel) {
+ case X:
+ return 'xOffset';
+
+ case Y:
+ return 'yOffset';
+ }
+
+ return undefined;
+ }
+ function getMainChannelFromOffsetChannel(channel) {
+ switch (channel) {
+ case 'xOffset':
+ return 'x';
+
+ case 'yOffset':
+ return 'y';
+ }
} // CHANNELS without COLUMN, ROW
+ const UNIT_CHANNELS = keys(UNIT_CHANNEL_INDEX); // NONPOSITION_CHANNELS = UNIT_CHANNELS without X, Y, X2, Y2;
+
const {
x: _x,
y: _y,
// x2 and y2 share the same scale as x and y
x2: _x2,
y2: _y2,
+ //
+ xOffset: _xo,
+ yOffset: _yo,
latitude: _latitude,
longitude: _longitude,
latitude2: _latitude2,
longitude2: _longitude2,
theta: _theta,
@@ -1306,11 +1354,18 @@
radius: 1
};
const POLAR_POSITION_SCALE_CHANNELS = keys(POLAR_POSITION_SCALE_CHANNEL_INDEX);
function getPositionScaleChannel(sizeType) {
return sizeType === 'width' ? X : Y;
- } // NON_POSITION_SCALE_CHANNEL = SCALE_CHANNELS without X, Y
+ }
+ const OFFSET_SCALE_CHANNEL_INDEX = {
+ xOffset: 1,
+ yOffset: 1
+ };
+ function isXorYOffset(channel) {
+ return channel in OFFSET_SCALE_CHANNEL_INDEX;
+ } // NON_POSITION_SCALE_CHANNEL = SCALE_CHANNELS without position / offset
const {
// x2 and y2 share the same scale as x and y
// text and tooltip have format instead of scale,
// href has neither format, nor scale
@@ -1352,10 +1407,11 @@
}
} // Declare SCALE_CHANNEL_INDEX
const SCALE_CHANNEL_INDEX = { ...POSITION_SCALE_CHANNEL_INDEX,
...POLAR_POSITION_SCALE_CHANNEL_INDEX,
+ ...OFFSET_SCALE_CHANNEL_INDEX,
...NONPOSITION_SCALE_CHANNEL_INDEX
};
/** List of channels with scales */
const SCALE_CHANNELS = keys(SCALE_CHANNEL_INDEX);
@@ -1423,10 +1479,12 @@
case COLUMN:
return ALL_MARKS;
case X:
case Y:
+ case XOFFSET:
+ case YOFFSET:
case LATITUDE:
case LONGITUDE:
// all marks except geoshape. geoshape does not use X, Y -- it uses a projection
return ALL_MARKS_EXCEPT_GEOSHAPE;
@@ -1520,10 +1578,12 @@
switch (channel) {
case X:
case Y:
case THETA:
case RADIUS:
+ case XOFFSET:
+ case YOFFSET:
case SIZE:
case ANGLE:
case STROKEWIDTH:
case OPACITY:
case FILLOPACITY:
@@ -1601,38 +1661,37 @@
}
function isArgmaxDef(a) {
return !!a && !!a['argmax'];
}
function isAggregateOp(a) {
- return vegaUtil.isString(a) && !!AGGREGATE_OP_INDEX[a];
+ return vega.isString(a) && !!AGGREGATE_OP_INDEX[a];
}
- const COUNTING_OPS = ['count', 'valid', 'missing', 'distinct'];
+ const COUNTING_OPS = new Set(['count', 'valid', 'missing', 'distinct']);
function isCountingAggregateOp(aggregate) {
- return vegaUtil.isString(aggregate) && contains(COUNTING_OPS, aggregate);
+ return vega.isString(aggregate) && COUNTING_OPS.has(aggregate);
}
function isMinMaxOp(aggregate) {
- return vegaUtil.isString(aggregate) && contains(['min', 'max'], aggregate);
+ return vega.isString(aggregate) && contains(['min', 'max'], aggregate);
}
/** Additive-based aggregation operations. These can be applied to stack. */
- const SUM_OPS = ['count', 'sum', 'distinct', 'valid', 'missing'];
+ const SUM_OPS = new Set(['count', 'sum', 'distinct', 'valid', 'missing']);
/**
* Aggregation operators that always produce values within the range [domainMin, domainMax].
*/
- const SHARED_DOMAIN_OPS = ['mean', 'average', 'median', 'q1', 'q3', 'min', 'max'];
- const SHARED_DOMAIN_OP_INDEX = vegaUtil.toSet(SHARED_DOMAIN_OPS);
+ const SHARED_DOMAIN_OPS = new Set(['mean', 'average', 'median', 'q1', 'q3', 'min', 'max']);
/**
* Create a key for the bin configuration. Not for prebinned bin.
*/
function binToString(bin) {
- if (vegaUtil.isBoolean(bin)) {
+ if (vega.isBoolean(bin)) {
bin = normalizeBin(bin, undefined);
}
- return 'bin' + keys(bin).map(p => isParameterExtent(bin[p]) ? varName(`_${p}_${entries$1(bin[p])}`) : varName(`_${p}_${bin[p]}`)).join('');
+ return 'bin' + keys(bin).map(p => isParameterExtent(bin[p]) ? varName("_".concat(p, "_").concat(entries$1(bin[p]))) : varName("_".concat(p, "_").concat(bin[p]))).join('');
}
/**
* Vega-Lite should bin the data.
*/
@@ -1645,11 +1704,11 @@
function isBinned(bin) {
return bin === 'binned' || isBinParams(bin) && bin.binned === true;
}
function isBinParams(bin) {
- return vegaUtil.isObject(bin);
+ return vega.isObject(bin);
}
function isParameterExtent(extent) {
return extent === null || extent === void 0 ? void 0 : extent['param'];
}
function autoMaxBins(channel) {
@@ -1765,41 +1824,41 @@
};
const subtitleMarkConfig = pick(titleConfig, ['align', 'baseline', 'dx', 'dy', 'limit']);
return {
titleMarkConfig,
subtitleMarkConfig,
- nonMarkTitleProperties: nonMarkTitleProperties,
+ nonMarkTitleProperties,
subtitle
};
}
function isText(v) {
- return vegaUtil.isString(v) || vegaUtil.isArray(v) && vegaUtil.isString(v[0]);
+ return vega.isString(v) || vega.isArray(v) && vega.isString(v[0]);
}
function isSignalRef(o) {
return o && !!o['signal'];
} // TODO: add type of value (Make it VgValueRef<V extends ValueOrGradient> {value?:V ...})
function isVgRangeStep(range) {
return !!range['step'];
}
function isDataRefUnionedDomain(domain) {
- if (!vegaUtil.isArray(domain)) {
+ if (!vega.isArray(domain)) {
return 'fields' in domain && !('data' in domain);
}
return false;
}
function isFieldRefUnionDomain(domain) {
- if (!vegaUtil.isArray(domain)) {
+ if (!vega.isArray(domain)) {
return 'fields' in domain && 'data' in domain;
}
return false;
}
function isDataRefDomain(domain) {
- if (!vegaUtil.isArray(domain)) {
+ if (!vega.isArray(domain)) {
return 'field' in domain && 'data' in domain;
}
return false;
}
@@ -1888,11 +1947,11 @@
}; // Vega's cornerRadius channels.
const VG_CORNERRADIUS_CHANNELS = ['cornerRadius', 'cornerRadiusTopLeft', 'cornerRadiusTopRight', 'cornerRadiusBottomLeft', 'cornerRadiusBottomRight'];
function signalOrValueRefWithCondition(val) {
- const condition = vegaUtil.isArray(val.condition) ? val.condition.map(conditionalSignalRefOrValue) : conditionalSignalRefOrValue(val.condition);
+ const condition = vega.isArray(val.condition) ? val.condition.map(conditionalSignalRefOrValue) : conditionalSignalRefOrValue(val.condition);
return { ...signalRefOrValue(val),
condition
};
}
function signalRefOrValue(value) {
@@ -1941,23 +2000,30 @@
return value !== undefined ? {
value
} : undefined;
}
- function exprFromValueOrSignalRef(ref) {
+ function exprFromSignalRefOrValue(ref) {
if (isSignalRef(ref)) {
return ref.signal;
}
- return vegaUtil.stringValue(ref.value);
+ return vega.stringValue(ref);
}
+ function exprFromValueRefOrSignalRef(ref) {
+ if (isSignalRef(ref)) {
+ return ref.signal;
+ }
+
+ return vega.stringValue(ref.value);
+ }
function signalOrStringValue(v) {
if (isSignalRef(v)) {
return v.signal;
}
- return v == null ? null : vegaUtil.stringValue(v);
+ return v == null ? null : vega.stringValue(v);
}
function applyMarkConfig(e, model, propsList) {
for (const property of propsList) {
const value = getMarkConfig(property, model.markDef, model.config);
@@ -1967,13 +2033,16 @@
}
return e;
}
function getStyles(mark) {
- return [].concat(mark.type, mark.style ?? []);
+ var _mark$style;
+
+ return [].concat(mark.type, (_mark$style = mark.style) !== null && _mark$style !== void 0 ? _mark$style : []);
}
- function getMarkPropOrConfig(channel, mark, config, opt = {}) {
+ function getMarkPropOrConfig(channel, mark, config) {
+ let opt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
const {
vgChannel,
ignoreVgConfig
} = opt;
@@ -1990,13 +2059,14 @@
/**
* Return property value from style or mark specific config property if exists.
* Otherwise, return general mark specific config.
*/
- function getMarkConfig(channel, mark, config, {
- vgChannel
- } = {}) {
+ function getMarkConfig(channel, mark, config) {
+ let {
+ vgChannel
+ } = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
return getFirstDefined( // style config has highest precedence
vgChannel ? getMarkStyleConfig(channel, mark, config.style) : undefined, getMarkStyleConfig(channel, mark, config.style), // then mark-specific config
vgChannel ? config[mark.type][vgChannel] : undefined, config[mark.type][channel], // Need to cast because MarkDef doesn't perfectly match with AnyMarkConfig, but if the type isn't available, we'll get nothing here, which is fine
// If there is vgChannel, skip vl channel.
// For example, vl size for text is vg fontSize, but config.mark.size is only for point size.
@@ -2005,11 +2075,11 @@
}
function getMarkStyleConfig(prop, mark, styleConfigIndex) {
return getStyleConfig(prop, getStyles(mark), styleConfigIndex);
}
function getStyleConfig(p, styles, styleConfigIndex) {
- styles = vegaUtil.array(styles);
+ styles = vega.array(styles);
let value;
for (const style of styles) {
const styleConfig = styleConfigIndex[style];
@@ -2023,13 +2093,15 @@
/**
* Return Vega sort parameters (tuple of field and order).
*/
function sortParams(orderDef, fieldRefOption) {
- return vegaUtil.array(orderDef).reduce((s, orderChannelDef) => {
+ return vega.array(orderDef).reduce((s, orderChannelDef) => {
+ var _orderChannelDef$sort;
+
s.field.push(vgField(orderChannelDef, fieldRefOption));
- s.order.push(orderChannelDef.sort ?? 'ascending');
+ s.order.push((_orderChannelDef$sort = orderChannelDef.sort) !== null && _orderChannelDef$sort !== void 0 ? _orderChannelDef$sort : 'ascending');
return s;
}, {
field: [],
order: []
});
@@ -2054,11 +2126,11 @@
return title1;
} else if (!title1) {
// if title1 is falsy
return title2;
} else {
- return [...vegaUtil.array(title1), ...vegaUtil.array(title2)].join(', ');
+ return [...vega.array(title1), ...vega.array(title2)].join(', ');
}
}
function mergeTitleComponent(v1, v2) {
const v1Val = v1.value;
const v2Val = v2.value;
@@ -2150,240 +2222,261 @@
descriptor.value = value;
}
}
+ function _checkPrivateRedeclaration(obj, privateCollection) {
+ if (privateCollection.has(obj)) {
+ throw new TypeError("Cannot initialize the same private elements twice on an object");
+ }
+ }
+
+ function _classPrivateFieldInitSpec(obj, privateMap, value) {
+ _checkPrivateRedeclaration(obj, privateMap);
+
+ privateMap.set(obj, value);
+ }
+
/**
* Collection of all Vega-Lite Error Messages
*/
function invalidSpec(spec) {
- return `Invalid specification ${stringify(spec)}. Make sure the specification includes at least one of the following properties: "mark", "layer", "facet", "hconcat", "vconcat", "concat", or "repeat".`;
+ return "Invalid specification ".concat(stringify(spec), ". Make sure the specification includes at least one of the following properties: \"mark\", \"layer\", \"facet\", \"hconcat\", \"vconcat\", \"concat\", or \"repeat\".");
} // FIT
const FIT_NON_SINGLE = 'Autosize "fit" only works for single views and layered views.';
function containerSizeNonSingle(name) {
const uName = name == 'width' ? 'Width' : 'Height';
- return `${uName} "container" only works for single views and layered views.`;
+ return "".concat(uName, " \"container\" only works for single views and layered views.");
}
function containerSizeNotCompatibleWithAutosize(name) {
const uName = name == 'width' ? 'Width' : 'Height';
const fitDirection = name == 'width' ? 'x' : 'y';
- return `${uName} "container" only works well with autosize "fit" or "fit-${fitDirection}".`;
+ return "".concat(uName, " \"container\" only works well with autosize \"fit\" or \"fit-").concat(fitDirection, "\".");
}
function droppingFit(channel) {
- return channel ? `Dropping "fit-${channel}" because spec has discrete ${getSizeChannel$1(channel)}.` : `Dropping "fit" because spec has discrete size.`;
+ return channel ? "Dropping \"fit-".concat(channel, "\" because spec has discrete ").concat(getSizeChannel(channel), ".") : "Dropping \"fit\" because spec has discrete size.";
} // VIEW SIZE
function unknownField(channel) {
- return `Unknown field for ${channel}. Cannot calculate view size.`;
+ return "Unknown field for ".concat(channel, ". Cannot calculate view size.");
} // SELECTION
function cannotProjectOnChannelWithoutField(channel) {
- return `Cannot project a selection on encoding channel "${channel}", which has no field.`;
+ return "Cannot project a selection on encoding channel \"".concat(channel, "\", which has no field.");
}
function cannotProjectAggregate(channel, aggregate) {
- return `Cannot project a selection on encoding channel "${channel}" as it uses an aggregate function ("${aggregate}").`;
+ return "Cannot project a selection on encoding channel \"".concat(channel, "\" as it uses an aggregate function (\"").concat(aggregate, "\").");
}
function nearestNotSupportForContinuous(mark) {
- return `The "nearest" transform is not supported for ${mark} marks.`;
+ return "The \"nearest\" transform is not supported for ".concat(mark, " marks.");
}
function selectionNotSupported(mark) {
- return `Selection not supported for ${mark} yet.`;
+ return "Selection not supported for ".concat(mark, " yet.");
}
function selectionNotFound(name) {
- return `Cannot find a selection named "${name}".`;
+ return "Cannot find a selection named \"".concat(name, "\".");
}
const SCALE_BINDINGS_CONTINUOUS = 'Scale bindings are currently only supported for scales with unbinned, continuous domains.';
const LEGEND_BINDINGS_MUST_HAVE_PROJECTION = 'Legend bindings are only supported for selections over an individual field or encoding channel.';
function cannotLookupVariableParameter(name) {
- return `Lookups can only be performed on selection parameters. "${name}" is a variable parameter.`;
+ return "Lookups can only be performed on selection parameters. \"".concat(name, "\" is a variable parameter.");
}
function noSameUnitLookup(name) {
- return `Cannot define and lookup the "${name}" selection in the same view. ` + `Try moving the lookup into a second, layered view?`;
+ return "Cannot define and lookup the \"".concat(name, "\" selection in the same view. ") + "Try moving the lookup into a second, layered view?";
}
const NEEDS_SAME_SELECTION = 'The same selection must be used to override scale domains in a layered view.';
const INTERVAL_INITIALIZED_WITH_X_Y = 'Interval selections should be initialized using "x" and/or "y" keys.'; // REPEAT
function noSuchRepeatedValue(field) {
- return `Unknown repeated value "${field}".`;
+ return "Unknown repeated value \"".concat(field, "\".");
}
function columnsNotSupportByRowCol(type) {
- return `The "columns" property cannot be used when "${type}" has nested row/column.`;
+ return "The \"columns\" property cannot be used when \"".concat(type, "\" has nested row/column.");
} // CONCAT / REPEAT
const CONCAT_CANNOT_SHARE_AXIS = 'Axes cannot be shared in concatenated or repeated views yet (https://github.com/vega/vega-lite/issues/2415).'; // DATA
function unrecognizedParse(p) {
- return `Unrecognized parse "${p}".`;
+ return "Unrecognized parse \"".concat(p, "\".");
}
function differentParse(field, local, ancestor) {
- return `An ancestor parsed field "${field}" as ${ancestor} but a child wants to parse the field as ${local}.`;
+ return "An ancestor parsed field \"".concat(field, "\" as ").concat(ancestor, " but a child wants to parse the field as ").concat(local, ".");
}
const ADD_SAME_CHILD_TWICE = 'Attempt to add the same child twice.'; // TRANSFORMS
function invalidTransformIgnored(transform) {
- return `Ignoring an invalid transform: ${stringify(transform)}.`;
+ return "Ignoring an invalid transform: ".concat(stringify(transform), ".");
}
const NO_FIELDS_NEEDS_AS = 'If "from.fields" is not specified, "as" has to be a string that specifies the key to be used for the data from the secondary source.'; // ENCODING & FACET
function customFormatTypeNotAllowed(channel) {
- return `Config.customFormatTypes is not true, thus custom format type and format for channel ${channel} are dropped.`;
+ return "Config.customFormatTypes is not true, thus custom format type and format for channel ".concat(channel, " are dropped.");
}
function projectionOverridden(opt) {
const {
parentProjection,
projection
} = opt;
- return `Layer's shared projection ${stringify(parentProjection)} is overridden by a child projection ${stringify(projection)}.`;
+ return "Layer's shared projection ".concat(stringify(parentProjection), " is overridden by a child projection ").concat(stringify(projection), ".");
}
const REPLACE_ANGLE_WITH_THETA = 'Arc marks uses theta channel rather than angle, replacing angle with theta.';
+ function offsetNestedInsideContinuousPositionScaleDropped(mainChannel) {
+ return "".concat(mainChannel, "Offset dropped because ").concat(mainChannel, " is continuous");
+ }
+ function replaceOffsetWithMainChannel(mainChannel) {
+ return "There is no ".concat(mainChannel, " encoding. Replacing ").concat(mainChannel, "Offset encoding as ").concat(mainChannel, ".");
+ }
function primitiveChannelDef(channel, type, value) {
- return `Channel ${channel} is a ${type}. Converted to {value: ${stringify(value)}}.`;
+ return "Channel ".concat(channel, " is a ").concat(type, ". Converted to {value: ").concat(stringify(value), "}.");
}
function invalidFieldType(type) {
- return `Invalid field type "${type}".`;
+ return "Invalid field type \"".concat(type, "\".");
}
function invalidFieldTypeForCountAggregate(type, aggregate) {
- return `Invalid field type "${type}" for aggregate: "${aggregate}", using "quantitative" instead.`;
+ return "Invalid field type \"".concat(type, "\" for aggregate: \"").concat(aggregate, "\", using \"quantitative\" instead.");
}
function invalidAggregate(aggregate) {
- return `Invalid aggregation operator "${aggregate}".`;
+ return "Invalid aggregation operator \"".concat(aggregate, "\".");
}
function droppingColor(type, opt) {
const {
fill,
stroke
} = opt;
- return `Dropping color ${type} as the plot also has ${fill && stroke ? 'fill and stroke' : fill ? 'fill' : 'stroke'}.`;
+ return "Dropping color ".concat(type, " as the plot also has ").concat(fill && stroke ? 'fill and stroke' : fill ? 'fill' : 'stroke', ".");
}
function relativeBandSizeNotSupported(sizeChannel) {
- return `Position range does not support relative band size for ${sizeChannel}.`;
+ return "Position range does not support relative band size for ".concat(sizeChannel, ".");
}
function emptyFieldDef(fieldDef, channel) {
- return `Dropping ${stringify(fieldDef)} from channel "${channel}" since it does not contain any data field, datum, value, or signal.`;
+ return "Dropping ".concat(stringify(fieldDef), " from channel \"").concat(channel, "\" since it does not contain any data field, datum, value, or signal.");
}
const LINE_WITH_VARYING_SIZE = 'Line marks cannot encode size with a non-groupby field. You may want to use trail marks instead.';
function incompatibleChannel(channel, markOrFacet, when) {
- return `${channel} dropped as it is incompatible with "${markOrFacet}"${when ? ` when ${when}` : ''}.`;
+ return "".concat(channel, " dropped as it is incompatible with \"").concat(markOrFacet, "\"").concat(when ? " when ".concat(when) : '', ".");
}
+ function offsetEncodingScaleIgnored(channel) {
+ return "".concat(channel, " encoding has no scale, so specified scale is ignored.");
+ }
function invalidEncodingChannel(channel) {
- return `${channel}-encoding is dropped as ${channel} is not a valid encoding channel.`;
+ return "".concat(channel, "-encoding is dropped as ").concat(channel, " is not a valid encoding channel.");
}
function channelShouldBeDiscrete(channel) {
- return `${channel} encoding should be discrete (ordinal / nominal / binned).`;
+ return "".concat(channel, " encoding should be discrete (ordinal / nominal / binned).");
}
function channelShouldBeDiscreteOrDiscretizing(channel) {
- return `${channel} encoding should be discrete (ordinal / nominal / binned) or use a discretizing scale (e.g. threshold).`;
+ return "".concat(channel, " encoding should be discrete (ordinal / nominal / binned) or use a discretizing scale (e.g. threshold).");
}
function facetChannelDropped(channels) {
- return `Facet encoding dropped as ${channels.join(' and ')} ${channels.length > 1 ? 'are' : 'is'} also specified.`;
+ return "Facet encoding dropped as ".concat(channels.join(' and '), " ").concat(channels.length > 1 ? 'are' : 'is', " also specified.");
}
function discreteChannelCannotEncode(channel, type) {
- return `Using discrete channel "${channel}" to encode "${type}" field can be misleading as it does not encode ${type === 'ordinal' ? 'order' : 'magnitude'}.`;
+ return "Using discrete channel \"".concat(channel, "\" to encode \"").concat(type, "\" field can be misleading as it does not encode ").concat(type === 'ordinal' ? 'order' : 'magnitude', ".");
} // MARK
function rangeMarkAlignmentCannotBeExpression(align) {
- return `The ${align} for range marks cannot be an expression`;
+ return "The ".concat(align, " for range marks cannot be an expression");
}
function lineWithRange(hasX2, hasY2) {
const channels = hasX2 && hasY2 ? 'x2 and y2' : hasX2 ? 'x2' : 'y2';
- return `Line mark is for continuous lines and thus cannot be used with ${channels}. We will use the rule mark (line segments) instead.`;
+ return "Line mark is for continuous lines and thus cannot be used with ".concat(channels, ". We will use the rule mark (line segments) instead.");
}
function orientOverridden(original, actual) {
- return `Specified orient "${original}" overridden with "${actual}".`;
+ return "Specified orient \"".concat(original, "\" overridden with \"").concat(actual, "\".");
} // SCALE
function cannotUseScalePropertyWithNonColor(prop) {
- return `Cannot use the scale property "${prop}" with non-color channel.`;
+ return "Cannot use the scale property \"".concat(prop, "\" with non-color channel.");
}
function cannotUseRelativeBandSizeWithNonBandScale(scaleType) {
- return `Cannot use the relative band size with ${scaleType} scale.`;
+ return "Cannot use the relative band size with ".concat(scaleType, " scale.");
}
function unaggregateDomainHasNoEffectForRawField(fieldDef) {
- return `Using unaggregated domain with raw field has no effect (${stringify(fieldDef)}).`;
+ return "Using unaggregated domain with raw field has no effect (".concat(stringify(fieldDef), ").");
}
function unaggregateDomainWithNonSharedDomainOp(aggregate) {
- return `Unaggregated domain not applicable for "${aggregate}" since it produces values outside the origin domain of the source data.`;
+ return "Unaggregated domain not applicable for \"".concat(aggregate, "\" since it produces values outside the origin domain of the source data.");
}
function unaggregatedDomainWithLogScale(fieldDef) {
- return `Unaggregated domain is currently unsupported for log scale (${stringify(fieldDef)}).`;
+ return "Unaggregated domain is currently unsupported for log scale (".concat(stringify(fieldDef), ").");
}
function cannotApplySizeToNonOrientedMark(mark) {
- return `Cannot apply size to non-oriented mark "${mark}".`;
+ return "Cannot apply size to non-oriented mark \"".concat(mark, "\".");
}
function scaleTypeNotWorkWithChannel(channel, scaleType, defaultScaleType) {
- return `Channel "${channel}" does not work with "${scaleType}" scale. We are using "${defaultScaleType}" scale instead.`;
+ return "Channel \"".concat(channel, "\" does not work with \"").concat(scaleType, "\" scale. We are using \"").concat(defaultScaleType, "\" scale instead.");
}
function scaleTypeNotWorkWithFieldDef(scaleType, defaultScaleType) {
- return `FieldDef does not work with "${scaleType}" scale. We are using "${defaultScaleType}" scale instead.`;
+ return "FieldDef does not work with \"".concat(scaleType, "\" scale. We are using \"").concat(defaultScaleType, "\" scale instead.");
}
function scalePropertyNotWorkWithScaleType(scaleType, propName, channel) {
- return `${channel}-scale's "${propName}" is dropped as it does not work with ${scaleType} scale.`;
+ return "".concat(channel, "-scale's \"").concat(propName, "\" is dropped as it does not work with ").concat(scaleType, " scale.");
}
function stepDropped(channel) {
- return `The step for "${channel}" is dropped because the ${channel === 'width' ? 'x' : 'y'} is continuous.`;
+ return "The step for \"".concat(channel, "\" is dropped because the ").concat(channel === 'width' ? 'x' : 'y', " is continuous.");
}
function mergeConflictingProperty(property, propertyOf, v1, v2) {
- return `Conflicting ${propertyOf.toString()} property "${property.toString()}" (${stringify(v1)} and ${stringify(v2)}). Using ${stringify(v1)}.`;
+ return "Conflicting ".concat(propertyOf.toString(), " property \"").concat(property.toString(), "\" (").concat(stringify(v1), " and ").concat(stringify(v2), "). Using ").concat(stringify(v1), ".");
}
function mergeConflictingDomainProperty(property, propertyOf, v1, v2) {
- return `Conflicting ${propertyOf.toString()} property "${property.toString()}" (${stringify(v1)} and ${stringify(v2)}). Using the union of the two domains.`;
+ return "Conflicting ".concat(propertyOf.toString(), " property \"").concat(property.toString(), "\" (").concat(stringify(v1), " and ").concat(stringify(v2), "). Using the union of the two domains.");
}
function independentScaleMeansIndependentGuide(channel) {
- return `Setting the scale to be independent for "${channel}" means we also have to set the guide (axis or legend) to be independent.`;
+ return "Setting the scale to be independent for \"".concat(channel, "\" means we also have to set the guide (axis or legend) to be independent.");
}
function domainSortDropped(sort) {
- return `Dropping sort property ${stringify(sort)} as unioned domains only support boolean or op "count", "min", and "max".`;
+ return "Dropping sort property ".concat(stringify(sort), " as unioned domains only support boolean or op \"count\", \"min\", and \"max\".");
}
const MORE_THAN_ONE_SORT = 'Domains that should be unioned has conflicting sort properties. Sort will be set to true.';
const FACETED_INDEPENDENT_DIFFERENT_SOURCES = 'Detected faceted independent scales that union domain of multiple fields from different data sources. We will use the first field. The result view size may be incorrect.';
const FACETED_INDEPENDENT_SAME_FIELDS_DIFFERENT_SOURCES = 'Detected faceted independent scales that union domain of the same fields from different source. We will assume that this is the same field from a different fork of the same data source. However, if this is not the case, the result view size may be incorrect.';
const FACETED_INDEPENDENT_SAME_SOURCE = 'Detected faceted independent scales that union domain of multiple fields from the same data source. We will use the first field. The result view size may be incorrect.'; // AXIS
function cannotStackRangedMark(channel) {
- return `Cannot stack "${channel}" if there is already "${channel}2".`;
+ return "Cannot stack \"".concat(channel, "\" if there is already \"").concat(channel, "2\".");
}
function cannotStackNonLinearScale(scaleType) {
- return `Cannot stack non-linear scale (${scaleType}).`;
+ return "Cannot stack non-linear scale (".concat(scaleType, ").");
}
function stackNonSummativeAggregate(aggregate) {
- return `Stacking is applied even though the aggregate function is non-summative ("${aggregate}").`;
+ return "Stacking is applied even though the aggregate function is non-summative (\"".concat(aggregate, "\").");
} // TIMEUNIT
function invalidTimeUnit(unitName, value) {
- return `Invalid ${unitName}: ${stringify(value)}.`;
+ return "Invalid ".concat(unitName, ": ").concat(stringify(value), ".");
}
function droppedDay(d) {
- return `Dropping day from datetime ${stringify(d)} as day cannot be combined with other units.`;
+ return "Dropping day from datetime ".concat(stringify(d), " as day cannot be combined with other units.");
}
function errorBarCenterAndExtentAreNotNeeded(center, extent) {
- return `${extent ? 'extent ' : ''}${extent && center ? 'and ' : ''}${center ? 'center ' : ''}${extent && center ? 'are ' : 'is '}not needed when data are aggregated.`;
+ return "".concat(extent ? 'extent ' : '').concat(extent && center ? 'and ' : '').concat(center ? 'center ' : '').concat(extent && center ? 'are ' : 'is ', "not needed when data are aggregated.");
}
function errorBarCenterIsUsedWithWrongExtent(center, extent, mark) {
- return `${center} is not usually used with ${extent} for ${mark}.`;
+ return "".concat(center, " is not usually used with ").concat(extent, " for ").concat(mark, ".");
}
function errorBarContinuousAxisHasCustomizedAggregate(aggregate, compositeMark) {
- return `Continuous axis should not have customized aggregation function ${aggregate}; ${compositeMark} already agregates the axis.`;
+ return "Continuous axis should not have customized aggregation function ".concat(aggregate, "; ").concat(compositeMark, " already agregates the axis.");
}
function errorBand1DNotSupport(property) {
- return `1D error band does not support ${property}.`;
+ return "1D error band does not support ".concat(property, ".");
} // CHANNEL
function channelRequiredForBinned(channel) {
- return `Channel ${channel} is required for "binned" bin.`;
+ return "Channel ".concat(channel, " is required for \"binned\" bin.");
}
function channelShouldNotBeUsedForBinned(channel) {
- return `Channel ${channel} should not be used with "binned" bin.`;
+ return "Channel ".concat(channel, " should not be used with \"binned\" bin.");
}
function domainRequiredForThresholdScale(channel) {
- return `Domain for ${channel} is required for threshold scale.`;
+ return "Domain for ".concat(channel, " is required for threshold scale.");
}
/**
* Main (default) Vega Logger instance for Vega-Lite.
*/
- const main = vegaUtil.logger(vegaUtil.Warn);
+ const main = vega.logger(vega.Warn);
let current = main;
/**
* Set the singleton logger to be a custom logger.
*/
@@ -2397,26 +2490,26 @@
function reset() {
current = main;
return current;
}
- function warn(...args) {
- current.warn(...args);
+ function warn() {
+ current.warn(...arguments);
}
- function debug(...args) {
- current.debug(...args);
+ function debug() {
+ current.debug(...arguments);
}
// DateTime definition object
/**
* @minimum 1
* @maximum 12
* @TJS-type integer
*/
function isDateTime(o) {
- if (o && vegaUtil.isObject(o)) {
+ if (o && vega.isObject(o)) {
for (const part of TIMEUNIT_PARTS) {
if (part in o) {
return true;
}
}
@@ -2432,11 +2525,11 @@
function normalizeQuarter(q) {
if (isNumeric(q)) {
q = +q;
}
- if (vegaUtil.isNumber(q)) {
+ if (vega.isNumber(q)) {
if (q > 4) {
warn(invalidTimeUnit('quarter', q));
} // We accept 1-based quarter, so need to readjust to 0-based quarter
@@ -2450,11 +2543,11 @@
function normalizeMonth(m) {
if (isNumeric(m)) {
m = +m;
}
- if (vegaUtil.isNumber(m)) {
+ if (vega.isNumber(m)) {
// We accept 1-based month, so need to readjust to 0-based month
return m - 1;
} else {
const lowerM = m.toLowerCase();
const monthIndex = MONTHS.indexOf(lowerM);
@@ -2478,11 +2571,11 @@
function normalizeDay(d) {
if (isNumeric(d)) {
d = +d;
}
- if (vegaUtil.isNumber(d)) {
+ if (vega.isNumber(d)) {
// mod so that this can be both 0-based where 0 = sunday
// and 1-based where 7=sunday
return d % 7;
} else {
const lowerD = d.toLowerCase();
@@ -2532,22 +2625,22 @@
if (d.month !== undefined) {
const month = normalize ? normalizeMonth(d.month) : d.month;
parts.push(month);
} else if (d.quarter !== undefined) {
const quarter = normalize ? normalizeQuarter(d.quarter) : d.quarter;
- parts.push(vegaUtil.isNumber(quarter) ? quarter * 3 : `${quarter}*3`);
+ parts.push(vega.isNumber(quarter) ? quarter * 3 : "".concat(quarter, "*3"));
} else {
parts.push(0); // months start at zero in JS
}
if (d.date !== undefined) {
parts.push(d.date);
} else if (d.day !== undefined) {
// HACK: Day only works as a standalone unit
// This is only correct because we always set year to 2006 for day
const day = normalize ? normalizeDay(d.day) : d.day;
- parts.push(vegaUtil.isNumber(day) ? day + 1 : `${day}+1`);
+ parts.push(vega.isNumber(day) ? day + 1 : "".concat(day, "+1"));
} else {
parts.push(1); // Date starts at 1 in JS
} // Note: can't use TimeUnit enum here as importing it will create
// circular dependency problem!
@@ -2570,13 +2663,13 @@
function dateTimeToExpr(d) {
const parts = dateTimeParts(d, true);
const string = parts.join(', ');
if (d.utc) {
- return `utc(${string})`;
+ return "utc(".concat(string, ")");
} else {
- return `datetime(${string})`;
+ return "datetime(".concat(string, ")");
}
}
/**
* Return Vega expression for a date time expression.
*
@@ -2587,13 +2680,13 @@
function dateTimeExprToExpr(d) {
const parts = dateTimeParts(d, false);
const string = parts.join(', ');
if (d.utc) {
- return `utc(${string})`;
+ return "utc(".concat(string, ")");
} else {
- return `datetime(${string})`;
+ return "datetime(".concat(string, ")");
}
}
/**
* @param d the date time.
* @returns the timestamp.
@@ -2669,24 +2762,25 @@
}
/**
* Returns Vega expression for a given timeUnit and fieldRef
*/
- function fieldExpr(fullTimeUnit, field, {
- end
- } = {
- end: false
- }) {
+ function fieldExpr(fullTimeUnit, field) {
+ let {
+ end
+ } = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
+ end: false
+ };
const fieldRef = accessPathWithDatum(field);
const utc = isUTCTimeUnit(fullTimeUnit) ? 'utc' : '';
function func(timeUnit) {
if (timeUnit === 'quarter') {
// quarter starting at 0 (0,3,6,9).
- return `(${utc}quarter(${fieldRef})-1)`;
+ return "(".concat(utc, "quarter(").concat(fieldRef, ")-1)");
} else {
- return `${utc}${timeUnit}(${fieldRef})`;
+ return "".concat(utc).concat(timeUnit, "(").concat(fieldRef, ")");
}
}
let lastTimeUnit;
const dateExpr = {};
@@ -2708,11 +2802,11 @@
if (!timeUnit) {
return undefined;
}
const timeUnitParts = getTimeUnitParts(timeUnit);
- return `timeUnitSpecifier(${stringify(timeUnitParts)}, ${stringify(VEGALITE_TIMEFORMAT)})`;
+ return "timeUnitSpecifier(".concat(stringify(timeUnitParts), ", ").concat(stringify(VEGALITE_TIMEFORMAT), ")");
}
/**
* Returns the signal expression used for axis labels for a time unit.
*/
@@ -2724,24 +2818,24 @@
const expr = timeUnitSpecifierExpression(timeUnit); // We only use utcFormat for utc scale
// For utc time units, the data is already converted as a part of timeUnit transform.
// Thus, utc time units should use timeFormat to avoid shifting the time twice.
const utc = isUTCScale || isUTCTimeUnit(timeUnit);
- return `${utc ? 'utc' : 'time'}Format(${field}, ${expr})`;
+ return "".concat(utc ? 'utc' : 'time', "Format(").concat(field, ", ").concat(expr, ")");
}
function normalizeTimeUnit(timeUnit) {
if (!timeUnit) {
return undefined;
}
let params;
- if (vegaUtil.isString(timeUnit)) {
+ if (vega.isString(timeUnit)) {
params = {
unit: timeUnit
};
- } else if (vegaUtil.isObject(timeUnit)) {
+ } else if (vega.isObject(timeUnit)) {
params = { ...timeUnit,
...(timeUnit.unit ? {
unit: timeUnit.unit
} : {})
};
@@ -2759,14 +2853,14 @@
utc,
...rest
} = normalizeTimeUnit(tu);
if (rest.unit) {
- return (utc ? 'utc' : '') + keys(rest).map(p => varName(`${p === 'unit' ? '' : `_${p}_`}${rest[p]}`)).join('');
+ return (utc ? 'utc' : '') + keys(rest).map(p => varName("".concat(p === 'unit' ? '' : "_".concat(p, "_")).concat(rest[p]))).join('');
} else {
// when maxbins is specified instead of units
- return (utc ? 'utc' : '') + 'timeunit' + keys(rest).map(p => varName(`_${p}_${rest[p]}`)).join('');
+ return (utc ? 'utc' : '') + 'timeunit' + keys(rest).map(p => varName("_".concat(p, "_").concat(rest[p]))).join('');
}
}
function isSelectionPredicate(predicate) {
return predicate === null || predicate === void 0 ? void 0 : predicate['param'];
@@ -2786,21 +2880,21 @@
function isFieldGTEPredicate(predicate) {
return predicate && !!predicate.field && predicate.gte !== undefined;
}
function isFieldRangePredicate(predicate) {
if (predicate !== null && predicate !== void 0 && predicate.field) {
- if (vegaUtil.isArray(predicate.range) && predicate.range.length === 2) {
+ if (vega.isArray(predicate.range) && predicate.range.length === 2) {
return true;
} else if (isSignalRef(predicate.range)) {
return true;
}
}
return false;
}
function isFieldOneOfPredicate(predicate) {
- return predicate && !!predicate.field && (vegaUtil.isArray(predicate.oneOf) || vegaUtil.isArray(predicate.in)) // backward compatibility
+ return predicate && !!predicate.field && (vega.isArray(predicate.oneOf) || vega.isArray(predicate.in)) // backward compatibility
;
}
function isFieldValidPredicate(predicate) {
return predicate && !!predicate.field && predicate.valid !== undefined;
}
@@ -2818,79 +2912,82 @@
function predicateValuesExpr(vals, timeUnit) {
return vals.map(v => predicateValueExpr(v, timeUnit));
} // This method is used by Voyager. Do not change its behavior without changing Voyager.
- function fieldFilterExpression(predicate, useInRange = true) {
+ function fieldFilterExpression(predicate) {
var _normalizeTimeUnit;
+ let useInRange = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
const {
field
} = predicate;
const timeUnit = (_normalizeTimeUnit = normalizeTimeUnit(predicate.timeUnit)) === null || _normalizeTimeUnit === void 0 ? void 0 : _normalizeTimeUnit.unit;
const fieldExpr$1 = timeUnit ? // For timeUnit, cast into integer with time() so we can use ===, inrange, indexOf to compare values directly.
// TODO: We calculate timeUnit on the fly here. Consider if we would like to consolidate this with timeUnit pipeline
// TODO: support utc
- `time(${fieldExpr(timeUnit, field)})` : vgField(predicate, {
+ "time(".concat(fieldExpr(timeUnit, field), ")") : vgField(predicate, {
expr: 'datum'
});
if (isFieldEqualPredicate(predicate)) {
- return `${fieldExpr$1}===${predicateValueExpr(predicate.equal, timeUnit)}`;
+ return "".concat(fieldExpr$1, "===").concat(predicateValueExpr(predicate.equal, timeUnit));
} else if (isFieldLTPredicate(predicate)) {
const upper = predicate.lt;
- return `${fieldExpr$1}<${predicateValueExpr(upper, timeUnit)}`;
+ return "".concat(fieldExpr$1, "<").concat(predicateValueExpr(upper, timeUnit));
} else if (isFieldGTPredicate(predicate)) {
const lower = predicate.gt;
- return `${fieldExpr$1}>${predicateValueExpr(lower, timeUnit)}`;
+ return "".concat(fieldExpr$1, ">").concat(predicateValueExpr(lower, timeUnit));
} else if (isFieldLTEPredicate(predicate)) {
const upper = predicate.lte;
- return `${fieldExpr$1}<=${predicateValueExpr(upper, timeUnit)}`;
+ return "".concat(fieldExpr$1, "<=").concat(predicateValueExpr(upper, timeUnit));
} else if (isFieldGTEPredicate(predicate)) {
const lower = predicate.gte;
- return `${fieldExpr$1}>=${predicateValueExpr(lower, timeUnit)}`;
+ return "".concat(fieldExpr$1, ">=").concat(predicateValueExpr(lower, timeUnit));
} else if (isFieldOneOfPredicate(predicate)) {
- return `indexof([${predicateValuesExpr(predicate.oneOf, timeUnit).join(',')}], ${fieldExpr$1}) !== -1`;
+ return "indexof([".concat(predicateValuesExpr(predicate.oneOf, timeUnit).join(','), "], ").concat(fieldExpr$1, ") !== -1");
} else if (isFieldValidPredicate(predicate)) {
return fieldValidPredicate(fieldExpr$1, predicate.valid);
} else if (isFieldRangePredicate(predicate)) {
const {
range
} = predicate;
const lower = isSignalRef(range) ? {
- signal: `${range.signal}[0]`
+ signal: "".concat(range.signal, "[0]")
} : range[0];
const upper = isSignalRef(range) ? {
- signal: `${range.signal}[1]`
+ signal: "".concat(range.signal, "[1]")
} : range[1];
if (lower !== null && upper !== null && useInRange) {
return 'inrange(' + fieldExpr$1 + ', [' + predicateValueExpr(lower, timeUnit) + ', ' + predicateValueExpr(upper, timeUnit) + '])';
}
const exprs = [];
if (lower !== null) {
- exprs.push(`${fieldExpr$1} >= ${predicateValueExpr(lower, timeUnit)}`);
+ exprs.push("".concat(fieldExpr$1, " >= ").concat(predicateValueExpr(lower, timeUnit)));
}
if (upper !== null) {
- exprs.push(`${fieldExpr$1} <= ${predicateValueExpr(upper, timeUnit)}`);
+ exprs.push("".concat(fieldExpr$1, " <= ").concat(predicateValueExpr(upper, timeUnit)));
}
return exprs.length > 0 ? exprs.join(' && ') : 'true';
}
/* istanbul ignore next: it should never reach here */
- throw new Error(`Invalid field predicate: ${stringify(predicate)}`);
+ throw new Error("Invalid field predicate: ".concat(stringify(predicate)));
}
- function fieldValidPredicate(fieldExpr, valid = true) {
+ function fieldValidPredicate(fieldExpr) {
+ let valid = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
+
if (valid) {
- return `isValid(${fieldExpr}) && isFinite(+${fieldExpr})`;
+ return "isValid(".concat(fieldExpr, ") && isFinite(+").concat(fieldExpr, ")");
} else {
- return `!isValid(${fieldExpr}) || !isFinite(+${fieldExpr})`;
+ return "!isValid(".concat(fieldExpr, ") || !isFinite(+").concat(fieldExpr, ")");
}
}
function normalizePredicate$1(f) {
if (isFieldPredicate(f) && f.timeUnit) {
var _normalizeTimeUnit2;
@@ -2912,10 +3009,16 @@
ordinal: 'ordinal',
temporal: 'temporal',
nominal: 'nominal',
geojson: 'geojson'
};
+ function isContinuous(type) {
+ return type === 'quantitative' || type === 'temporal';
+ }
+ function isDiscrete$1(type) {
+ return type === 'ordinal' || type === 'nominal';
+ }
const QUANTITATIVE = Type.quantitative;
const ORDINAL = Type.ordinal;
const TEMPORAL = Type.temporal;
const NOMINAL = Type.nominal;
const GEOJSON = Type.geojson;
@@ -3042,39 +3145,36 @@
*/
function scaleTypePrecedence(scaleType) {
return SCALE_PRECEDENCE_INDEX[scaleType];
}
- const CONTINUOUS_TO_CONTINUOUS_SCALES = ['linear', 'log', 'pow', 'sqrt', 'symlog', 'time', 'utc'];
- const CONTINUOUS_TO_CONTINUOUS_INDEX = vegaUtil.toSet(CONTINUOUS_TO_CONTINUOUS_SCALES);
- const QUANTITATIVE_SCALES = ['linear', 'log', 'pow', 'sqrt', 'symlog'];
- const QUANTITATIVE_SCALES_INDEX = vegaUtil.toSet(QUANTITATIVE_SCALES);
+ const QUANTITATIVE_SCALES = new Set(['linear', 'log', 'pow', 'sqrt', 'symlog']);
+ const CONTINUOUS_TO_CONTINUOUS_SCALES = new Set([...QUANTITATIVE_SCALES, 'time', 'utc']);
function isQuantitative(type) {
- return type in QUANTITATIVE_SCALES_INDEX;
+ return QUANTITATIVE_SCALES.has(type);
}
- const CONTINUOUS_TO_DISCRETE_SCALES = ['quantile', 'quantize', 'threshold'];
- const CONTINUOUS_TO_DISCRETE_INDEX = vegaUtil.toSet(CONTINUOUS_TO_DISCRETE_SCALES);
- const CONTINUOUS_DOMAIN_SCALES = CONTINUOUS_TO_CONTINUOUS_SCALES.concat(['quantile', 'quantize', 'threshold', 'sequential', 'identity']);
- const CONTINUOUS_DOMAIN_INDEX = vegaUtil.toSet(CONTINUOUS_DOMAIN_SCALES);
- const DISCRETE_DOMAIN_SCALES = ['ordinal', 'bin-ordinal', 'point', 'band'];
- const DISCRETE_DOMAIN_INDEX = vegaUtil.toSet(DISCRETE_DOMAIN_SCALES);
+ const CONTINUOUS_TO_DISCRETE_SCALES = new Set(['quantile', 'quantize', 'threshold']);
+ const CONTINUOUS_DOMAIN_SCALES = new Set([...CONTINUOUS_TO_CONTINUOUS_SCALES, ...CONTINUOUS_TO_DISCRETE_SCALES, 'sequential', 'identity']);
+ const DISCRETE_DOMAIN_SCALES = new Set(['ordinal', 'bin-ordinal', 'point', 'band']);
function hasDiscreteDomain(type) {
- return type in DISCRETE_DOMAIN_INDEX;
+ return DISCRETE_DOMAIN_SCALES.has(type);
}
function hasContinuousDomain(type) {
- return type in CONTINUOUS_DOMAIN_INDEX;
+ return CONTINUOUS_DOMAIN_SCALES.has(type);
}
function isContinuousToContinuous(type) {
- return type in CONTINUOUS_TO_CONTINUOUS_INDEX;
+ return CONTINUOUS_TO_CONTINUOUS_SCALES.has(type);
}
function isContinuousToDiscrete(type) {
- return type in CONTINUOUS_TO_DISCRETE_INDEX;
+ return CONTINUOUS_TO_DISCRETE_SCALES.has(type);
}
const defaultScaleConfig = {
pointPadding: 0.5,
barBandPaddingInner: 0.1,
rectBandPaddingInner: 0,
+ bandWithNestedOffsetPaddingInner: 0.2,
+ bandWithNestedOffsetPaddingOuter: 0.2,
minBandSize: 2,
minFontSize: 8,
maxFontSize: 40,
minOpacity: 0.3,
maxOpacity: 0.8,
@@ -3085,11 +3185,11 @@
maxStrokeWidth: 4,
quantileCount: 4,
quantizeCount: 4
};
function isExtendedScheme(scheme) {
- return !vegaUtil.isString(scheme) && !!scheme['name'];
+ return !vega.isString(scheme) && !!scheme['name'];
}
function isParameterDomain(domain) {
return domain === null || domain === void 0 ? void 0 : domain['param'];
}
function isDomainUnionWith(domain) {
@@ -3237,27 +3337,43 @@
if (contains([ORDINAL, NOMINAL], fieldDefType)) {
return specifiedType === undefined || hasDiscreteDomain(specifiedType);
} else if (fieldDefType === TEMPORAL) {
return contains([ScaleType.TIME, ScaleType.UTC, undefined], specifiedType);
} else if (fieldDefType === QUANTITATIVE) {
- return contains([ScaleType.LOG, ScaleType.POW, ScaleType.SQRT, ScaleType.SYMLOG, ScaleType.QUANTILE, ScaleType.QUANTIZE, ScaleType.THRESHOLD, ScaleType.LINEAR, undefined], specifiedType);
+ return isQuantitative(specifiedType) || isContinuousToDiscrete(specifiedType) || specifiedType === undefined;
}
return true;
}
function channelSupportScaleType(channel, scaleType) {
+ let hasNestedOffsetScale = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
+
if (!isScaleChannel(channel)) {
return false;
}
switch (channel) {
case X:
case Y:
+ case XOFFSET:
+ case YOFFSET:
case THETA:
case RADIUS:
- return isContinuousToContinuous(scaleType) || contains(['band', 'point'], scaleType);
+ if (isContinuousToContinuous(scaleType)) {
+ return true;
+ } else if (scaleType === 'band') {
+ return true;
+ } else if (scaleType === 'point') {
+ /*
+ Point scale can't be use if the position has a nested offset scale
+ because if there is a nested scale, then it's band.
+ */
+ return !hasNestedOffsetScale;
+ }
+ return false;
+
case SIZE: // TODO: size and opacity can support ordinal with more modification
case STROKEWIDTH:
case OPACITY:
case FILLOPACITY:
@@ -3318,15 +3434,14 @@
function isRectBasedMark(m) {
return ['rect', 'bar', 'image', 'arc'
/* arc is rect/interval in polar coordinate */
].includes(m);
}
- const PRIMITIVE_MARKS = keys(Mark);
+ const PRIMITIVE_MARKS = new Set(keys(Mark));
function isMarkDef(mark) {
return mark['type'];
}
- vegaUtil.toSet(PRIMITIVE_MARKS);
const STROKE_CONFIG = ['stroke', 'strokeWidth', 'strokeDash', 'strokeDashOffset', 'strokeOpacity', 'strokeJoin', 'strokeMiterLimit'];
const FILL_CONFIG = ['fill', 'fillOpacity'];
const FILL_STROKE_CONFIG = [...STROKE_CONFIG, ...FILL_CONFIG];
const VL_ONLY_MARK_CONFIG_INDEX = {
color: 1,
@@ -3407,12 +3522,12 @@
config
} = params;
const ref = midPoint(params); // Wrap to check if the positional value is invalid, if so, plot the point on the min value
if ( // Only this for field def without counting aggregate (as count wouldn't be null)
- isFieldDef(channelDef) && !isCountingAggregateOp(channelDef.aggregate) && // and only for continuous scale without zero (otherwise, null / invalid will be interpreted as zero, which doesn't cause layout problem)
- scale && isContinuousToContinuous(scale.get('type')) && scale.get('zero') === false) {
+ isFieldDef(channelDef) && !isCountingAggregateOp(channelDef.aggregate) && // and only for continuous scale
+ scale && isContinuousToContinuous(scale.get('type'))) {
return wrapPositionInvalidTest({
fieldDef: channelDef,
channel,
markDef,
ref,
@@ -3420,30 +3535,32 @@
});
}
return ref;
}
- function wrapPositionInvalidTest({
- fieldDef,
- channel,
- markDef,
- ref,
- config
- }) {
+ function wrapPositionInvalidTest(_ref) {
+ let {
+ fieldDef,
+ channel,
+ markDef,
+ ref,
+ config
+ } = _ref;
+
if (isPathMark(markDef.type)) {
// path mark already use defined to skip points, no need to do it here.
return ref;
}
const invalid = getMarkPropOrConfig('invalid', markDef, config);
if (invalid === null) {
// if there is no invalid filter, don't do the invalid test
- return ref;
+ return [fieldInvalidTestValueRef(fieldDef, channel), ref];
}
- return [fieldInvalidTestValueRef(fieldDef, channel), ref];
+ return ref;
}
function fieldInvalidTestValueRef(fieldDef, channel) {
const test = fieldInvalidPredicate(fieldDef, true);
const mainChannel = getMainRangeChannel(channel); // we can cast here as the output can't be other things.
@@ -3458,12 +3575,13 @@
return {
test,
...zeroValueRef
};
}
- function fieldInvalidPredicate(field, invalid = true) {
- return fieldValidPredicate(vegaUtil.isString(field) ? field : vgField(field, {
+ function fieldInvalidPredicate(field) {
+ let invalid = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
+ return fieldValidPredicate(vega.isString(field) ? field : vgField(field, {
expr: 'datum'
}), !invalid);
}
function datumDefToExpr(datumDef) {
const {
@@ -3472,11 +3590,11 @@
if (isDateTime(datum)) {
return dateTimeToExpr(datum);
}
- return `${stringify(datum)}`;
+ return "".concat(stringify(datum));
}
function valueRefForFieldOrDatumDef(fieldDef, scaleName, opt, encode) {
const ref = {};
if (scaleName) {
@@ -3520,18 +3638,19 @@
}
/**
* Signal that returns the middle of a bin from start and end field. Should only be used with x and y.
*/
- function interpolatedSignalRef({
- scaleName,
- fieldOrDatumDef,
- fieldOrDatumDef2,
- offset,
- startSuffix,
- bandPosition = 0.5
- }) {
+ function interpolatedSignalRef(_ref2) {
+ let {
+ scaleName,
+ fieldOrDatumDef,
+ fieldOrDatumDef2,
+ offset,
+ startSuffix,
+ bandPosition = 0.5
+ } = _ref2;
const expr = 0 < bandPosition && bandPosition < 1 ? 'datum' : undefined;
const start = vgField(fieldOrDatumDef, {
expr,
suffix: startSuffix
});
@@ -3546,12 +3665,12 @@
if (bandPosition === 0 || bandPosition === 1) {
ref.scale = scaleName;
const val = bandPosition === 0 ? start : end;
ref.field = val;
} else {
- const datum = isSignalRef(bandPosition) ? `${bandPosition.signal} * ${start} + (1-${bandPosition.signal}) * ${end}` : `${bandPosition} * ${start} + ${1 - bandPosition} * ${end}`;
- ref.signal = `scale("${scaleName}", ${datum})`;
+ const datum = isSignalRef(bandPosition) ? "".concat(bandPosition.signal, " * ").concat(start, " + (1-").concat(bandPosition.signal, ") * ").concat(end) : "".concat(bandPosition, " * ").concat(start, " + ").concat(1 - bandPosition, " * ").concat(end);
+ ref.signal = "scale(\"".concat(scaleName, "\", ").concat(datum, ")");
}
if (offset) {
ref.offset = offset;
}
@@ -3560,34 +3679,42 @@
}
/**
* @returns {VgValueRef} Value Ref for xc / yc or mid point for other channels.
*/
- function midPoint({
- channel,
- channelDef,
- channel2Def,
- markDef,
- config,
- scaleName,
- scale,
- stack,
- offset,
- defaultRef,
- bandPosition
- }) {
+ function midPoint(_ref3) {
+ let {
+ channel,
+ channelDef,
+ channel2Def,
+ markDef,
+ config,
+ scaleName,
+ scale,
+ stack,
+ offset,
+ defaultRef,
+ bandPosition
+ } = _ref3;
+
// TODO: datum support
if (channelDef) {
/* istanbul ignore else */
if (isFieldOrDatumDef(channelDef)) {
+ var _ref4, _bandPosition2;
+
+ const scaleType = scale === null || scale === void 0 ? void 0 : scale.get('type');
+
if (isTypedFieldDef(channelDef)) {
- bandPosition ?? (bandPosition = getBandPosition({
+ var _bandPosition;
+
+ (_bandPosition = bandPosition) !== null && _bandPosition !== void 0 ? _bandPosition : bandPosition = getBandPosition({
fieldDef: channelDef,
fieldDef2: channel2Def,
markDef,
config
- }));
+ });
const {
bin,
timeUnit,
type
} = channelDef;
@@ -3602,11 +3729,11 @@
}, {
offset
});
}
- if (bandPosition) {
+ if (bandPosition && !hasDiscreteDomain(scaleType)) {
// if band = 0, no need to call interpolation
// For non-stack, we can just calculate bin mid on the fly using signal.
return interpolatedSignalRef({
scaleName,
fieldOrDatumDef: channelDef,
@@ -3634,18 +3761,17 @@
warn(channelRequiredForBinned(channel2));
}
}
}
- const scaleType = scale === null || scale === void 0 ? void 0 : scale.get('type');
return valueRefForFieldOrDatumDef(channelDef, scaleName, hasDiscreteDomain(scaleType) ? {
binSuffix: 'range'
} : {}, // no need for bin suffix if there is no scale
{
offset,
// For band, to get mid point, need to offset by half of the band
- band: scaleType === 'band' ? bandPosition ?? channelDef.bandPosition ?? 0.5 : undefined
+ band: scaleType === 'band' ? (_ref4 = (_bandPosition2 = bandPosition) !== null && _bandPosition2 !== void 0 ? _bandPosition2 : channelDef.bandPosition) !== null && _ref4 !== void 0 ? _ref4 : 0.5 : undefined
});
} else if (isValueDef(channelDef)) {
const value = channelDef.value;
const offsetMixins = offset ? {
offset
@@ -3656,11 +3782,11 @@
} // If channelDef is neither field def or value def, it's a condition-only def.
// In such case, we will use default ref.
}
- if (vegaUtil.isFunction(defaultRef)) {
+ if (vega.isFunction(defaultRef)) {
defaultRef = defaultRef();
}
if (defaultRef) {
// for non-position, ref could be undefined.
@@ -3699,22 +3825,24 @@
function isCustomFormatType(formatType) {
return formatType && formatType !== 'number' && formatType !== 'time';
}
function customFormatExpr(formatType, field, format) {
- return `${formatType}(${field}${format ? `, ${stringify(format)}` : ''})`;
+ return "".concat(formatType, "(").concat(field).concat(format ? ", ".concat(stringify(format)) : '', ")");
}
const BIN_RANGE_DELIMITER = ' \u2013 ';
- function formatSignalRef({
- fieldOrDatumDef,
- format,
- formatType,
- expr,
- normalizeStack,
- config
- }) {
+ function formatSignalRef(_ref) {
+ let {
+ fieldOrDatumDef,
+ format,
+ formatType,
+ expr,
+ normalizeStack,
+ config
+ } = _ref;
+
if (isCustomFormatType(formatType)) {
return formatCustomType({
fieldOrDatumDef,
format,
formatType,
@@ -3744,50 +3872,53 @@
return {
signal: binFormatExpression(field, endField, format, formatType, config)
};
} else if (format || channelDefType(fieldOrDatumDef) === 'quantitative') {
return {
- signal: `${formatExpr(field, format)}`
+ signal: "".concat(formatExpr(field, format))
};
} else {
return {
- signal: `isValid(${field}) ? ${field} : ""+${field}`
+ signal: "isValid(".concat(field, ") ? ").concat(field, " : \"\"+").concat(field)
};
}
}
function fieldToFormat(fieldOrDatumDef, expr, normalizeStack) {
if (isFieldDef(fieldOrDatumDef)) {
if (normalizeStack) {
- return `${vgField(fieldOrDatumDef, {
- expr,
- suffix: 'end'
- })}-${vgField(fieldOrDatumDef, {
- expr,
- suffix: 'start'
- })}`;
+ return "".concat(vgField(fieldOrDatumDef, {
+ expr,
+ suffix: 'end'
+ }), "-").concat(vgField(fieldOrDatumDef, {
+ expr,
+ suffix: 'start'
+ }));
} else {
return vgField(fieldOrDatumDef, {
expr
});
}
} else {
return datumDefToExpr(fieldOrDatumDef);
}
}
- function formatCustomType({
- fieldOrDatumDef,
- format,
- formatType,
- expr,
- normalizeStack,
- config,
- field
- }) {
- field ?? (field = fieldToFormat(fieldOrDatumDef, expr, normalizeStack));
+ function formatCustomType(_ref2) {
+ var _field;
+ let {
+ fieldOrDatumDef,
+ format,
+ formatType,
+ expr,
+ normalizeStack,
+ config,
+ field
+ } = _ref2;
+ (_field = field) !== null && _field !== void 0 ? _field : field = fieldToFormat(fieldOrDatumDef, expr, normalizeStack);
+
if (isFieldDef(fieldOrDatumDef) && isBinning(fieldOrDatumDef.bin)) {
const endField = vgField(fieldOrDatumDef, {
expr,
binSuffix: 'end'
});
@@ -3829,11 +3960,11 @@
* Returns number format for a fieldDef.
*/
function numberFormat(type, specifiedFormat, config) {
// Specified format in axis/legend has higher precedence than fieldDef.format
- if (vegaUtil.isString(specifiedFormat)) {
+ if (vega.isString(specifiedFormat)) {
return specifiedFormat;
}
if (type === QUANTITATIVE) {
// we only apply the default if the field is quantitative
@@ -3859,37 +3990,39 @@
return omitTimeFormatConfig ? undefined : config.timeFormat;
}
function formatExpr(field, format) {
- return `format(${field}, "${format || ''}")`;
+ return "format(".concat(field, ", \"").concat(format || '', "\")");
}
function binNumberFormatExpr(field, format, formatType, config) {
+ var _ref3;
+
if (isCustomFormatType(formatType)) {
return customFormatExpr(formatType, field, format);
}
- return formatExpr(field, (vegaUtil.isString(format) ? format : undefined) ?? config.numberFormat);
+ return formatExpr(field, (_ref3 = vega.isString(format) ? format : undefined) !== null && _ref3 !== void 0 ? _ref3 : config.numberFormat);
}
function binFormatExpression(startField, endField, format, formatType, config) {
const start = binNumberFormatExpr(startField, format, formatType, config);
const end = binNumberFormatExpr(endField, format, formatType, config);
- return `${fieldValidPredicate(startField, false)} ? "null" : ${start} + "${BIN_RANGE_DELIMITER}" + ${end}`;
+ return "".concat(fieldValidPredicate(startField, false), " ? \"null\" : ").concat(start, " + \"").concat(BIN_RANGE_DELIMITER, "\" + ").concat(end);
}
/**
* Returns the time expression used for axis/legend labels or text mark for a temporal field
*/
function timeFormatExpression(field, timeUnit, format, rawTimeFormat, // should be provided only for actual text and headers, not axis/legend labels
isUTCScale) {
if (!timeUnit || format) {
// If there is no time unit, or if user explicitly specifies format for axis/legend/text.
- format = vegaUtil.isString(format) ? format : rawTimeFormat; // only use provided timeFormat if there is no timeUnit.
+ format = vega.isString(format) ? format : rawTimeFormat; // only use provided timeFormat if there is no timeUnit.
- return `${isUTCScale ? 'utc' : 'time'}Format(${field}, '${format}')`;
+ return "".concat(isUTCScale ? 'utc' : 'time', "Format(").concat(field, ", '").concat(format, "')");
} else {
return formatExpression(timeUnit, field, isUTCScale);
}
}
@@ -3920,11 +4053,11 @@
}
function isSortField(sort) {
return !!sort && (sort['op'] === 'count' || !!sort['field']);
}
function isSortArray(sort) {
- return !!sort && vegaUtil.isArray(sort);
+ return !!sort && vega.isArray(sort);
}
function isFacetMapping(f) {
return 'row' in f || 'column' in f;
}
@@ -3945,11 +4078,11 @@
function isConditionalParameter(c) {
return c['param'];
}
function isRepeatRef(field) {
- return field && !vegaUtil.isString(field) && 'repeat' in field;
+ return field && !vega.isString(field) && 'repeat' in field;
}
/** @@hidden */
function toFieldDefBase(fieldDef) {
const {
@@ -3971,16 +4104,18 @@
};
}
function isSortableFieldDef(fieldDef) {
return 'sort' in fieldDef;
}
- function getBandPosition({
- fieldDef,
- fieldDef2,
- markDef: mark,
- config
- }) {
+ function getBandPosition(_ref) {
+ let {
+ fieldDef,
+ fieldDef2,
+ markDef: mark,
+ config
+ } = _ref;
+
if (isFieldOrDatumDef(fieldDef) && fieldDef.bandPosition !== undefined) {
return fieldDef.bandPosition;
}
if (isFieldDef(fieldDef)) {
@@ -3996,20 +4131,21 @@
}
}
return undefined;
}
- function getBandSize({
- channel,
- fieldDef,
- fieldDef2,
- markDef: mark,
- config,
- scaleType,
- useVlSizeChannel
- }) {
- const sizeChannel = getSizeChannel$1(channel);
+ function getBandSize(_ref2) {
+ let {
+ channel,
+ fieldDef,
+ fieldDef2,
+ markDef: mark,
+ config,
+ scaleType,
+ useVlSizeChannel
+ } = _ref2;
+ const sizeChannel = getSizeChannel(channel);
const size = getMarkPropOrConfig(useVlSizeChannel ? 'size' : sizeChannel, mark, config, {
vgChannel: sizeChannel
});
if (size !== undefined) {
@@ -4080,19 +4216,19 @@
* Return if a channelDef is a ConditionalValueDef with ConditionFieldDef
*/
function hasConditionalFieldDef(channelDef) {
const condition = channelDef && channelDef['condition'];
- return !!condition && !vegaUtil.isArray(condition) && isFieldDef(condition);
+ return !!condition && !vega.isArray(condition) && isFieldDef(condition);
}
function hasConditionalFieldOrDatumDef(channelDef) {
const condition = channelDef && channelDef['condition'];
- return !!condition && !vegaUtil.isArray(condition) && isFieldOrDatumDef(condition);
+ return !!condition && !vega.isArray(condition) && isFieldOrDatumDef(condition);
}
function hasConditionalValueDef(channelDef) {
const condition = channelDef && channelDef['condition'];
- return !!condition && (vegaUtil.isArray(condition) || isValueDef(condition));
+ return !!condition && (vega.isArray(condition) || isValueDef(condition));
}
function isFieldDef(channelDef) {
// TODO: we can't use field in channelDef here as it's somehow failing runtime test
return channelDef && (!!channelDef['field'] || channelDef['aggregate'] === 'count');
}
@@ -4105,11 +4241,11 @@
function isContinuousFieldOrDatumDef(cd) {
// TODO: make datum support DateTime object
return isTypedFieldDef(cd) && !isDiscrete(cd) || isNumericDataDef(cd);
}
function isNumericDataDef(cd) {
- return isDatumDef(cd) && vegaUtil.isNumber(cd.datum);
+ return isDatumDef(cd) && vega.isNumber(cd.datum);
}
function isFieldOrDatumDef(channelDef) {
return isFieldDef(channelDef) || isDatumDef(channelDef);
}
function isTypedFieldDef(channelDef) {
@@ -4141,11 +4277,12 @@
/**
* Get a Vega field reference from a Vega-Lite field def.
*/
- function vgField(fieldDef, opt = {}) {
+ function vgField(fieldDef) {
+ let opt = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let field = fieldDef.field;
const prefix = opt.prefix;
let suffix = opt.suffix;
let argAccessor = ''; // for accessing argmin/argmax field at the end without getting escaped
@@ -4163,40 +4300,44 @@
aggregate,
timeUnit
} = fieldDef;
if (isBinning(bin)) {
+ var _opt$binSuffix, _opt$suffix;
+
fn = binToString(bin);
- suffix = (opt.binSuffix ?? '') + (opt.suffix ?? '');
+ suffix = ((_opt$binSuffix = opt.binSuffix) !== null && _opt$binSuffix !== void 0 ? _opt$binSuffix : '') + ((_opt$suffix = opt.suffix) !== null && _opt$suffix !== void 0 ? _opt$suffix : '');
} else if (aggregate) {
if (isArgmaxDef(aggregate)) {
- argAccessor = `["${field}"]`;
- field = `argmax_${aggregate.argmax}`;
+ argAccessor = "[\"".concat(field, "\"]");
+ field = "argmax_".concat(aggregate.argmax);
} else if (isArgminDef(aggregate)) {
- argAccessor = `["${field}"]`;
- field = `argmin_${aggregate.argmin}`;
+ argAccessor = "[\"".concat(field, "\"]");
+ field = "argmin_".concat(aggregate.argmin);
} else {
fn = String(aggregate);
}
} else if (timeUnit) {
+ var _opt$suffix2;
+
fn = timeUnitToString(timeUnit);
- suffix = (!['range', 'mid'].includes(opt.binSuffix) && opt.binSuffix || '') + (opt.suffix ?? '');
+ suffix = (!['range', 'mid'].includes(opt.binSuffix) && opt.binSuffix || '') + ((_opt$suffix2 = opt.suffix) !== null && _opt$suffix2 !== void 0 ? _opt$suffix2 : '');
}
}
}
if (fn) {
- field = field ? `${fn}_${field}` : fn;
+ field = field ? "".concat(fn, "_").concat(field) : fn;
}
}
if (suffix) {
- field = `${field}_${suffix}`;
+ field = "".concat(field, "_").concat(suffix);
}
if (prefix) {
- field = `${prefix}_${field}`;
+ field = "".concat(prefix, "_").concat(field);
}
if (opt.forAs) {
return removePathFromField(field);
} else if (opt.expr) {
@@ -4240,26 +4381,26 @@
} = fieldDef;
if (aggregate === 'count') {
return config.countTitle;
} else if (isBinning(bin)) {
- return `${field} (binned)`;
+ return "".concat(field, " (binned)");
} else if (timeUnit) {
var _normalizeTimeUnit;
const unit = (_normalizeTimeUnit = normalizeTimeUnit(timeUnit)) === null || _normalizeTimeUnit === void 0 ? void 0 : _normalizeTimeUnit.unit;
if (unit) {
- return `${field} (${getTimeUnitParts(unit).join('-')})`;
+ return "".concat(field, " (").concat(getTimeUnitParts(unit).join('-'), ")");
}
} else if (aggregate) {
if (isArgmaxDef(aggregate)) {
- return `${field} for max ${aggregate.argmax}`;
+ return "".concat(field, " for max ").concat(aggregate.argmax);
} else if (isArgminDef(aggregate)) {
- return `${field} for min ${aggregate.argmin}`;
+ return "".concat(field, " for min ").concat(aggregate.argmin);
} else {
- return `${titleCase(aggregate)} of ${field}`;
+ return "".concat(titleCase(aggregate), " of ").concat(field);
}
}
return field;
}
@@ -4270,20 +4411,20 @@
timeUnit,
field
} = fieldDef;
if (isArgmaxDef(aggregate)) {
- return `${field} for argmax(${aggregate.argmax})`;
+ return "".concat(field, " for argmax(").concat(aggregate.argmax, ")");
} else if (isArgminDef(aggregate)) {
- return `${field} for argmin(${aggregate.argmin})`;
+ return "".concat(field, " for argmin(").concat(aggregate.argmin, ")");
}
const timeUnitParams = normalizeTimeUnit(timeUnit);
const fn = aggregate || (timeUnitParams === null || timeUnitParams === void 0 ? void 0 : timeUnitParams.unit) || (timeUnitParams === null || timeUnitParams === void 0 ? void 0 : timeUnitParams.maxbins) && 'timeunit' || isBinning(bin) && 'bin';
if (fn) {
- return `${fn.toUpperCase()}(${field})`;
+ return "".concat(fn.toUpperCase(), "(").concat(field, ")");
} else {
return field;
}
}
const defaultTitleFormatter = (fieldDef, config) => {
@@ -4303,29 +4444,32 @@
titleFormatter = formatter;
}
function resetTitleFormatter() {
setTitleFormatter(defaultTitleFormatter);
}
- function title(fieldOrDatumDef, config, {
- allowDisabling,
- includeDefault = true
- }) {
+ function title(fieldOrDatumDef, config, _ref3) {
var _getGuide;
+ let {
+ allowDisabling,
+ includeDefault = true
+ } = _ref3;
const guideTitle = (_getGuide = getGuide(fieldOrDatumDef)) === null || _getGuide === void 0 ? void 0 : _getGuide.title;
if (!isFieldDef(fieldOrDatumDef)) {
- return guideTitle;
+ return guideTitle !== null && guideTitle !== void 0 ? guideTitle : fieldOrDatumDef.title;
}
const fieldDef = fieldOrDatumDef;
const def = includeDefault ? defaultTitle(fieldDef, config) : undefined;
if (allowDisabling) {
return getFirstDefined(guideTitle, fieldDef.title, def);
} else {
- return guideTitle ?? fieldDef.title ?? def;
+ var _ref4;
+
+ return (_ref4 = guideTitle !== null && guideTitle !== void 0 ? guideTitle : fieldDef.title) !== null && _ref4 !== void 0 ? _ref4 : def;
}
}
function getGuide(fieldDef) {
if (isPositionFieldOrDatumDef(fieldDef) && fieldDef.axis) {
return fieldDef.axis;
@@ -4349,11 +4493,13 @@
return {
format,
formatType
};
} else {
- const guide = getGuide(fieldDef) ?? {};
+ var _getGuide2;
+
+ const guide = (_getGuide2 = getGuide(fieldDef)) !== null && _getGuide2 !== void 0 ? _getGuide2 : {};
const {
format,
formatType
} = guide;
return {
@@ -4379,11 +4525,11 @@
case 'order':
return 'ordinal';
}
- if (isSortableFieldDef(fieldDef) && vegaUtil.isArray(fieldDef.sort)) {
+ if (isSortableFieldDef(fieldDef) && vega.isArray(fieldDef.sort)) {
return 'ordinal';
}
const {
aggregate,
@@ -4437,13 +4583,15 @@
}
/**
* Convert type to full, lowercase type, or augment the fieldDef with a default type if missing.
*/
- function initChannelDef(channelDef, channel, config, opt = {}) {
- if (vegaUtil.isString(channelDef) || vegaUtil.isNumber(channelDef) || vegaUtil.isBoolean(channelDef)) {
- const primitiveType = vegaUtil.isString(channelDef) ? 'string' : vegaUtil.isNumber(channelDef) ? 'number' : 'boolean';
+ function initChannelDef(channelDef, channel, config) {
+ let opt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
+
+ if (vega.isString(channelDef) || vega.isNumber(channelDef) || vega.isBoolean(channelDef)) {
+ const primitiveType = vega.isString(channelDef) ? 'string' : vega.isNumber(channelDef) ? 'number' : 'boolean';
warn(primitiveChannelDef(channel, primitiveType, channelDef));
return {
value: channelDef
};
} // If a fieldDef contains a field, we need type.
@@ -4506,19 +4654,20 @@
}
const {
datum
} = datumDef;
- type = vegaUtil.isNumber(datum) ? 'quantitative' : vegaUtil.isString(datum) ? 'nominal' : isDateTime(datum) ? 'temporal' : undefined;
+ type = vega.isNumber(datum) ? 'quantitative' : vega.isString(datum) ? 'nominal' : isDateTime(datum) ? 'temporal' : undefined;
return { ...datumDef,
type
};
}
- function initFieldDef(fd, channel, {
- compositeMark = false
- } = {}) {
+ function initFieldDef(fd, channel) {
+ let {
+ compositeMark = false
+ } = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
const {
aggregate,
timeUnit,
bin,
field
@@ -4535,11 +4684,11 @@
if (timeUnit) {
fieldDef.timeUnit = normalizeTimeUnit(timeUnit);
}
if (field) {
- fieldDef.field = `${field}`;
+ fieldDef.field = "".concat(field);
} // Normalize bin
if (isBinning(bin)) {
fieldDef.bin = normalizeBin(bin, channel);
@@ -4582,11 +4731,11 @@
if (compatible === false) {
warn(warning);
}
}
- if (isSortableFieldDef(fieldDef) && vegaUtil.isString(fieldDef.sort)) {
+ if (isSortableFieldDef(fieldDef) && vega.isString(fieldDef.sort)) {
const {
sort
} = fieldDef;
if (isSortByChannel(sort)) {
@@ -4632,11 +4781,11 @@
}
return fieldDef;
}
function normalizeBin(bin, channel) {
- if (vegaUtil.isBoolean(bin)) {
+ if (vega.isBoolean(bin)) {
return {
maxbins: autoMaxBins(channel)
};
} else if (bin === 'binned') {
return {
@@ -4657,11 +4806,11 @@
const type = fieldDef.type;
if (type === 'geojson' && channel !== 'shape') {
return {
compatible: false,
- warning: `Channel ${channel} should not be used with a geojson data.`
+ warning: "Channel ".concat(channel, " should not be used with a geojson data.")
};
}
switch (channel) {
case ROW:
@@ -4676,10 +4825,12 @@
return COMPATIBLE;
case X:
case Y:
+ case XOFFSET:
+ case YOFFSET:
case COLOR:
case FILL:
case STROKE:
case TEXT$1:
case DETAIL:
@@ -4698,11 +4849,11 @@
case LATITUDE:
case LATITUDE2:
if (type !== QUANTITATIVE) {
return {
compatible: false,
- warning: `Channel ${channel} should be used with a quantitative field only, not ${fieldDef.type} field.`
+ warning: "Channel ".concat(channel, " should be used with a quantitative field only, not ").concat(fieldDef.type, " field.")
};
}
return COMPATIBLE;
@@ -4716,11 +4867,11 @@
case X2:
case Y2:
if (type === 'nominal' && !fieldDef['sort']) {
return {
compatible: false,
- warning: `Channel ${channel} should not be used with an unsorted discrete field.`
+ warning: "Channel ".concat(channel, " should not be used with an unsorted discrete field.")
};
}
return COMPATIBLE;
@@ -4737,11 +4888,11 @@
case ORDER:
if (fieldDef.type === 'nominal' && !('sort' in fieldDef)) {
return {
compatible: false,
- warning: `Channel order is inappropriate for nominal field, which has no inherent order.`
+ warning: "Channel order is inappropriate for nominal field, which has no inherent order."
};
}
return COMPATIBLE;
}
@@ -4767,18 +4918,19 @@
/**
* Getting a value associated with a fielddef.
* Convert the value to Vega expression if applicable (for datetime object, or string if the field def is temporal or has timeUnit)
*/
- function valueExpr(v, {
- timeUnit,
- type,
- wrapTime,
- undefinedIfExprNotRequired
- }) {
+ function valueExpr(v, _ref5) {
var _normalizeTimeUnit2;
+ let {
+ timeUnit,
+ type,
+ wrapTime,
+ undefinedIfExprNotRequired
+ } = _ref5;
const unit = timeUnit && ((_normalizeTimeUnit2 = normalizeTimeUnit(timeUnit)) === null || _normalizeTimeUnit2 === void 0 ? void 0 : _normalizeTimeUnit2.unit);
let isTime = unit || type === 'temporal';
let expr;
if (isExprRef(v)) {
@@ -4786,27 +4938,27 @@
} else if (isSignalRef(v)) {
expr = v.signal;
} else if (isDateTime(v)) {
isTime = true;
expr = dateTimeToExpr(v);
- } else if (vegaUtil.isString(v) || vegaUtil.isNumber(v)) {
+ } else if (vega.isString(v) || vega.isNumber(v)) {
if (isTime) {
- expr = `datetime(${stringify(v)})`;
+ expr = "datetime(".concat(stringify(v), ")");
if (isLocalSingleTimeUnit(unit)) {
// for single timeUnit, we will use dateTimeToExpr to convert number/string to match the timeUnit
- if (vegaUtil.isNumber(v) && v < 10000 || vegaUtil.isString(v) && isNaN(Date.parse(v))) {
+ if (vega.isNumber(v) && v < 10000 || vega.isString(v) && isNaN(Date.parse(v))) {
expr = dateTimeToExpr({
[unit]: v
});
}
}
}
}
if (expr) {
- return wrapTime && isTime ? `time(${expr})` : expr;
+ return wrapTime && isTime ? "time(".concat(expr, ")") : expr;
} // number or boolean or normal string
return undefinedIfExprNotRequired ? undefined : stringify(v);
}
@@ -5173,25 +5325,50 @@
function channelHasField(encoding, channel) {
const channelDef = encoding && encoding[channel];
if (channelDef) {
- if (vegaUtil.isArray(channelDef)) {
+ if (vega.isArray(channelDef)) {
return some(channelDef, fieldDef => !!fieldDef.field);
} else {
return isFieldDef(channelDef) || hasConditionalFieldDef(channelDef);
}
}
return false;
}
+ function channelHasFieldOrDatum(encoding, channel) {
+ const channelDef = encoding && encoding[channel];
+
+ if (channelDef) {
+ if (vega.isArray(channelDef)) {
+ return some(channelDef, fieldDef => !!fieldDef.field);
+ } else {
+ return isFieldDef(channelDef) || isDatumDef(channelDef) || hasConditionalFieldOrDatumDef(channelDef);
+ }
+ }
+
+ return false;
+ }
+ function channelHasNestedOffsetScale(encoding, channel) {
+ if (isXorY(channel)) {
+ const fieldDef = encoding[channel];
+
+ if ((isFieldDef(fieldDef) || isDatumDef(fieldDef)) && isDiscrete$1(fieldDef.type)) {
+ const offsetChannel = getOffsetScaleChannel(channel);
+ return channelHasFieldOrDatum(encoding, offsetChannel);
+ }
+ }
+
+ return false;
+ }
function isAggregate$1(encoding) {
return some(CHANNELS, channel => {
if (channelHasField(encoding, channel)) {
const channelDef = encoding[channel];
- if (vegaUtil.isArray(channelDef)) {
+ if (vega.isArray(channelDef)) {
return some(channelDef, fieldDef => !!fieldDef.aggregate);
} else {
const fieldDef = getFieldDef(channelDef);
return fieldDef && !!fieldDef.aggregate;
}
@@ -5243,20 +5420,20 @@
op: 'argmax',
field: aggOp.argmax
}, {
forAs: true
});
- newFieldDef.field = `${newField}.${field}`;
+ newFieldDef.field = "".concat(newField, ".").concat(field);
} else if (isArgminDef(aggOp)) {
op = 'argmin';
newField = vgField({
op: 'argmin',
field: aggOp.argmin
}, {
forAs: true
});
- newFieldDef.field = `${newField}.${field}`;
+ newFieldDef.field = "".concat(newField, ".").concat(field);
} else if (aggOp !== 'boxplot' && aggOp !== 'errorbar' && aggOp !== 'errorband') {
op = aggOp;
}
if (op) {
@@ -5292,13 +5469,13 @@
} // Create accompanying 'x2' or 'y2' field if channel is 'x' or 'y' respectively
if (isXorY(channel)) {
const secondaryChannel = {
- field: `${newField}_end`
+ field: "".concat(newField, "_end")
};
- encoding[`${channel}2`] = secondaryChannel;
+ encoding["".concat(channel, "2")] = secondaryChannel;
}
newFieldDef.bin = 'binned';
if (!isSecondaryRangeChannel(channel)) {
@@ -5367,53 +5544,80 @@
}
return true;
}
function initEncoding(encoding, mark, filled, config) {
- return keys(encoding).reduce((normalizedEncoding, channel) => {
- if (!isChannel(channel)) {
+ const normalizedEncoding = {};
+
+ for (const key of keys(encoding)) {
+ if (!isChannel(key)) {
// Drop invalid channel
- warn(invalidEncodingChannel(channel));
- return normalizedEncoding;
+ warn(invalidEncodingChannel(key));
}
+ }
+ for (let channel of UNIT_CHANNELS) {
+ if (!encoding[channel]) {
+ continue;
+ }
+
const channelDef = encoding[channel];
+ if (isXorYOffset(channel)) {
+ const mainChannel = getMainChannelFromOffsetChannel(channel);
+ const positionDef = normalizedEncoding[mainChannel];
+
+ if (isFieldDef(positionDef)) {
+ if (isContinuous(positionDef.type)) {
+ if (isFieldDef(channelDef)) {
+ // TODO: nesting continuous field instead continuous field should
+ // behave like offsetting the data in data domain
+ warn(offsetNestedInsideContinuousPositionScaleDropped(mainChannel));
+ continue;
+ }
+ }
+ } else {
+ // no x/y, replace it with main channel
+ channel = mainChannel;
+ warn(replaceOffsetWithMainChannel(mainChannel));
+ }
+ }
+
if (channel === 'angle' && mark === 'arc' && !encoding.theta) {
warn(REPLACE_ANGLE_WITH_THETA);
channel = THETA;
}
if (!markChannelCompatible(encoding, channel, mark)) {
// Drop unsupported channel
warn(incompatibleChannel(channel, mark));
- return normalizedEncoding;
+ continue;
} // Drop line's size if the field is aggregated.
if (channel === SIZE && mark === 'line') {
const fieldDef = getFieldDef(encoding[channel]);
if (fieldDef !== null && fieldDef !== void 0 && fieldDef.aggregate) {
warn(LINE_WITH_VARYING_SIZE);
- return normalizedEncoding;
+ continue;
}
} // Drop color if either fill or stroke is specified
if (channel === COLOR && (filled ? 'fill' in encoding : 'stroke' in encoding)) {
warn(droppingColor('encoding', {
fill: 'fill' in encoding,
stroke: 'stroke' in encoding
}));
- return normalizedEncoding;
+ continue;
}
- if (channel === DETAIL || channel === ORDER && !vegaUtil.isArray(channelDef) && !isValueDef(channelDef) || channel === TOOLTIP && vegaUtil.isArray(channelDef)) {
+ if (channel === DETAIL || channel === ORDER && !vega.isArray(channelDef) && !isValueDef(channelDef) || channel === TOOLTIP && vega.isArray(channelDef)) {
if (channelDef) {
// Array of fieldDefs for detail channel (or production rule)
- normalizedEncoding[channel] = vegaUtil.array(channelDef).reduce((defs, fieldDef) => {
+ normalizedEncoding[channel] = vega.array(channelDef).reduce((defs, fieldDef) => {
if (!isFieldDef(fieldDef)) {
warn(emptyFieldDef(fieldDef, channel));
} else {
defs.push(initFieldDef(fieldDef, channel));
}
@@ -5425,18 +5629,18 @@
if (channel === TOOLTIP && channelDef === null) {
// Preserve null so we can use it to disable tooltip
normalizedEncoding[channel] = null;
} else if (!isFieldDef(channelDef) && !isDatumDef(channelDef) && !isValueDef(channelDef) && !isConditionalDef(channelDef) && !isSignalRef(channelDef)) {
warn(emptyFieldDef(channelDef, channel));
- return normalizedEncoding;
+ continue;
}
normalizedEncoding[channel] = initChannelDef(channelDef, channel, config);
}
+ }
- return normalizedEncoding;
- }, {});
+ return normalizedEncoding;
}
/**
* For composite marks, we have to call initChannelDef during init so we can infer types earlier.
*/
@@ -5456,11 +5660,11 @@
const arr = [];
for (const channel of keys(encoding)) {
if (channelHasField(encoding, channel)) {
const channelDef = encoding[channel];
- const channelDefArray = vegaUtil.array(channelDef);
+ const channelDefArray = vega.array(channelDef);
for (const def of channelDefArray) {
if (isFieldDef(def)) {
arr.push(def);
} else if (hasConditionalFieldDef(def)) {
@@ -5478,11 +5682,11 @@
}
for (const channel of keys(mapping)) {
const el = mapping[channel];
- if (vegaUtil.isArray(el)) {
+ if (vega.isArray(el)) {
for (const channelDef of el) {
f.call(thisArg, channelDef, channel);
}
} else {
f.call(thisArg, el, channel);
@@ -5495,11 +5699,11 @@
}
return keys(mapping).reduce((r, channel) => {
const map = mapping[channel];
- if (vegaUtil.isArray(map)) {
+ if (vega.isArray(map)) {
return map.reduce((r1, channelDef) => {
return f.call(thisArg, r1, channelDef, channel);
}, r);
} else {
return f.call(thisArg, r, map, channel);
@@ -5519,10 +5723,12 @@
case HREF:
case DESCRIPTION:
case URL:
case X2:
case Y2:
+ case XOFFSET:
+ case YOFFSET:
case THETA:
case THETA2:
case RADIUS:
case RADIUS2: // falls through
@@ -5551,12 +5757,12 @@
case DETAIL:
case KEY:
{
const channelDef = encoding[channel];
- if (vegaUtil.isArray(channelDef) || isFieldDef(channelDef)) {
- for (const fieldDef of vegaUtil.array(channelDef)) {
+ if (vega.isArray(channelDef) || isFieldDef(channelDef)) {
+ for (const fieldDef of vega.array(channelDef)) {
if (!fieldDef.aggregate) {
details.push(vgField(fieldDef, {}));
}
}
}
@@ -5609,11 +5815,11 @@
}
let customTooltipWithAggregatedField;
let customTooltipWithoutAggregatedField;
- if (vegaUtil.isArray(tooltip)) {
+ if (vega.isArray(tooltip)) {
for (const t of tooltip) {
if (t.aggregate) {
if (!customTooltipWithAggregatedField) {
customTooltipWithAggregatedField = [];
}
@@ -5637,36 +5843,39 @@
} else {
customTooltipWithoutAggregatedField = tooltip;
}
}
- if (vegaUtil.isArray(customTooltipWithoutAggregatedField) && customTooltipWithoutAggregatedField.length === 1) {
+ if (vega.isArray(customTooltipWithoutAggregatedField) && customTooltipWithoutAggregatedField.length === 1) {
customTooltipWithoutAggregatedField = customTooltipWithoutAggregatedField[0];
}
return {
customTooltipWithoutAggregatedField,
filteredEncoding
};
}
- function getCompositeMarkTooltip(tooltipSummary, continuousAxisChannelDef, encodingWithoutContinuousAxis, withFieldName = true) {
+ function getCompositeMarkTooltip(tooltipSummary, continuousAxisChannelDef, encodingWithoutContinuousAxis) {
+ let withFieldName = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
+
if ('tooltip' in encodingWithoutContinuousAxis) {
return {
tooltip: encodingWithoutContinuousAxis.tooltip
};
}
- const fiveSummaryTooltip = tooltipSummary.map(({
- fieldPrefix,
- titlePrefix
- }) => {
- const mainTitle = withFieldName ? ` of ${getTitle(continuousAxisChannelDef)}` : '';
+ const fiveSummaryTooltip = tooltipSummary.map(_ref => {
+ let {
+ fieldPrefix,
+ titlePrefix
+ } = _ref;
+ const mainTitle = withFieldName ? " of ".concat(getTitle(continuousAxisChannelDef)) : '';
return {
field: fieldPrefix + continuousAxisChannelDef.field,
type: continuousAxisChannelDef.type,
title: isSignalRef(titlePrefix) ? {
- signal: `${titlePrefix}"${escape(mainTitle)}"`
+ signal: "".concat(titlePrefix, "\"").concat(escape(mainTitle), "\"")
} : titlePrefix + mainTitle
};
});
const tooltipFieldDefs = fieldDefs(encodingWithoutContinuousAxis).map(toStringFieldDef);
return {
@@ -5684,24 +5893,25 @@
function makeCompositeAggregatePartFactory(compositeMarkDef, continuousAxis, continuousAxisChannelDef, sharedEncoding, compositeMarkConfig) {
const {
scale,
axis
} = continuousAxisChannelDef;
- return ({
- partName,
- mark,
- positionPrefix,
- endPositionPrefix = undefined,
- extraEncoding = {}
- }) => {
+ return _ref2 => {
+ let {
+ partName,
+ mark,
+ positionPrefix,
+ endPositionPrefix = undefined,
+ extraEncoding = {}
+ } = _ref2;
const title = getTitle(continuousAxisChannelDef);
return partLayerMixins(compositeMarkDef, partName, compositeMarkConfig, {
mark,
// TODO better remove this method and just have mark as a parameter of the method
encoding: {
[continuousAxis]: {
- field: `${positionPrefix}_${continuousAxisChannelDef.field}`,
+ field: "".concat(positionPrefix, "_").concat(continuousAxisChannelDef.field),
type: continuousAxisChannelDef.type,
...(title !== undefined ? {
title
} : {}),
...(scale !== undefined ? {
@@ -5709,13 +5919,13 @@
} : {}),
...(axis !== undefined ? {
axis
} : {})
},
- ...(vegaUtil.isString(endPositionPrefix) ? {
- [`${continuousAxis}2`]: {
- field: `${endPositionPrefix}_${continuousAxisChannelDef.field}`
+ ...(vega.isString(endPositionPrefix) ? {
+ ["".concat(continuousAxis, "2")]: {
+ field: "".concat(endPositionPrefix, "_").concat(continuousAxisChannelDef.field)
}
} : {}),
...sharedEncoding,
...extraEncoding
}
@@ -5743,12 +5953,12 @@
opacity
} : {}),
...(isMarkDef(partBaseSpec.mark) ? partBaseSpec.mark : {
type: partBaseSpec.mark
}),
- style: `${mark}-${part}`,
- ...(vegaUtil.isBoolean(markDef[part]) ? {} : markDef[part])
+ style: "".concat(mark, "-").concat(part),
+ ...(vega.isBoolean(markDef[part]) ? {} : markDef[part])
}
}];
}
return [];
@@ -5758,13 +5968,13 @@
encoding
} = spec;
const continuousAxis = orient === 'vertical' ? 'y' : 'x';
const continuousAxisChannelDef = encoding[continuousAxis]; // Safe to cast because if x is not continuous fielddef, the orient would not be horizontal.
- const continuousAxisChannelDef2 = encoding[`${continuousAxis}2`];
- const continuousAxisChannelDefError = encoding[`${continuousAxis}Error`];
- const continuousAxisChannelDefError2 = encoding[`${continuousAxis}Error2`];
+ const continuousAxisChannelDef2 = encoding["".concat(continuousAxis, "2")];
+ const continuousAxisChannelDefError = encoding["".concat(continuousAxis, "Error")];
+ const continuousAxisChannelDefError2 = encoding["".concat(continuousAxis, "Error2")];
return {
continuousAxisChannelDef: filterAggregateFromChannelDef(continuousAxisChannelDef, compositeMark),
continuousAxisChannelDef2: filterAggregateFromChannelDef(continuousAxisChannelDef2, compositeMark),
continuousAxisChannelDefError: filterAggregateFromChannelDef(continuousAxisChannelDefError, compositeMark),
continuousAxisChannelDefError2: filterAggregateFromChannelDef(continuousAxisChannelDefError2, compositeMark),
@@ -5831,28 +6041,31 @@
} else if (isContinuousFieldOrDatumDef(y)) {
// y is continuous but x is not
return 'vertical';
} else {
// Neither x nor y is continuous.
- throw new Error(`Need a valid continuous axis for ${compositeMark}s`);
+ throw new Error("Need a valid continuous axis for ".concat(compositeMark, "s"));
}
}
const BOXPLOT = 'boxplot';
const BOXPLOT_PARTS = ['box', 'median', 'outliers', 'rule', 'ticks'];
const boxPlotNormalizer = new CompositeMarkNormalizer(BOXPLOT, normalizeBoxPlot);
function getBoxPlotType(extent) {
- if (vegaUtil.isNumber(extent)) {
+ if (vega.isNumber(extent)) {
return 'tukey';
} // Ham: If we ever want to, we could add another extent syntax `{kIQR: number}` for the original [Q1-k*IQR, Q3+k*IQR] whisker and call this boxPlotType = `kIQR`. However, I'm not exposing this for now.
return extent;
}
- function normalizeBoxPlot(spec, {
- config
- }) {
+ function normalizeBoxPlot(spec, _ref) {
+ var _markDef$extent;
+
+ let {
+ config
+ } = _ref;
// Need to initEncoding first so we can infer type
spec = { ...spec,
encoding: normalizeEncoding(spec.encoding, config)
};
const {
@@ -5868,11 +6081,11 @@
if (params) {
warn(selectionNotSupported('boxplot'));
}
- const extent = markDef.extent ?? config.boxplot.extent;
+ const extent = (_markDef$extent = markDef.extent) !== null && _markDef$extent !== void 0 ? _markDef$extent : config.boxplot.extent;
const sizeValue = getMarkPropOrConfig('size', markDef, // TODO: https://github.com/vega/vega-lite/issues/6245
config);
const boxPlotType = getBoxPlotType(extent);
const {
bins,
@@ -5988,11 +6201,11 @@
}), ...makeBoxPlotMidTick({
partName: 'median',
mark: {
type: 'tick',
invalid: null,
- ...(vegaUtil.isObject(config.boxplot.median) && config.boxplot.median.color ? {
+ ...(vega.isObject(config.boxplot.median) && config.boxplot.median.color ? {
color: config.boxplot.median.color
} : {}),
...(sizeValue ? {
size: sizeValue
} : {}),
@@ -6002,48 +6215,50 @@
positionPrefix: 'mid_box',
extraEncoding: fiveSummaryTooltipEncoding
})];
if (boxPlotType === 'min-max') {
+ var _outerSpec$transform;
+
return { ...outerSpec,
- transform: (outerSpec.transform ?? []).concat(transform),
+ transform: ((_outerSpec$transform = outerSpec.transform) !== null && _outerSpec$transform !== void 0 ? _outerSpec$transform : []).concat(transform),
layer: boxLayers
};
} // Tukey Box Plot
- const lowerBoxExpr = `datum["lower_box_${continuousAxisChannelDef.field}"]`;
- const upperBoxExpr = `datum["upper_box_${continuousAxisChannelDef.field}"]`;
- const iqrExpr = `(${upperBoxExpr} - ${lowerBoxExpr})`;
- const lowerWhiskerExpr = `${lowerBoxExpr} - ${extent} * ${iqrExpr}`;
- const upperWhiskerExpr = `${upperBoxExpr} + ${extent} * ${iqrExpr}`;
- const fieldExpr = `datum["${continuousAxisChannelDef.field}"]`;
+ const lowerBoxExpr = "datum[\"lower_box_".concat(continuousAxisChannelDef.field, "\"]");
+ const upperBoxExpr = "datum[\"upper_box_".concat(continuousAxisChannelDef.field, "\"]");
+ const iqrExpr = "(".concat(upperBoxExpr, " - ").concat(lowerBoxExpr, ")");
+ const lowerWhiskerExpr = "".concat(lowerBoxExpr, " - ").concat(extent, " * ").concat(iqrExpr);
+ const upperWhiskerExpr = "".concat(upperBoxExpr, " + ").concat(extent, " * ").concat(iqrExpr);
+ const fieldExpr = "datum[\"".concat(continuousAxisChannelDef.field, "\"]");
const joinaggregateTransform = {
joinaggregate: boxParamsQuartiles(continuousAxisChannelDef.field),
groupby
};
const filteredWhiskerSpec = {
transform: [{
- filter: `(${lowerWhiskerExpr} <= ${fieldExpr}) && (${fieldExpr} <= ${upperWhiskerExpr})`
+ filter: "(".concat(lowerWhiskerExpr, " <= ").concat(fieldExpr, ") && (").concat(fieldExpr, " <= ").concat(upperWhiskerExpr, ")")
}, {
aggregate: [{
op: 'min',
field: continuousAxisChannelDef.field,
- as: `lower_whisker_${continuousAxisChannelDef.field}`
+ as: "lower_whisker_".concat(continuousAxisChannelDef.field)
}, {
op: 'max',
field: continuousAxisChannelDef.field,
- as: `upper_whisker_${continuousAxisChannelDef.field}`
+ as: "upper_whisker_".concat(continuousAxisChannelDef.field)
}, // preserve lower_box / upper_box
{
op: 'min',
- field: `lower_box_${continuousAxisChannelDef.field}`,
- as: `lower_box_${continuousAxisChannelDef.field}`
+ field: "lower_box_".concat(continuousAxisChannelDef.field),
+ as: "lower_box_".concat(continuousAxisChannelDef.field)
}, {
op: 'max',
- field: `upper_box_${continuousAxisChannelDef.field}`,
- as: `upper_box_${continuousAxisChannelDef.field}`
+ field: "upper_box_".concat(continuousAxisChannelDef.field),
+ as: "upper_box_".concat(continuousAxisChannelDef.field)
}, ...aggregate],
groupby
}],
layer: whiskerLayers
};
@@ -6057,11 +6272,11 @@
} = continuousAxisChannelDef;
const title = getTitle(continuousAxisChannelDef);
const axisWithoutTitle = omit(axis, ['title']);
const outlierLayersMixins = partLayerMixins(markDef, 'outliers', config.boxplot, {
transform: [{
- filter: `(${fieldExpr} < ${lowerWhiskerExpr}) || (${fieldExpr} > ${upperWhiskerExpr})`
+ filter: "(".concat(fieldExpr, " < ").concat(lowerWhiskerExpr, ") || (").concat(fieldExpr, " > ").concat(upperWhiskerExpr, ")")
}],
mark: 'point',
encoding: {
[continuousAxis]: {
field: continuousAxisChannelDef.field,
@@ -6110,15 +6325,15 @@
function boxParamsQuartiles(continousAxisField) {
return [{
op: 'q1',
field: continousAxisField,
- as: `lower_box_${continousAxisField}`
+ as: "lower_box_".concat(continousAxisField)
}, {
op: 'q3',
field: continousAxisField,
- as: `upper_box_${continousAxisField}`
+ as: "upper_box_".concat(continousAxisField)
}];
}
function boxParams(spec, extent, config) {
const orient = compositeMarkOrient(spec, BOXPLOT);
@@ -6129,11 +6344,11 @@
const continuousFieldName = continuousAxisChannelDef.field;
const boxPlotType = getBoxPlotType(extent);
const boxplotSpecificAggregate = [...boxParamsQuartiles(continuousFieldName), {
op: 'median',
field: continuousFieldName,
- as: `mid_box_${continuousFieldName}`
+ as: "mid_box_".concat(continuousFieldName)
}, {
op: 'min',
field: continuousFieldName,
as: (boxPlotType === 'min-max' ? 'lower_whisker_' : 'min_') + continuousFieldName
}, {
@@ -6141,18 +6356,18 @@
field: continuousFieldName,
as: (boxPlotType === 'min-max' ? 'upper_whisker_' : 'max_') + continuousFieldName
}];
const postAggregateCalculates = boxPlotType === 'min-max' || boxPlotType === 'tukey' ? [] : [// This is for the original k-IQR, which we do not expose
{
- calculate: `datum["upper_box_${continuousFieldName}"] - datum["lower_box_${continuousFieldName}"]`,
- as: `iqr_${continuousFieldName}`
+ calculate: "datum[\"upper_box_".concat(continuousFieldName, "\"] - datum[\"lower_box_").concat(continuousFieldName, "\"]"),
+ as: "iqr_".concat(continuousFieldName)
}, {
- calculate: `min(datum["upper_box_${continuousFieldName}"] + datum["iqr_${continuousFieldName}"] * ${extent}, datum["max_${continuousFieldName}"])`,
- as: `upper_whisker_${continuousFieldName}`
+ calculate: "min(datum[\"upper_box_".concat(continuousFieldName, "\"] + datum[\"iqr_").concat(continuousFieldName, "\"] * ").concat(extent, ", datum[\"max_").concat(continuousFieldName, "\"])"),
+ as: "upper_whisker_".concat(continuousFieldName)
}, {
- calculate: `max(datum["lower_box_${continuousFieldName}"] - datum["iqr_${continuousFieldName}"] * ${extent}, datum["min_${continuousFieldName}"])`,
- as: `lower_whisker_${continuousFieldName}`
+ calculate: "max(datum[\"lower_box_".concat(continuousFieldName, "\"] - datum[\"iqr_").concat(continuousFieldName, "\"] * ").concat(extent, ", datum[\"min_").concat(continuousFieldName, "\"])"),
+ as: "lower_whisker_".concat(continuousFieldName)
}];
const {
[continuousAxis]: oldContinuousAxisChannelDef,
...oldEncodingWithoutContinuousAxis
} = spec.encoding;
@@ -6189,13 +6404,14 @@
}
const ERRORBAR = 'errorbar';
const ERRORBAR_PARTS = ['ticks', 'rule'];
const errorBarNormalizer = new CompositeMarkNormalizer(ERRORBAR, normalizeErrorBar);
- function normalizeErrorBar(spec, {
- config
- }) {
+ function normalizeErrorBar(spec, _ref) {
+ let {
+ config
+ } = _ref;
// Need to initEncoding first so we can infer type
spec = { ...spec,
encoding: normalizeEncoding(spec.encoding, config)
};
const {
@@ -6273,29 +6489,29 @@
const y = encoding.y;
if (isTypeAggregatedUpperLower) {
// type is aggregated-upper-lower
if (isTypeAggregatedError) {
- throw new Error(`${compositeMark} cannot be both type aggregated-upper-lower and aggregated-error`);
+ throw new Error("".concat(compositeMark, " cannot be both type aggregated-upper-lower and aggregated-error"));
}
const x2 = encoding.x2;
const y2 = encoding.y2;
if (isFieldOrDatumDef(x2) && isFieldOrDatumDef(y2)) {
// having both x, x2 and y, y2
- throw new Error(`${compositeMark} cannot have both x2 and y2`);
+ throw new Error("".concat(compositeMark, " cannot have both x2 and y2"));
} else if (isFieldOrDatumDef(x2)) {
if (isContinuousFieldOrDatumDef(x)) {
// having x, x2 quantitative and field y, y2 are not specified
return {
orient: 'horizontal',
inputType: 'aggregated-upper-lower'
};
} else {
// having x, x2 that are not both quantitative
- throw new Error(`Both x and x2 have to be quantitative in ${compositeMark}`);
+ throw new Error("Both x and x2 have to be quantitative in ".concat(compositeMark));
}
} else if (isFieldOrDatumDef(y2)) {
// y2 is a FieldDef
if (isContinuousFieldOrDatumDef(y)) {
// having y, y2 quantitative and field x, x2 are not specified
@@ -6303,11 +6519,11 @@
orient: 'vertical',
inputType: 'aggregated-upper-lower'
};
} else {
// having y, y2 that are not both quantitative
- throw new Error(`Both y and y2 have to be quantitative in ${compositeMark}`);
+ throw new Error("Both y and y2 have to be quantitative in ".concat(compositeMark));
}
}
throw new Error('No ranged axis');
} else {
@@ -6317,21 +6533,21 @@
const yError = encoding.yError;
const yError2 = encoding.yError2;
if (isFieldOrDatumDef(xError2) && !isFieldOrDatumDef(xError)) {
// having xError2 without xError
- throw new Error(`${compositeMark} cannot have xError2 without xError`);
+ throw new Error("".concat(compositeMark, " cannot have xError2 without xError"));
}
if (isFieldOrDatumDef(yError2) && !isFieldOrDatumDef(yError)) {
// having yError2 without yError
- throw new Error(`${compositeMark} cannot have yError2 without yError`);
+ throw new Error("".concat(compositeMark, " cannot have yError2 without yError"));
}
if (isFieldOrDatumDef(xError) && isFieldOrDatumDef(yError)) {
// having both xError and yError
- throw new Error(`${compositeMark} cannot have both xError and yError with both are quantiative`);
+ throw new Error("".concat(compositeMark, " cannot have both xError and yError with both are quantiative"));
} else if (isFieldOrDatumDef(xError)) {
if (isContinuousFieldOrDatumDef(x)) {
// having x and xError that are all quantitative
return {
orient: 'horizontal',
@@ -6369,10 +6585,12 @@
function errorBarIsInputTypeAggregatedError(encoding) {
return isFieldOrDatumDef(encoding.xError) || isFieldOrDatumDef(encoding.xError2) || isFieldOrDatumDef(encoding.yError) || isFieldOrDatumDef(encoding.yError2);
}
function errorBarParams(spec, compositeMark, config) {
+ var _outerSpec$transform;
+
// TODO: use selection
const {
mark,
encoding,
params,
@@ -6420,11 +6638,11 @@
} = extractTransformsFromEncoding(oldEncodingWithoutContinuousAxis, config);
const aggregate = [...oldAggregate, ...errorBarSpecificAggregate];
const groupby = inputType !== 'raw' ? [] : oldGroupBy;
const tooltipEncoding = getCompositeMarkTooltip(tooltipSummary, continuousAxisChannelDef, encodingWithoutContinuousAxis, tooltipTitleWithFieldName);
return {
- transform: [...(outerSpec.transform ?? []), ...bins, ...timeUnits, ...(aggregate.length === 0 ? [] : [{
+ transform: [...((_outerSpec$transform = outerSpec.transform) !== null && _outerSpec$transform !== void 0 ? _outerSpec$transform : []), ...bins, ...timeUnits, ...(aggregate.length === 0 ? [] : [{
aggregate,
groupby
}]), ...postAggregateCalculates],
groupby,
continuousAxisChannelDef,
@@ -6454,22 +6672,22 @@
if (extent === 'stderr' || extent === 'stdev') {
errorBarSpecificAggregate = [{
op: extent,
field: continuousFieldName,
- as: `extent_${continuousFieldName}`
+ as: "extent_".concat(continuousFieldName)
}, {
op: center,
field: continuousFieldName,
- as: `center_${continuousFieldName}`
+ as: "center_".concat(continuousFieldName)
}];
postAggregateCalculates = [{
- calculate: `datum["center_${continuousFieldName}"] + datum["extent_${continuousFieldName}"]`,
- as: `upper_${continuousFieldName}`
+ calculate: "datum[\"center_".concat(continuousFieldName, "\"] + datum[\"extent_").concat(continuousFieldName, "\"]"),
+ as: "upper_".concat(continuousFieldName)
}, {
- calculate: `datum["center_${continuousFieldName}"] - datum["extent_${continuousFieldName}"]`,
- as: `lower_${continuousFieldName}`
+ calculate: "datum[\"center_".concat(continuousFieldName, "\"] - datum[\"extent_").concat(continuousFieldName, "\"]"),
+ as: "lower_".concat(continuousFieldName)
}];
tooltipSummary = [{
fieldPrefix: 'center_',
titlePrefix: titleCase(center)
}, {
@@ -6496,19 +6714,19 @@
}
errorBarSpecificAggregate = [{
op: lowerExtentOp,
field: continuousFieldName,
- as: `lower_${continuousFieldName}`
+ as: "lower_".concat(continuousFieldName)
}, {
op: upperExtentOp,
field: continuousFieldName,
- as: `upper_${continuousFieldName}`
+ as: "upper_".concat(continuousFieldName)
}, {
op: centerOp,
field: continuousFieldName,
- as: `center_${continuousFieldName}`
+ as: "center_".concat(continuousFieldName)
}];
tooltipSummary = [{
fieldPrefix: 'upper_',
titlePrefix: title({
field: continuousFieldName,
@@ -6543,35 +6761,35 @@
}
if (inputType === 'aggregated-upper-lower') {
tooltipSummary = [];
postAggregateCalculates = [{
- calculate: `datum["${continuousAxisChannelDef2.field}"]`,
- as: `upper_${continuousFieldName}`
+ calculate: "datum[\"".concat(continuousAxisChannelDef2.field, "\"]"),
+ as: "upper_".concat(continuousFieldName)
}, {
- calculate: `datum["${continuousFieldName}"]`,
- as: `lower_${continuousFieldName}`
+ calculate: "datum[\"".concat(continuousFieldName, "\"]"),
+ as: "lower_".concat(continuousFieldName)
}];
} else if (inputType === 'aggregated-error') {
tooltipSummary = [{
fieldPrefix: '',
titlePrefix: continuousFieldName
}];
postAggregateCalculates = [{
- calculate: `datum["${continuousFieldName}"] + datum["${continuousAxisChannelDefError.field}"]`,
- as: `upper_${continuousFieldName}`
+ calculate: "datum[\"".concat(continuousFieldName, "\"] + datum[\"").concat(continuousAxisChannelDefError.field, "\"]"),
+ as: "upper_".concat(continuousFieldName)
}];
if (continuousAxisChannelDefError2) {
postAggregateCalculates.push({
- calculate: `datum["${continuousFieldName}"] + datum["${continuousAxisChannelDefError2.field}"]`,
- as: `lower_${continuousFieldName}`
+ calculate: "datum[\"".concat(continuousFieldName, "\"] + datum[\"").concat(continuousAxisChannelDefError2.field, "\"]"),
+ as: "lower_".concat(continuousFieldName)
});
} else {
postAggregateCalculates.push({
- calculate: `datum["${continuousFieldName}"] - datum["${continuousAxisChannelDefError.field}"]`,
- as: `lower_${continuousFieldName}`
+ calculate: "datum[\"".concat(continuousFieldName, "\"] - datum[\"").concat(continuousAxisChannelDefError.field, "\"]"),
+ as: "lower_".concat(continuousFieldName)
});
}
}
for (const postAggregateCalculate of postAggregateCalculates) {
@@ -6589,19 +6807,20 @@
tooltipTitleWithFieldName
};
}
function getTitlePrefix(center, extent, operation) {
- return `${titleCase(center)} ${operation} ${extent}`;
+ return "".concat(titleCase(center), " ").concat(operation, " ").concat(extent);
}
const ERRORBAND = 'errorband';
const ERRORBAND_PARTS = ['band', 'borders'];
const errorBandNormalizer = new CompositeMarkNormalizer(ERRORBAND, normalizeErrorBand);
- function normalizeErrorBand(spec, {
- config
- }) {
+ function normalizeErrorBand(spec, _ref) {
+ let {
+ config
+ } = _ref;
// Need to initEncoding first so we can infer type
spec = { ...spec,
encoding: normalizeEncoding(spec.encoding, config)
};
const {
@@ -6829,11 +7048,11 @@
};
function isLegendBinding(bind) {
return !!bind && (bind === 'legend' || !!bind.legend);
}
function isLegendStreamBinding(bind) {
- return isLegendBinding(bind) && vegaUtil.isObject(bind);
+ return isLegendBinding(bind) && vega.isObject(bind);
}
function isSelectionParameter(param) {
return !!param['select'];
}
@@ -6905,11 +7124,11 @@
function isFitType(autoSizeType) {
return autoSizeType === 'fit' || autoSizeType === 'fit-x' || autoSizeType === 'fit-y';
}
function getFitType(sizeType) {
- return sizeType ? `fit-${getPositionScaleChannel(sizeType)}` : 'fit';
+ return sizeType ? "fit-".concat(getPositionScaleChannel(sizeType)) : 'fit';
}
const TOP_LEVEL_PROPERTIES = ['background', 'padding' // We do not include "autosize" here as it is supported by only unit and layer specs and thus need to be normalized
];
function extractTopLevelProperties(t, includeParams) {
const o = {};
@@ -6929,12 +7148,26 @@
/**
* Common properties for all types of specification
*/
+ function getStepFor(_ref) {
+ let {
+ step,
+ offsetIsDiscrete
+ } = _ref;
+
+ if (offsetIsDiscrete) {
+ var _step$for;
+
+ return (_step$for = step.for) !== null && _step$for !== void 0 ? _step$for : 'offset';
+ } else {
+ return 'position';
+ }
+ }
function isStep(size) {
- return vegaUtil.isObject(size) && size['step'] !== undefined;
+ return vega.isObject(size) && size['step'] !== undefined;
} // TODO(https://github.com/vega/vega-lite/issues/2503): Make this generic so we can support some form of top-down sizing.
/**
* Common properties for specifying width and height of unit and layer specifications.
*/
@@ -6976,14 +7209,16 @@
for (const prop of COMPOSITION_LAYOUT_PROPERTIES) {
if (spec[prop] !== undefined) {
if (prop === 'spacing') {
+ var _spacing$row, _spacing$column;
+
const spacing = spec[prop];
- layout[prop] = vegaUtil.isNumber(spacing) ? spacing : {
- row: spacing.row ?? spacingConfig,
- column: spacing.column ?? spacingConfig
+ layout[prop] = vega.isNumber(spacing) ? spacing : {
+ row: (_spacing$row = spacing.row) !== null && _spacing$row !== void 0 ? _spacing$row : spacingConfig,
+ column: (_spacing$column = spacing.column) !== null && _spacing$column !== void 0 ? _spacing$column : spacingConfig
};
} else {
layout[prop] = spec[prop];
}
}
@@ -6991,19 +7226,23 @@
return layout;
}
function getViewConfigContinuousSize(viewConfig, channel) {
- return viewConfig[channel] ?? viewConfig[channel === 'width' ? 'continuousWidth' : 'continuousHeight']; // get width/height for backwards compatibility
+ var _viewConfig$channel;
+
+ return (_viewConfig$channel = viewConfig[channel]) !== null && _viewConfig$channel !== void 0 ? _viewConfig$channel : viewConfig[channel === 'width' ? 'continuousWidth' : 'continuousHeight']; // get width/height for backwards compatibility
}
function getViewConfigDiscreteStep(viewConfig, channel) {
const size = getViewConfigDiscreteSize(viewConfig, channel);
return isStep(size) ? size.step : DEFAULT_STEP;
}
function getViewConfigDiscreteSize(viewConfig, channel) {
- const size = viewConfig[channel] ?? viewConfig[channel === 'width' ? 'discreteWidth' : 'discreteHeight']; // get width/height for backwards compatibility
+ var _viewConfig$channel2;
+ const size = (_viewConfig$channel2 = viewConfig[channel]) !== null && _viewConfig$channel2 !== void 0 ? _viewConfig$channel2 : viewConfig[channel === 'width' ? 'discreteWidth' : 'discreteHeight']; // get width/height for backwards compatibility
+
return getFirstDefined(size, {
step: viewConfig.step
});
}
const DEFAULT_STEP = 20;
@@ -7115,15 +7354,16 @@
gray12: '#ccc',
gray13: '#ddd',
gray14: '#eee',
gray15: '#fff'
};
- function colorSignalConfig(color = {}) {
+ function colorSignalConfig() {
+ let color = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return {
signals: [{
name: 'color',
- value: vegaUtil.isObject(color) ? { ...DEFAULT_COLOR,
+ value: vega.isObject(color) ? { ...DEFAULT_COLOR,
...color
} : DEFAULT_COLOR
}],
mark: {
color: {
@@ -7205,11 +7445,11 @@
}
function fontSizeSignalConfig(fontSize) {
return {
signals: [{
name: 'fontSize',
- value: vegaUtil.isObject(fontSize) ? { ...DEFAULT_FONT_SIZE,
+ value: vega.isObject(fontSize) ? { ...DEFAULT_FONT_SIZE,
...fontSize
} : DEFAULT_FONT_SIZE
}],
text: {
fontSize: {
@@ -7290,19 +7530,20 @@
/**
* Merge specified config with default config and config for the `color` flag,
* then replace all expressions with signals
*/
- function initConfig(specifiedConfig = {}) {
+ function initConfig() {
+ let specifiedConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const {
color,
font,
fontSize,
selection,
...restConfig
} = specifiedConfig;
- const mergedConfig = vegaUtil.mergeConfig({}, duplicate(defaultConfig), font ? fontConfig(font) : {}, color ? colorSignalConfig(color) : {}, fontSize ? fontSizeSignalConfig(fontSize) : {}, restConfig || {}); // mergeConfig doesn't recurse and overrides object values.
+ const mergedConfig = vega.mergeConfig({}, duplicate(defaultConfig), font ? fontConfig(font) : {}, color ? colorSignalConfig(color) : {}, fontSize ? fontSizeSignalConfig(fontSize) : {}, restConfig || {}); // mergeConfig doesn't recurse and overrides object values.
if (selection) {
vega.writeConfig(mergedConfig, 'selection', selection, true);
}
@@ -7353,11 +7594,11 @@
outputConfig.view = replaceExprRef(mergedConfig.view);
}
return outputConfig;
}
- const MARK_STYLES = ['view', ...PRIMITIVE_MARKS];
+ const MARK_STYLES = new Set(['view', ...PRIMITIVE_MARKS]);
const VL_ONLY_CONFIG_PROPERTIES = ['color', 'fontSize', 'background', // We apply background to the spec directly.
'padding', 'facet', 'concat', 'numberFormat', 'timeFormat', 'countTitle', 'header', 'axisQuantitative', 'axisTemporal', 'axisDiscrete', 'axisPoint', 'axisXBand', 'axisXPoint', 'axisXDiscrete', 'axisXQuantitative', 'axisXTemporal', 'axisYBand', 'axisYPoint', 'axisYDiscrete', 'axisYQuantitative', 'axisYTemporal', 'scale', 'selection', 'overlay' // FIXME: Redesign and unhide this
];
const VL_ONLY_ALL_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX = {
view: ['continuousWidth', 'continuousHeight', 'discreteWidth', 'discreteHeight', 'step'],
@@ -7389,11 +7630,11 @@
if (config.mark) {
for (const prop of VL_ONLY_MARK_CONFIG_PROPERTIES) {
delete config.mark[prop];
}
- if (config.mark.tooltip && vegaUtil.isObject(config.mark.tooltip)) {
+ if (config.mark.tooltip && vega.isObject(config.mark.tooltip)) {
delete config.mark.tooltip;
}
}
if (config.params) {
@@ -7428,11 +7669,11 @@
}
redirectTitleConfig(config); // Remove empty config objects.
for (const prop in config) {
- if (vegaUtil.isObject(config[prop]) && isEmpty(config[prop])) {
+ if (vega.isObject(config[prop]) && isEmpty(config[prop])) {
delete config[prop];
}
}
return isEmpty(config) ? undefined : config;
@@ -7473,22 +7714,26 @@
}
}
function redirectConfigToStyleConfig(config, prop, // string = composite mark
toProp, compositeMarkPart) {
+ var _toProp;
+
const propConfig = compositeMarkPart ? config[prop][compositeMarkPart] : config[prop];
if (prop === 'view') {
toProp = 'cell'; // View's default style is "cell"
}
const style = { ...propConfig,
- ...config.style[toProp ?? prop]
+ ...config.style[(_toProp = toProp) !== null && _toProp !== void 0 ? _toProp : prop]
}; // set config.style if it is not an empty object
if (!isEmpty(style)) {
- config.style[toProp ?? prop] = style;
+ var _toProp2;
+
+ config.style[(_toProp2 = toProp) !== null && _toProp2 !== void 0 ? _toProp2 : prop] = style;
}
if (!compositeMarkPart) {
// For composite mark, so don't delete the whole config yet as we have to do multiple redirections.
delete config[prop];
@@ -7512,11 +7757,11 @@
function isRepeatSpec(spec) {
return 'repeat' in spec;
}
function isLayerRepeatSpec(spec) {
- return !vegaUtil.isArray(spec.repeat) && spec.repeat['layer'];
+ return !vega.isArray(spec.repeat) && spec.repeat['layer'];
}
class SpecMapper {
map(spec, params) {
if (isFacetSpec(spec)) {
@@ -7664,13 +7909,14 @@
}
} // Note: CompassQL uses this method and only pass in required properties of each argument object.
// If required properties change, make sure to update CompassQL.
- function stack(m, encoding, opt = {}) {
+ function stack(m, encoding) {
var _stackedFieldDef$scal, _stackedFieldDef$scal2;
+ let opt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
const mark = isMarkDef(m) ? m.type : m; // Should have stackable mark
if (!STACKABLE_MARKS.has(mark)) {
return null;
} // Run potential stacked twice, one for Cartesian and another for Polar,
@@ -7685,39 +7931,55 @@
return null;
}
const stackedFieldDef = encoding[fieldChannel];
const stackedField = isFieldDef(stackedFieldDef) ? vgField(stackedFieldDef, {}) : undefined;
- let dimensionChannel = getDimensionChannel(fieldChannel);
- let dimensionDef = encoding[dimensionChannel];
- let dimensionField = isFieldDef(dimensionDef) ? vgField(dimensionDef, {}) : undefined; // avoid grouping by the stacked field
+ const dimensionChannel = getDimensionChannel(fieldChannel);
+ const groupbyChannels = [];
+ const groupbyFields = new Set();
- if (dimensionField === stackedField) {
- dimensionField = undefined;
- dimensionDef = undefined;
- dimensionChannel = undefined;
- } // Should have grouping level of detail that is different from the dimension field
+ if (encoding[dimensionChannel]) {
+ const dimensionDef = encoding[dimensionChannel];
+ const dimensionField = isFieldDef(dimensionDef) ? vgField(dimensionDef, {}) : undefined;
+ if (dimensionField && dimensionField !== stackedField) {
+ // avoid grouping by the stacked field
+ groupbyChannels.push(dimensionChannel);
+ groupbyFields.add(dimensionField);
+ }
+ const dimensionOffsetChannel = dimensionChannel === 'x' ? 'xOffset' : 'yOffset';
+ const dimensionOffsetDef = encoding[dimensionOffsetChannel];
+ const dimensionOffsetField = isFieldDef(dimensionOffsetDef) ? vgField(dimensionOffsetDef, {}) : undefined;
+
+ if (dimensionOffsetField && dimensionOffsetField !== stackedField) {
+ // avoid grouping by the stacked field
+ groupbyChannels.push(dimensionOffsetChannel);
+ groupbyFields.add(dimensionOffsetField);
+ }
+ } // If the dimension has offset, don't stack anymore
+ // Should have grouping level of detail that is different from the dimension field
+
+
const stackBy = NONPOSITION_CHANNELS.reduce((sc, channel) => {
// Ignore tooltip in stackBy (https://github.com/vega/vega-lite/issues/4001)
if (channel !== 'tooltip' && channelHasField(encoding, channel)) {
const channelDef = encoding[channel];
- for (const cDef of vegaUtil.array(channelDef)) {
+ for (const cDef of vega.array(channelDef)) {
const fieldDef = getFieldDef(cDef);
if (fieldDef.aggregate) {
continue;
} // Check whether the channel's field is identical to x/y's field or if the channel is a repeat
const f = vgField(fieldDef, {});
if ( // if fielddef is a repeat, just include it in the stack by
- !f || // otherwise, the field must be different from x and y fields.
- f !== dimensionField) {
+ !f || // otherwise, the field must be different from the groupBy fields.
+ !groupbyFields.has(f)) {
sc.push({
channel,
fieldDef
});
}
@@ -7728,11 +7990,11 @@
}, []); // Automatically determine offset
let offset;
if (stackedFieldDef.stack !== undefined) {
- if (vegaUtil.isBoolean(stackedFieldDef.stack)) {
+ if (vega.isBoolean(stackedFieldDef.stack)) {
offset = stackedFieldDef.stack ? 'zero' : null;
} else {
offset = stackedFieldDef.stack;
}
} else if (STACK_BY_DEFAULT_MARKS.has(mark)) {
@@ -7764,17 +8026,17 @@
return null;
} // Warn if stacking non-summative aggregate
- if (isFieldDef(stackedFieldDef) && stackedFieldDef.aggregate && !contains(SUM_OPS, stackedFieldDef.aggregate)) {
+ if (isFieldDef(stackedFieldDef) && stackedFieldDef.aggregate && !SUM_OPS.has(stackedFieldDef.aggregate)) {
warn(stackNonSummativeAggregate(stackedFieldDef.aggregate));
}
return {
- groupbyChannel: dimensionDef ? dimensionChannel : undefined,
- groupbyField: dimensionField,
+ groupbyChannels,
+ groupbyFields,
fieldChannel,
impute: stackedFieldDef.impute === null ? false : isPathMark(mark),
stackBy,
offset
};
@@ -7800,34 +8062,39 @@
}
return config;
}
- function getPointOverlay(markDef, markConfig = {}, encoding) {
+ function getPointOverlay(markDef) {
+ let markConfig = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ let encoding = arguments.length > 2 ? arguments[2] : undefined;
+
if (markDef.point === 'transparent') {
return {
opacity: 0
};
} else if (markDef.point) {
// truthy : true or object
- return vegaUtil.isObject(markDef.point) ? markDef.point : {};
+ return vega.isObject(markDef.point) ? markDef.point : {};
} else if (markDef.point !== undefined) {
// false or null
return null;
} else {
// undefined (not disabled)
if (markConfig.point || encoding.shape) {
// enable point overlay if config[mark].point is truthy or if encoding.shape is provided
- return vegaUtil.isObject(markConfig.point) ? markConfig.point : {};
+ return vega.isObject(markConfig.point) ? markConfig.point : {};
} // markDef.point is defined as falsy
return undefined;
}
}
- function getLineOverlay(markDef, markConfig = {}) {
+ function getLineOverlay(markDef) {
+ let markConfig = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+
if (markDef.line) {
// true or object
return markDef.line === true ? {} : markDef.line;
} else if (markDef.line !== undefined) {
// false or null
@@ -8076,16 +8343,17 @@
function replaceRepeaterInMapping(mapping, repeater) {
const out = {};
for (const channel in mapping) {
- if (vegaUtil.hasOwnProperty(mapping, channel)) {
+ if (vega.hasOwnProperty(mapping, channel)) {
const channelDef = mapping[channel];
- if (vegaUtil.isArray(channelDef)) {
+ if (vega.isArray(channelDef)) {
// array cannot have condition
- out[channel] = channelDef.map(cd => replaceRepeaterInChannelDef(cd, repeater)).filter(cd => cd);
+ out[channel] = channelDef // somehow we need to cast it here
+ .map(cd => replaceRepeaterInChannelDef(cd, repeater)).filter(cd => cd);
} else {
const cd = replaceRepeaterInChannelDef(channelDef, repeater);
if (cd !== undefined) {
out[channel] = cd;
@@ -8131,21 +8399,21 @@
encoding,
mark
} = spec;
warn(lineWithRange(!!encoding.x2, !!encoding.y2));
return normalize({ ...spec,
- mark: vegaUtil.isObject(mark) ? { ...mark,
+ mark: vega.isObject(mark) ? { ...mark,
type: 'rule'
} : 'rule'
}, params);
}
}
class CoreNormalizer extends SpecMapper {
- constructor(...args) {
- super(...args);
+ constructor() {
+ super(...arguments);
_defineProperty(this, "nonFacetUnitNormalizers", [boxPlotNormalizer, errorBarNormalizer, errorBandNormalizer, new PathOverlayNormalizer(), new RuleForRangedLineNormalizer()]);
}
map(spec, params) {
@@ -8235,11 +8503,11 @@
return { ...rest,
layer: layer.map(layerValue => {
const childRepeater = { ...repeater,
layer: layerValue
};
- const childName = `${(childSpec.name || '') + repeaterPrefix}child__layer_${varName(layerValue)}`;
+ const childName = "".concat((childSpec.name || '') + repeaterPrefix, "child__layer_").concat(varName(layerValue));
const child = this.mapLayerOrUnit(childSpec, { ...params,
repeater: childRepeater,
repeaterPrefix: childName
});
child.name = childName;
@@ -8248,42 +8516,44 @@
};
}
}
mapNonLayerRepeat(spec, params) {
+ var _childSpec$data;
+
const {
repeat,
spec: childSpec,
data,
...remainingProperties
} = spec;
- if (!vegaUtil.isArray(repeat) && spec.columns) {
+ if (!vega.isArray(repeat) && spec.columns) {
// is repeat with row/column
spec = omit(spec, ['columns']);
warn(columnsNotSupportByRowCol('repeat'));
}
const concat = [];
const {
repeater = {},
repeaterPrefix = ''
} = params;
- const row = !vegaUtil.isArray(repeat) && repeat.row || [repeater ? repeater.row : null];
- const column = !vegaUtil.isArray(repeat) && repeat.column || [repeater ? repeater.column : null];
- const repeatValues = vegaUtil.isArray(repeat) && repeat || [repeater ? repeater.repeat : null]; // cross product
+ const row = !vega.isArray(repeat) && repeat.row || [repeater ? repeater.row : null];
+ const column = !vega.isArray(repeat) && repeat.column || [repeater ? repeater.column : null];
+ const repeatValues = vega.isArray(repeat) && repeat || [repeater ? repeater.repeat : null]; // cross product
for (const repeatValue of repeatValues) {
for (const rowValue of row) {
for (const columnValue of column) {
const childRepeater = {
repeat: repeatValue,
row: rowValue,
column: columnValue,
layer: repeater.layer
};
- const childName = (childSpec.name || '') + repeaterPrefix + 'child__' + (vegaUtil.isArray(repeat) ? `${varName(repeatValue)}` : (repeat.row ? `row_${varName(rowValue)}` : '') + (repeat.column ? `column_${varName(columnValue)}` : ''));
+ const childName = (childSpec.name || '') + repeaterPrefix + 'child__' + (vega.isArray(repeat) ? "".concat(varName(repeatValue)) : (repeat.row ? "row_".concat(varName(rowValue)) : '') + (repeat.column ? "column_".concat(varName(columnValue)) : ''));
const child = this.map(childSpec, { ...params,
repeater: childRepeater,
repeaterPrefix: childName
});
child.name = childName; // we move data up
@@ -8291,13 +8561,13 @@
concat.push(omit(child, ['data']));
}
}
}
- const columns = vegaUtil.isArray(repeat) ? spec.columns : repeat.column ? repeat.column.length : 1;
+ const columns = vega.isArray(repeat) ? spec.columns : repeat.column ? repeat.column.length : 1;
return {
- data: childSpec.data ?? data,
+ data: (_childSpec$data = childSpec.data) !== null && _childSpec$data !== void 0 ? _childSpec$data : data,
// data from child spec should have precedence
align: 'all',
...remainingProperties,
columns,
concat
@@ -8430,11 +8700,13 @@
} = def;
facetMapping[channel] = defWithoutLayout;
for (const prop of ['align', 'center', 'spacing']) {
if (def[prop] !== undefined) {
- layout[prop] ?? (layout[prop] = {});
+ var _layout$prop;
+
+ (_layout$prop = layout[prop]) !== null && _layout$prop !== void 0 ? _layout$prop : layout[prop] = {};
layout[prop][channel] = def[prop];
}
}
}
}
@@ -8468,15 +8740,16 @@
}
};
}
}
- mapLayer(spec, {
- parentEncoding,
- parentProjection,
- ...otherParams
- }) {
+ mapLayer(spec, _ref) {
+ let {
+ parentEncoding,
+ parentProjection,
+ ...otherParams
+ } = _ref;
// Special handling for extended layer spec
const {
encoding,
projection,
...rest
@@ -8495,15 +8768,16 @@
return super.mapLayer(rest, params);
}
}
- function mergeEncoding({
- parentEncoding,
- encoding = {},
- layer
- }) {
+ function mergeEncoding(_ref2) {
+ let {
+ parentEncoding,
+ encoding = {},
+ layer
+ } = _ref2;
let merged = {};
if (parentEncoding) {
const channels = new Set([...keys(parentEncoding), ...keys(encoding)]);
@@ -8524,11 +8798,11 @@
...channelDef.condition
}
};
} else if (channelDef || channelDef === null) {
merged[channel] = channelDef;
- } else if (layer || isValueDef(parentChannelDef) || isSignalRef(parentChannelDef) || isFieldOrDatumDef(parentChannelDef) || vegaUtil.isArray(parentChannelDef)) {
+ } else if (layer || isValueDef(parentChannelDef) || isSignalRef(parentChannelDef) || isFieldOrDatumDef(parentChannelDef) || vega.isArray(parentChannelDef)) {
merged[channel] = parentChannelDef;
}
}
} else {
merged = encoding;
@@ -8548,11 +8822,11 @@
parentProjection,
projection
}));
}
- return projection ?? parentProjection;
+ return projection !== null && projection !== void 0 ? projection : parentProjection;
}
function isFilter(t) {
return 'filter' in t;
}
@@ -8628,12 +8902,14 @@
});
}
class SelectionCompatibilityNormalizer extends SpecMapper {
map(spec, normParams) {
- normParams.emptySelections ?? (normParams.emptySelections = {});
- normParams.selectionPredicates ?? (normParams.selectionPredicates = {});
+ var _normParams$emptySele, _normParams$selection;
+
+ (_normParams$emptySele = normParams.emptySelections) !== null && _normParams$emptySele !== void 0 ? _normParams$emptySele : normParams.emptySelections = {};
+ (_normParams$selection = normParams.selectionPredicates) !== null && _normParams$selection !== void 0 ? _normParams$selection : normParams.selectionPredicates = {};
spec = normalizeTransforms(spec, normParams);
return super.map(spec, normParams);
}
mapLayerOrUnit(spec, normParams) {
@@ -8660,11 +8936,12 @@
...rest
} = spec;
if (selection) {
return { ...rest,
- params: entries$1(selection).map(([name, selDef]) => {
+ params: entries$1(selection).map(_ref => {
+ let [name, selDef] = _ref;
const {
init: value,
bind,
empty,
...select
@@ -8678,11 +8955,13 @@
} // Propagate emptiness forwards and backwards
normParams.emptySelections[name] = empty !== 'none';
- for (const pred of vals(normParams.selectionPredicates[name] ?? {})) {
+ for (const pred of vals((_normParams$selection2 = normParams.selectionPredicates[name]) !== null && _normParams$selection2 !== void 0 ? _normParams$selection2 : {})) {
+ var _normParams$selection2;
+
pred.empty = empty !== 'none';
}
return {
name,
@@ -8808,30 +9087,32 @@
function normalizePredicate(op, normParams) {
// Normalize old compositions of selection names (e.g., selection: {and: ["one", "two"]})
const normalizeSelectionComposition = o => {
return normalizeLogicalComposition(o, param => {
- var _normParams$selection;
+ var _normParams$emptySele2, _normParams$selection3, _normParams$selection4;
- const empty = normParams.emptySelections[param] ?? true;
+ const empty = (_normParams$emptySele2 = normParams.emptySelections[param]) !== null && _normParams$emptySele2 !== void 0 ? _normParams$emptySele2 : true;
const pred = {
param,
empty
};
- (_normParams$selection = normParams.selectionPredicates)[param] ?? (_normParams$selection[param] = []);
+ (_normParams$selection4 = (_normParams$selection3 = normParams.selectionPredicates)[param]) !== null && _normParams$selection4 !== void 0 ? _normParams$selection4 : _normParams$selection3[param] = [];
normParams.selectionPredicates[param].push(pred);
return pred;
});
};
return op.selection ? normalizeSelectionComposition(op.selection) : normalizeLogicalComposition(op.test || op.filter, o => o.selection ? normalizeSelectionComposition(o.selection) : o);
}
class TopLevelSelectionsNormalizer extends SpecMapper {
map(spec, normParams) {
- const selections = normParams.selections ?? [];
+ var _normParams$selection;
+ const selections = (_normParams$selection = normParams.selections) !== null && _normParams$selection !== void 0 ? _normParams$selection : [];
+
if (spec.params && !isUnitSpec(spec)) {
const params = [];
for (const param of spec.params) {
if (isSelectionParameter(param)) {
@@ -8847,13 +9128,15 @@
normParams.selections = selections;
return super.map(spec, addSpecNameToParams(spec, normParams));
}
mapUnit(spec, normParams) {
+ var _normParams$path;
+
const selections = normParams.selections;
if (!selections || !selections.length) return spec;
- const path = (normParams.path ?? []).concat(spec.name);
+ const path = ((_normParams$path = normParams.path) !== null && _normParams$path !== void 0 ? _normParams$path : []).concat(spec.name);
const params = [];
for (const selection of selections) {
// By default, apply selections to all unit views.
if (!selection.views || !selection.views.length) {
@@ -8881,12 +9164,14 @@
return proto.call(this, spec, addSpecNameToParams(spec, params));
};
}
function addSpecNameToParams(spec, params) {
+ var _params$path;
+
return spec.name ? { ...params,
- path: (params.path ?? []).concat(spec.name)
+ path: ((_params$path = params.path) !== null && _params$path !== void 0 ? _params$path : []).concat(spec.name)
} : params;
}
function normalize(spec, config) {
if (config === undefined) {
@@ -8915,21 +9200,22 @@
/**
* Decompose extended unit specs into composition of pure unit specs.
* And push top-level selection definitions down to unit specs.
*/
- function normalizeGenericSpec(spec, config = {}) {
+ function normalizeGenericSpec(spec) {
+ let config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const normParams = {
config
};
return topLevelSelectionNormalizer.map(coreNormalizer.map(selectionCompatNormalizer.map(spec, normParams), normParams), normParams);
}
function _normalizeAutoSize(autosize) {
- return vegaUtil.isString(autosize) ? {
+ return vega.isString(autosize) ? {
type: autosize
- } : autosize ?? {};
+ } : autosize !== null && autosize !== void 0 ? autosize : {};
}
/**
* Normalize autosize and deal with width or height == "container".
*/
@@ -9004,11 +9290,13 @@
* we want to prioritize properties that users explicitly specified.
*/
// eslint-disable-next-line @typescript-eslint/ban-types
class Split {
- constructor(explicit = {}, implicit = {}) {
+ constructor() {
+ let explicit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+ let implicit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
this.explicit = explicit;
this.implicit = implicit;
}
clone() {
@@ -9045,14 +9333,16 @@
explicit: false,
value: undefined
};
}
- setWithExplicit(key, {
- value,
- explicit
- }) {
+ setWithExplicit(key, _ref) {
+ let {
+ value,
+ explicit
+ } = _ref;
+
if (value !== undefined) {
this.set(key, value, explicit);
}
}
@@ -9060,14 +9350,16 @@
delete this[explicit ? 'implicit' : 'explicit'][key];
this[explicit ? 'explicit' : 'implicit'][key] = value;
return this;
}
- copyKeyFromSplit(key, {
- explicit,
- implicit
- }) {
+ copyKeyFromSplit(key, _ref2) {
+ let {
+ explicit,
+ implicit
+ } = _ref2;
+
// Explicit has higher precedence
if (explicit[key] !== undefined) {
this.set(key, explicit[key], true);
} else if (implicit[key] !== undefined) {
this.set(key, implicit[key], false);
@@ -9125,11 +9417,13 @@
} // If equal score, prefer v1.
return v1;
}
- function mergeValuesWithExplicit(v1, v2, property, propertyOf, tieBreaker = defaultTieBreaker) {
+ function mergeValuesWithExplicit(v1, v2, property, propertyOf) {
+ let tieBreaker = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : defaultTieBreaker;
+
if (v1 === undefined || v1.value === undefined) {
// For first run
return v2;
}
@@ -9148,11 +9442,14 @@
* Class to track interesting properties (see https://15721.courses.cs.cmu.edu/spring2016/papers/graefe-ieee1995.pdf)
* about how fields have been parsed or whether they have been derived in a transform. We use this to not parse the
* same field again (or differently).
*/
class AncestorParse extends Split {
- constructor(explicit = {}, implicit = {}, parseNothing = false) {
+ constructor() {
+ let explicit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+ let implicit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ let parseNothing = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
super(explicit, implicit);
this.explicit = explicit;
this.implicit = implicit;
this.parseNothing = parseNothing;
}
@@ -9198,230 +9495,17 @@
DataSourceType[DataSourceType["Row"] = 2] = "Row";
DataSourceType[DataSourceType["Column"] = 3] = "Column";
DataSourceType[DataSourceType["Lookup"] = 4] = "Lookup";
})(DataSourceType || (DataSourceType = {}));
- const VIEW = 'view',
- LBRACK = '[',
- RBRACK = ']',
- LBRACE = '{',
- RBRACE = '}',
- COLON = ':',
- COMMA = ',',
- NAME = '@',
- GT = '>',
- ILLEGAL$1 = /[[\]{}]/,
- DEFAULT_MARKS = {
- '*': 1,
- arc: 1,
- area: 1,
- group: 1,
- image: 1,
- line: 1,
- path: 1,
- rect: 1,
- rule: 1,
- shape: 1,
- symbol: 1,
- text: 1,
- trail: 1
- };
- let DEFAULT_SOURCE, MARKS;
- /**
- * Parse an event selector string.
- * Returns an array of event stream definitions.
- */
+ function assembleInit(init) {
+ let isExpr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
+ let wrap = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : vega.identity;
- function eventSelector(selector, source, marks) {
- DEFAULT_SOURCE = source || VIEW;
- MARKS = marks || DEFAULT_MARKS;
- return parseMerge(selector.trim()).map(parseSelector);
- }
-
- function isMarkType(type) {
- return MARKS[type];
- }
-
- function find(s, i, endChar, pushChar, popChar) {
- const n = s.length;
- let count = 0,
- c;
-
- for (; i < n; ++i) {
- c = s[i];
- if (!count && c === endChar) return i;else if (popChar && popChar.indexOf(c) >= 0) --count;else if (pushChar && pushChar.indexOf(c) >= 0) ++count;
- }
-
- return i;
- }
-
- function parseMerge(s) {
- const output = [],
- n = s.length;
- let start = 0,
- i = 0;
-
- while (i < n) {
- i = find(s, i, COMMA, LBRACK + LBRACE, RBRACK + RBRACE);
- output.push(s.substring(start, i).trim());
- start = ++i;
- }
-
- if (output.length === 0) {
- throw 'Empty event selector: ' + s;
- }
-
- return output;
- }
-
- function parseSelector(s) {
- return s[0] === '[' ? parseBetween(s) : parseStream(s);
- }
-
- function parseBetween(s) {
- const n = s.length;
- let i = 1,
- b;
- i = find(s, i, RBRACK, LBRACK, RBRACK);
-
- if (i === n) {
- throw 'Empty between selector: ' + s;
- }
-
- b = parseMerge(s.substring(1, i));
-
- if (b.length !== 2) {
- throw 'Between selector must have two elements: ' + s;
- }
-
- s = s.slice(i + 1).trim();
-
- if (s[0] !== GT) {
- throw 'Expected \'>\' after between selector: ' + s;
- }
-
- b = b.map(parseSelector);
- const stream = parseSelector(s.slice(1).trim());
-
- if (stream.between) {
- return {
- between: b,
- stream: stream
- };
- } else {
- stream.between = b;
- }
-
- return stream;
- }
-
- function parseStream(s) {
- const stream = {
- source: DEFAULT_SOURCE
- },
- source = [];
- let throttle = [0, 0],
- markname = 0,
- start = 0,
- n = s.length,
- i = 0,
- j,
- filter; // extract throttle from end
-
- if (s[n - 1] === RBRACE) {
- i = s.lastIndexOf(LBRACE);
-
- if (i >= 0) {
- try {
- throttle = parseThrottle(s.substring(i + 1, n - 1));
- } catch (e) {
- throw 'Invalid throttle specification: ' + s;
- }
-
- s = s.slice(0, i).trim();
- n = s.length;
- } else throw 'Unmatched right brace: ' + s;
-
- i = 0;
- }
-
- if (!n) throw s; // set name flag based on first char
-
- if (s[0] === NAME) markname = ++i; // extract first part of multi-part stream selector
-
- j = find(s, i, COLON);
-
- if (j < n) {
- source.push(s.substring(start, j).trim());
- start = i = ++j;
- } // extract remaining part of stream selector
-
-
- i = find(s, i, LBRACK);
-
- if (i === n) {
- source.push(s.substring(start, n).trim());
- } else {
- source.push(s.substring(start, i).trim());
- filter = [];
- start = ++i;
- if (start === n) throw 'Unmatched left bracket: ' + s;
- } // extract filters
-
-
- while (i < n) {
- i = find(s, i, RBRACK);
- if (i === n) throw 'Unmatched left bracket: ' + s;
- filter.push(s.substring(start, i).trim());
- if (i < n - 1 && s[++i] !== LBRACK) throw 'Expected left bracket: ' + s;
- start = ++i;
- } // marshall event stream specification
-
-
- if (!(n = source.length) || ILLEGAL$1.test(source[n - 1])) {
- throw 'Invalid event selector: ' + s;
- }
-
- if (n > 1) {
- stream.type = source[1];
-
- if (markname) {
- stream.markname = source[0].slice(1);
- } else if (isMarkType(source[0])) {
- stream.marktype = source[0];
- } else {
- stream.source = source[0];
- }
- } else {
- stream.type = source[0];
- }
-
- if (stream.type.slice(-1) === '!') {
- stream.consume = true;
- stream.type = stream.type.slice(0, -1);
- }
-
- if (filter != null) stream.filter = filter;
- if (throttle[0]) stream.throttle = throttle[0];
- if (throttle[1]) stream.debounce = throttle[1];
- return stream;
- }
-
- function parseThrottle(s) {
- const a = s.split(COMMA);
- if (!s.length || a.length > 2) throw s;
- return a.map(_ => {
- const x = +_;
- if (x !== x) throw s;
- return x;
- });
- }
-
- function assembleInit(init, isExpr = true, wrap = vegaUtil.identity) {
- if (vegaUtil.isArray(init)) {
+ if (vega.isArray(init)) {
const assembled = init.map(v => assembleInit(v, isExpr, wrap));
- return isExpr ? `[${assembled.join(', ')}]` : assembled;
+ return isExpr ? "[".concat(assembled.join(', '), "]") : assembled;
} else if (isDateTime(init)) {
if (isExpr) {
return wrap(dateTimeToExpr(init));
} else {
return wrap(dateTimeToTimestamp(init));
@@ -9429,13 +9513,15 @@
}
return isExpr ? wrap(stringify(init)) : init;
}
function assembleUnitSelectionSignals(model, signals) {
- for (const selCmpt of vals(model.component.selection ?? {})) {
+ for (const selCmpt of vals((_model$component$sele = model.component.selection) !== null && _model$component$sele !== void 0 ? _model$component$sele : {})) {
+ var _model$component$sele;
+
const name = selCmpt.name;
- let modifyExpr = `${name}${TUPLE}, ${selCmpt.resolve === 'global' ? 'true' : `{unit: ${unitName(model)}}`}`;
+ let modifyExpr = "".concat(name).concat(TUPLE, ", ").concat(selCmpt.resolve === 'global' ? 'true' : "{unit: ".concat(unitName(model), "}"));
for (const c of selectionCompilers) {
if (!c.defined(selCmpt)) continue;
if (c.signals) signals = c.signals(model, selCmpt, signals);
if (c.modifyExpr) modifyExpr = c.modifyExpr(model, selCmpt, modifyExpr);
@@ -9445,46 +9531,48 @@
name: name + MODIFY,
on: [{
events: {
signal: selCmpt.name + TUPLE
},
- update: `modify(${vegaUtil.stringValue(selCmpt.name + STORE)}, ${modifyExpr})`
+ update: "modify(".concat(vega.stringValue(selCmpt.name + STORE), ", ").concat(modifyExpr, ")")
}]
});
}
return cleanupEmptyOnArray(signals);
}
function assembleFacetSignals(model, signals) {
if (model.component.selection && keys(model.component.selection).length) {
- const name = vegaUtil.stringValue(model.getName('cell'));
+ const name = vega.stringValue(model.getName('cell'));
signals.unshift({
name: 'facet',
value: {},
on: [{
- events: eventSelector('mousemove', 'scope'),
- update: `isTuple(facet) ? facet : group(${name}).datum`
+ events: vega.parseSelector('mousemove', 'scope'),
+ update: "isTuple(facet) ? facet : group(".concat(name, ").datum")
}]
});
}
return cleanupEmptyOnArray(signals);
}
function assembleTopLevelSignals(model, signals) {
let hasSelections = false;
- for (const selCmpt of vals(model.component.selection ?? {})) {
+ for (const selCmpt of vals((_model$component$sele2 = model.component.selection) !== null && _model$component$sele2 !== void 0 ? _model$component$sele2 : {})) {
+ var _model$component$sele2;
+
const name = selCmpt.name;
- const store = vegaUtil.stringValue(name + STORE);
+ const store = vega.stringValue(name + STORE);
const hasSg = signals.filter(s => s.name === name);
if (hasSg.length === 0) {
const resolve = selCmpt.resolve === 'global' ? 'union' : selCmpt.resolve;
const isPoint = selCmpt.type === 'point' ? ', true, true)' : ')';
signals.push({
name: selCmpt.name,
- update: `${VL_SELECTION_RESOLVE}(${store}, ${vegaUtil.stringValue(resolve)}${isPoint}`
+ update: "".concat(VL_SELECTION_RESOLVE, "(").concat(store, ", ").concat(vega.stringValue(resolve)).concat(isPoint)
});
}
hasSelections = true;
@@ -9513,11 +9601,13 @@
return cleanupEmptyOnArray(signals);
}
function assembleUnitSelectionData(model, data) {
const dataCopy = [...data];
- for (const selCmpt of vals(model.component.selection ?? {})) {
+ for (const selCmpt of vals((_model$component$sele3 = model.component.selection) !== null && _model$component$sele3 !== void 0 ? _model$component$sele3 : {})) {
+ var _model$component$sele3;
+
const init = {
name: selCmpt.name + STORE
};
if (selCmpt.init) {
@@ -9545,11 +9635,13 @@
}
return dataCopy;
}
function assembleUnitSelectionMarks(model, marks) {
- for (const selCmpt of vals(model.component.selection ?? {})) {
+ for (const selCmpt of vals((_model$component$sele4 = model.component.selection) !== null && _model$component$sele4 !== void 0 ? _model$component$sele4 : {})) {
+ var _model$component$sele4;
+
for (const c of selectionCompilers) {
if (c.defined(selCmpt) && c.marks) {
marks = c.marks(model, selCmpt, marks);
}
}
@@ -9567,11 +9659,11 @@
return marks;
}
function assembleSelectionScaleDomain(model, extent, scaleCmpt, domain) {
const parsedExtent = parseSelectionExtent(model, extent.param, extent);
return {
- signal: hasContinuousDomain(scaleCmpt.get('type')) && vegaUtil.isArray(domain) && domain[0] > domain[1] ? `isValid(${parsedExtent}) && reverse(${parsedExtent})` : parsedExtent
+ signal: hasContinuousDomain(scaleCmpt.get('type')) && vega.isArray(domain) && domain[0] > domain[1] ? "isValid(".concat(parsedExtent, ") && reverse(").concat(parsedExtent, ")") : parsedExtent
};
}
function cleanupEmptyOnArray(signals) {
return signals.map(s => {
@@ -9703,13 +9795,13 @@
}
class OutputNode extends DataFlowNode {
clone() {
const cloneObj = new this.constructor();
- cloneObj.debugName = `clone_${this.debugName}`;
+ cloneObj.debugName = "clone_".concat(this.debugName);
cloneObj._source = this._source;
- cloneObj._name = `clone_${this._name}`;
+ cloneObj._name = "clone_".concat(this._name);
cloneObj.type = this.type;
cloneObj.refCounts = this.refCounts;
cloneObj.refCounts[cloneObj._name] = 0;
return cloneObj;
}
@@ -9744,11 +9836,11 @@
return new Set();
}
hash() {
if (this._hash === undefined) {
- this._hash = `Output ${uniqueId()}`;
+ this._hash = "Output ".concat(uniqueId());
}
return this._hash;
}
/**
@@ -9881,11 +9973,11 @@
dependentFields() {
return new Set(vals(this.formula).map(f => f.field));
}
hash() {
- return `TimeUnit ${hash(this.formula)}`;
+ return "TimeUnit ".concat(hash(this.formula));
}
assemble() {
const transforms = [];
@@ -9908,11 +10000,11 @@
} : {}),
...(utc ? {
timezone: 'utc'
} : {}),
...params,
- as: [as, `${as}_end`]
+ as: [as, "".concat(as, "_end")]
});
}
return transforms;
}
@@ -9923,19 +10015,23 @@
/**
* Whether the selection tuples hold enumerated or ranged values for a field.
*/
class SelectionProjectionComponent {
- constructor(...items) {
+ constructor() {
_defineProperty(this, "hasChannel", void 0);
_defineProperty(this, "hasField", void 0);
_defineProperty(this, "timeUnit", void 0);
_defineProperty(this, "items", void 0);
+ for (var _len = arguments.length, items = new Array(_len), _key = 0; _key < _len; _key++) {
+ items[_key] = arguments[_key];
+ }
+
this.items = items;
this.hasChannel = {};
this.hasField = {};
}
@@ -9943,44 +10039,46 @@
const project = {
defined: () => {
return true; // This transform handles its own defaults, so always run parse.
},
parse: (model, selCmpt, selDef) => {
+ var _selCmpt$project;
+
const name = selCmpt.name;
- const proj = selCmpt.project ?? (selCmpt.project = new SelectionProjectionComponent());
+ const proj = (_selCmpt$project = selCmpt.project) !== null && _selCmpt$project !== void 0 ? _selCmpt$project : selCmpt.project = new SelectionProjectionComponent();
const parsed = {};
const timeUnits = {};
const signals = new Set();
const signalName = (p, range) => {
const suffix = range === 'visual' ? p.channel : p.field;
- let sg = varName(`${name}_${suffix}`);
+ let sg = varName("".concat(name, "_").concat(suffix));
for (let counter = 1; signals.has(sg); counter++) {
- sg = varName(`${name}_${suffix}_${counter}`);
+ sg = varName("".concat(name, "_").concat(suffix, "_").concat(counter));
}
signals.add(sg);
return {
[range]: sg
};
};
const type = selCmpt.type;
const cfg = model.config.selection[type];
- const init = selDef.value !== undefined ? vegaUtil.array(selDef.value) : null; // If no explicit projection (either fields or encodings) is specified, set some defaults.
+ const init = selDef.value !== undefined ? vega.array(selDef.value) : null; // If no explicit projection (either fields or encodings) is specified, set some defaults.
// If an initial value is set, try to infer projections.
let {
fields,
encodings
- } = vegaUtil.isObject(selDef.select) ? selDef.select : {};
+ } = vega.isObject(selDef.select) ? selDef.select : {};
if (!fields && !encodings && init) {
for (const initVal of init) {
// initVal may be a scalar value to smoothen varParam -> pointSelection gradient.
- if (!vegaUtil.isObject(initVal)) {
+ if (!vega.isObject(initVal)) {
continue;
}
for (const key of keys(initVal)) {
if (isSingleDefUnitChannel(key)) {
@@ -10006,11 +10104,13 @@
if ('fields' in cfg) {
fields = cfg.fields;
}
}
- for (const channel of encodings ?? []) {
+ for (const channel of (_encodings = encodings) !== null && _encodings !== void 0 ? _encodings : []) {
+ var _encodings;
+
const fieldDef = model.fieldDef(channel);
if (fieldDef) {
let field = fieldDef.field;
@@ -10068,11 +10168,13 @@
} else {
warn(cannotProjectOnChannelWithoutField(channel));
}
}
- for (const field of fields ?? []) {
+ for (const field of (_fields = fields) !== null && _fields !== void 0 ? _fields : []) {
+ var _fields;
+
if (proj.hasField[field]) continue;
const p = {
type: 'E',
field
};
@@ -10084,11 +10186,11 @@
if (init) {
selCmpt.init = init.map(v => {
// Selections can be initialized either with a full object that maps projections to values
// or scalar values to smoothen the abstraction gradient from variable params to point selections.
- return proj.items.map(p => vegaUtil.isObject(v) ? v[p.channel] !== undefined ? v[p.channel] : v[p.field] : v);
+ return proj.items.map(p => vega.isObject(v) ? v[p.channel] !== undefined ? v[p.channel] : v[p.field] : v);
});
}
if (!isEmpty(timeUnits)) {
proj.timeUnit = new TimeUnitNode(null, timeUnits);
@@ -10157,17 +10259,17 @@
const namedSg = signals.filter(s => s.name === selCmpt.name)[0];
let update = namedSg.update;
if (update.indexOf(VL_SELECTION_RESOLVE) >= 0) {
- namedSg.update = `{${bound.map(proj => `${vegaUtil.stringValue(replacePathInField(proj.field))}: ${proj.signals.data}`).join(', ')}}`;
+ namedSg.update = "{".concat(bound.map(proj => "".concat(vega.stringValue(replacePathInField(proj.field)), ": ").concat(proj.signals.data)).join(', '), "}");
} else {
for (const proj of bound) {
- const mapping = `${vegaUtil.stringValue(replacePathInField(proj.field))}: ${proj.signals.data}`;
+ const mapping = "".concat(vega.stringValue(replacePathInField(proj.field)), ": ").concat(proj.signals.data);
if (!update.includes(mapping)) {
- update = `${update.substring(0, update.length - 1)}, ${mapping}}`;
+ update = "".concat(update.substring(0, update.length - 1), ", ").concat(mapping, "}");
}
}
namedSg.update = update;
}
@@ -10189,16 +10291,18 @@
return signals;
}
};
function domain(model, channel) {
- const scale = vegaUtil.stringValue(model.scaleName(channel));
- return `domain(${scale})`;
+ const scale = vega.stringValue(model.scaleName(channel));
+ return "domain(".concat(scale, ")");
}
function isTopLevelLayer(model) {
- return model.parent && isLayerModel(model.parent) && (!model.parent.parent ?? isTopLevelLayer(model.parent.parent));
+ var _model$parent$parent;
+
+ return model.parent && isLayerModel(model.parent) && ((_model$parent$parent = !model.parent.parent) !== null && _model$parent$parent !== void 0 ? _model$parent$parent : isTopLevelLayer(model.parent.parent));
}
const BRUSH = '_brush';
const SCALE_TRIGGER = '_scale_trigger';
const interval = {
@@ -10210,15 +10314,15 @@
const init = selCmpt.init ? selCmpt.init[0] : null;
const dataSignals = [];
const scaleTriggers = [];
if (selCmpt.translate && !hasScales) {
- const filterExpr = `!event.item || event.item.mark.name !== ${vegaUtil.stringValue(name + BRUSH)}`;
+ const filterExpr = "!event.item || event.item.mark.name !== ".concat(vega.stringValue(name + BRUSH));
events(selCmpt, (on, evt) => {
- var _evt$between$;
+ var _evt$between$, _evt$between$$filter;
- const filters = vegaUtil.array((_evt$between$ = evt.between[0]).filter ?? (_evt$between$.filter = []));
+ const filters = vega.array((_evt$between$$filter = (_evt$between$ = evt.between[0]).filter) !== null && _evt$between$$filter !== void 0 ? _evt$between$$filter : _evt$between$.filter = []);
if (!filters.includes(filterExpr)) {
filters.push(filterExpr);
}
@@ -10236,18 +10340,18 @@
const val = init ? init[i] : null;
const cs = channelSignals(model, selCmpt, proj, val);
const dname = proj.signals.data;
const vname = proj.signals.visual;
- const scaleName = vegaUtil.stringValue(model.scaleName(channel));
+ const scaleName = vega.stringValue(model.scaleName(channel));
const scaleType = model.getScaleComponent(channel).get('type');
const toNum = hasContinuousDomain(scaleType) ? '+' : '';
signals.push(...cs);
dataSignals.push(dname);
scaleTriggers.push({
scaleName: model.scaleName(channel),
- expr: `(!isArray(${dname}) || ` + `(${toNum}invert(${scaleName}, ${vname})[0] === ${toNum}${dname}[0] && ` + `${toNum}invert(${scaleName}, ${vname})[1] === ${toNum}${dname}[1]))`
+ expr: "(!isArray(".concat(dname, ") || ") + "(".concat(toNum, "invert(").concat(scaleName, ", ").concat(vname, ")[0] === ").concat(toNum).concat(dname, "[0] && ") + "".concat(toNum, "invert(").concat(scaleName, ", ").concat(vname, ")[1] === ").concat(toNum).concat(dname, "[1]))")
});
}); // Proxy scale reactions to ensure that an infinite loop doesn't occur
// when an interval selection filter touches the scale.
if (!hasScales && scaleTriggers.length) {
@@ -10256,70 +10360,70 @@
value: {},
on: [{
events: scaleTriggers.map(t => ({
scale: t.scaleName
})),
- update: `${scaleTriggers.map(t => t.expr).join(' && ')} ? ${name + SCALE_TRIGGER} : {}`
+ update: "".concat(scaleTriggers.map(t => t.expr).join(' && '), " ? ").concat(name + SCALE_TRIGGER, " : {}")
}]
});
} // Only add an interval to the store if it has valid data extents. Data extents
// are set to null if pixel extents are equal to account for intervals over
// ordinal/nominal domains which, when inverted, will still produce a valid datum.
- const update = `unit: ${unitName(model)}, fields: ${fieldsSg}, values`;
+ const update = "unit: ".concat(unitName(model), ", fields: ").concat(fieldsSg, ", values");
return signals.concat({
name: name + TUPLE,
...(init ? {
- init: `{${update}: ${assembleInit(init)}}`
+ init: "{".concat(update, ": ").concat(assembleInit(init), "}")
} : {}),
...(dataSignals.length ? {
on: [{
events: [{
signal: dataSignals.join(' || ')
}],
// Prevents double invocation, see https://github.com/vega/vega#1672.
- update: `${dataSignals.join(' && ')} ? {${update}: [${dataSignals}]} : null`
+ update: "".concat(dataSignals.join(' && '), " ? {").concat(update, ": [").concat(dataSignals, "]} : null")
}]
} : {})
});
},
marks: (model, selCmpt, marks) => {
const name = selCmpt.name;
const {
x,
y
} = selCmpt.project.hasChannel;
- const xvname = x && x.signals.visual;
- const yvname = y && y.signals.visual;
- const store = `data(${vegaUtil.stringValue(selCmpt.name + STORE)})`; // Do not add a brush if we're binding to scales
+ const xvname = x === null || x === void 0 ? void 0 : x.signals.visual;
+ const yvname = y === null || y === void 0 ? void 0 : y.signals.visual;
+ const store = "data(".concat(vega.stringValue(selCmpt.name + STORE), ")"); // Do not add a brush if we're binding to scales
// or we don't have a valid interval projection
if (scaleBindings.defined(selCmpt) || !x && !y) {
return marks;
}
const update = {
x: x !== undefined ? {
- signal: `${xvname}[0]`
+ signal: "".concat(xvname, "[0]")
} : {
value: 0
},
y: y !== undefined ? {
- signal: `${yvname}[0]`
+ signal: "".concat(yvname, "[0]")
} : {
value: 0
},
x2: x !== undefined ? {
- signal: `${xvname}[1]`
+ signal: "".concat(xvname, "[1]")
} : {
field: {
group: 'width'
}
},
y2: y !== undefined ? {
- signal: `${yvname}[1]`
+ signal: "".concat(yvname, "[1]")
} : {
field: {
group: 'height'
}
}
@@ -10329,11 +10433,11 @@
// to a unit different from the one in the store.
if (selCmpt.resolve === 'global') {
for (const key of keys(update)) {
update[key] = [{
- test: `${store}.length && ${store}[0].unit === ${unitName(model)}`,
+ test: "".concat(store, ".length && ").concat(store, "[0].unit === ").concat(unitName(model)),
...update[key]
}, {
value: 0
}];
}
@@ -10348,19 +10452,19 @@
cursor,
...stroke
} = selCmpt.mark;
const vgStroke = keys(stroke).reduce((def, k) => {
def[k] = [{
- test: [x !== undefined && `${xvname}[0] !== ${xvname}[1]`, y !== undefined && `${yvname}[0] !== ${yvname}[1]`].filter(t => t).join(' && '),
+ test: [x !== undefined && "".concat(xvname, "[0] !== ").concat(xvname, "[1]"), y !== undefined && "".concat(yvname, "[0] !== ").concat(yvname, "[1]")].filter(t => t).join(' && '),
value: stroke[k]
}, {
value: null
}];
return def;
}, {});
return [{
- name: `${name + BRUSH}_bg`,
+ name: "".concat(name + BRUSH, "_bg"),
type: 'rect',
clip: true,
encode: {
enter: {
fill: {
@@ -10368,11 +10472,11 @@
},
fillOpacity: {
value: fillOpacity
}
},
- update: update
+ update
}
}, ...marks, {
name: name + BRUSH,
type: 'rect',
clip: true,
@@ -10400,37 +10504,37 @@
function channelSignals(model, selCmpt, proj, init) {
const channel = proj.channel;
const vname = proj.signals.visual;
const dname = proj.signals.data;
const hasScales = scaleBindings.defined(selCmpt);
- const scaleName = vegaUtil.stringValue(model.scaleName(channel));
+ const scaleName = vega.stringValue(model.scaleName(channel));
const scale = model.getScaleComponent(channel);
const scaleType = scale ? scale.get('type') : undefined;
- const scaled = str => `scale(${scaleName}, ${str})`;
+ const scaled = str => "scale(".concat(scaleName, ", ").concat(str, ")");
const size = model.getSizeSignalRef(channel === X ? 'width' : 'height').signal;
- const coord = `${channel}(unit)`;
+ const coord = "".concat(channel, "(unit)");
const on = events(selCmpt, (def, evt) => {
return [...def, {
events: evt.between[0],
- update: `[${coord}, ${coord}]`
+ update: "[".concat(coord, ", ").concat(coord, "]")
}, // Brush Start
{
events: evt,
- update: `[${vname}[0], clamp(${coord}, 0, ${size})]`
+ update: "[".concat(vname, "[0], clamp(").concat(coord, ", 0, ").concat(size, ")]")
} // Brush End
];
}); // React to pan/zooms of continuous scales. Non-continuous scales
// (band, point) cannot be pan/zoomed and any other changes
// to their domains (e.g., filtering) should clear the brushes.
on.push({
events: {
signal: selCmpt.name + SCALE_TRIGGER
},
- update: hasContinuousDomain(scaleType) ? `[${scaled(`${dname}[0]`)}, ${scaled(`${dname}[1]`)}]` : `[0, 0]`
+ update: hasContinuousDomain(scaleType) ? "[".concat(scaled("".concat(dname, "[0]")), ", ").concat(scaled("".concat(dname, "[1]")), "]") : "[0, 0]"
});
return hasScales ? [{
name: dname,
on: []
}] : [{
@@ -10438,69 +10542,71 @@
...(init ? {
init: assembleInit(init, true, scaled)
} : {
value: []
}),
- on: on
+ on
}, {
name: dname,
...(init ? {
init: assembleInit(init)
} : {}),
// Cannot be `value` as `init` may require datetime exprs.
on: [{
events: {
signal: vname
},
- update: `${vname}[0] === ${vname}[1] ? null : invert(${scaleName}, ${vname})`
+ update: "".concat(vname, "[0] === ").concat(vname, "[1] ? null : invert(").concat(scaleName, ", ").concat(vname, ")")
}]
}];
}
function events(selCmpt, cb) {
return selCmpt.events.reduce((on, evt) => {
if (!evt.between) {
- warn(`${evt} is not an ordered event stream for interval selections.`);
+ warn("".concat(evt, " is not an ordered event stream for interval selections."));
return on;
}
return cb(on, evt);
}, []);
}
const point$1 = {
defined: selCmpt => selCmpt.type === 'point',
signals: (model, selCmpt, signals) => {
+ var _model$component$sele;
+
const name = selCmpt.name;
const fieldsSg = name + TUPLE_FIELDS;
const project = selCmpt.project;
const datum = '(item().isVoronoi ? datum.datum : datum)';
const values = project.items.map(p => {
const fieldDef = model.fieldDef(p.channel); // Binned fields should capture extents, for a range test against the raw field.
- return fieldDef !== null && fieldDef !== void 0 && fieldDef.bin ? `[${datum}[${vegaUtil.stringValue(model.vgField(p.channel, {}))}], ` + `${datum}[${vegaUtil.stringValue(model.vgField(p.channel, {
- binSuffix: 'end'
- }))}]]` : `${datum}[${vegaUtil.stringValue(p.field)}]`;
+ return fieldDef !== null && fieldDef !== void 0 && fieldDef.bin ? "[".concat(datum, "[").concat(vega.stringValue(model.vgField(p.channel, {})), "], ") + "".concat(datum, "[").concat(vega.stringValue(model.vgField(p.channel, {
+ binSuffix: 'end'
+ })), "]]") : "".concat(datum, "[").concat(vega.stringValue(p.field), "]");
}).join(', '); // Only add a discrete selection to the store if a datum is present _and_
// the interaction isn't occurring on a group mark. This guards against
// polluting interactive state with invalid values in faceted displays
// as the group marks are also data-driven. We force the update to account
// for constant null states but varying toggles (e.g., shift-click in
// whitespace followed by a click in whitespace; the store should only
// be cleared on the second click).
- const update = `unit: ${unitName(model)}, fields: ${fieldsSg}, values`;
+ const update = "unit: ".concat(unitName(model), ", fields: ").concat(fieldsSg, ", values");
const events = selCmpt.events;
- const brushes = vals(model.component.selection ?? {}).reduce((acc, cmpt) => {
+ const brushes = vals((_model$component$sele = model.component.selection) !== null && _model$component$sele !== void 0 ? _model$component$sele : {}).reduce((acc, cmpt) => {
return cmpt.type === 'interval' ? acc.concat(cmpt.name + BRUSH) : acc;
- }, []).map(b => `indexof(item().mark.name, '${b}') < 0`).join(' && ');
- const test = `datum && item().mark.marktype !== 'group'` + (brushes ? ` && ${brushes}` : '');
+ }, []).map(b => "indexof(item().mark.name, '".concat(b, "') < 0")).join(' && ');
+ const test = "datum && item().mark.marktype !== 'group'".concat(brushes ? " && ".concat(brushes) : '');
return signals.concat([{
name: name + TUPLE,
on: events ? [{
events,
- update: `${test} ? {${update}: [${values}]} : null`,
+ update: "".concat(test, " ? {").concat(update, ": [").concat(values, "]} : null"),
force: true
}] : []
}]);
}
};
@@ -10512,11 +10618,11 @@
function wrapCondition(model, channelDef, vgChannel, refFn) {
const condition = isConditionalDef(channelDef) && channelDef.condition;
const valueRef = refFn(channelDef);
if (condition) {
- const conditions = vegaUtil.array(condition);
+ const conditions = vega.array(condition);
const vgConditions = conditions.map(c => {
const conditionValueRef = refFn(c);
if (isConditionalParameter(c)) {
const {
@@ -10548,15 +10654,18 @@
[vgChannel]: valueRef
} : {};
}
}
- function text$1(model, channel = 'text') {
+ function text$1(model) {
+ let channel = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'text';
const channelDef = model.encoding[channel];
return wrapCondition(model, channelDef, channel, cDef => textRef(cDef, model.config));
}
- function textRef(channelDef, config, expr = 'datum') {
+ function textRef(channelDef, config) {
+ let expr = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'datum';
+
// text
if (channelDef) {
if (isValueDef(channelDef)) {
return signalOrValueRef(channelDef.value);
}
@@ -10577,20 +10686,21 @@
}
return undefined;
}
- function tooltip(model, opt = {}) {
+ function tooltip(model) {
+ let opt = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const {
encoding,
markDef,
config,
stack
} = model;
const channelDef = encoding.tooltip;
- if (vegaUtil.isArray(channelDef)) {
+ if (vega.isArray(channelDef)) {
return {
tooltip: tooltipRefForEncoding({
tooltip: channelDef
}, stack, config, opt)
};
@@ -10615,15 +10725,15 @@
markTooltip = {
content: 'encoding'
};
}
- if (vegaUtil.isString(markTooltip)) {
+ if (vega.isString(markTooltip)) {
return {
value: markTooltip
};
- } else if (vegaUtil.isObject(markTooltip)) {
+ } else if (vega.isObject(markTooltip)) {
// `tooltip` is `{fields: 'encodings' | 'fields'}`
if (isSignalRef(markTooltip)) {
return markTooltip;
} else if (markTooltip.content === 'encoding') {
return tooltipRefForEncoding(encoding, stack, config, opt);
@@ -10636,25 +10746,28 @@
return undefined;
});
}
}
- function tooltipData(encoding, stack, config, {
- reactiveGeom
- } = {}) {
+ function tooltipData(encoding, stack, config) {
+ let {
+ reactiveGeom
+ } = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
const toSkip = {};
const expr = reactiveGeom ? 'datum.datum' : 'datum';
const tuples = [];
function add(fDef, channel) {
+ var _value;
+
const mainChannel = getMainRangeChannel(channel);
const fieldDef = isTypedFieldDef(fDef) ? fDef : { ...fDef,
type: encoding[mainChannel].type // for secondary field def, copy type from main channel
};
const title = fieldDef.title || defaultTitle(fieldDef, config);
- const key = vegaUtil.array(title).join(', ');
+ const key = vega.array(title).join(', ');
let value;
if (isXorY(channel)) {
const channel2 = channel === 'x' ? 'x2' : 'y2';
const fieldDef2 = getFieldDef(encoding[channel2]);
@@ -10686,11 +10799,11 @@
normalizeStack: true
}).signal;
}
}
- value ?? (value = textRef(fieldDef, config, expr).signal);
+ (_value = value) !== null && _value !== void 0 ? _value : value = textRef(fieldDef, config, expr).signal;
tuples.push({
channel,
key,
value
});
@@ -10715,19 +10828,23 @@
}
}
return out;
}
- function tooltipRefForEncoding(encoding, stack, config, {
- reactiveGeom
- } = {}) {
+ function tooltipRefForEncoding(encoding, stack, config) {
+ let {
+ reactiveGeom
+ } = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
const data = tooltipData(encoding, stack, config, {
reactiveGeom
});
- const keyValues = entries$1(data).map(([key, value]) => `"${key}": ${value}`);
+ const keyValues = entries$1(data).map(_ref => {
+ let [key, value] = _ref;
+ return "\"".concat(key, "\": ").concat(value);
+ });
return keyValues.length > 0 ? {
- signal: `{${keyValues.join(', ')}}`
+ signal: "{".concat(keyValues.join(', '), "}")
} : undefined;
}
function aria(model) {
const {
@@ -10810,20 +10927,24 @@
return undefined;
}
return {
description: {
- signal: entries$1(data).map(([key, value], index) => `"${index > 0 ? '; ' : ''}${key}: " + (${value})`).join(' + ')
+ signal: entries$1(data).map((_ref, index) => {
+ let [key, value] = _ref;
+ return "\"".concat(index > 0 ? '; ' : '').concat(key, ": \" + (").concat(value, ")");
+ }).join(' + ')
}
};
}
/**
* Return encode for non-positional channels with scales. (Text doesn't have scale.)
*/
- function nonPosition(channel, model, opt = {}) {
+ function nonPosition(channel, model) {
+ let opt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
const {
markDef,
encoding,
config
} = model;
@@ -10834,23 +10955,25 @@
defaultRef,
defaultValue
} = opt;
if (defaultRef === undefined) {
+ var _defaultValue;
+
// prettier-ignore
- defaultValue ?? (defaultValue = getMarkPropOrConfig(channel, markDef, config, {
+ (_defaultValue = defaultValue) !== null && _defaultValue !== void 0 ? _defaultValue : defaultValue = getMarkPropOrConfig(channel, markDef, config, {
vgChannel,
ignoreVgConfig: true
- }));
+ });
if (defaultValue !== undefined) {
defaultRef = signalOrValueRef(defaultValue);
}
}
const channelDef = encoding[channel];
- return wrapCondition(model, channelDef, vgChannel ?? channel, cDef => {
+ return wrapCondition(model, channelDef, vgChannel !== null && vgChannel !== void 0 ? vgChannel : channel, cDef => {
return midPoint({
channel,
channelDef: cDef,
markDef,
config,
@@ -10861,33 +10984,36 @@
defaultRef
});
});
}
- function color(model, opt = {
- filled: undefined
- }) {
+ function color(model) {
+ var _opt$filled, _ref, _getMarkPropOrConfig, _getMarkPropOrConfig2;
+
+ let opt = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
+ filled: undefined
+ };
const {
markDef,
encoding,
config
} = model;
const {
type: markType
} = markDef; // Allow filled to be overridden (for trail's "filled")
- const filled = opt.filled ?? getMarkPropOrConfig('filled', markDef, config);
+ const filled = (_opt$filled = opt.filled) !== null && _opt$filled !== void 0 ? _opt$filled : getMarkPropOrConfig('filled', markDef, config);
const transparentIfNeeded = contains(['bar', 'point', 'circle', 'square', 'geoshape'], markType) ? 'transparent' : undefined;
- const defaultFill = getMarkPropOrConfig(filled === true ? 'color' : undefined, markDef, config, {
+ const defaultFill = (_ref = (_getMarkPropOrConfig = getMarkPropOrConfig(filled === true ? 'color' : undefined, markDef, config, {
vgChannel: 'fill'
- }) ?? // need to add this manually as getMarkConfig normally drops config.mark[channel] if vgChannel is specified
- config.mark[filled === true && 'color'] ?? // If there is no fill, always fill symbols, bar, geoshape
+ })) !== null && _getMarkPropOrConfig !== void 0 ? _getMarkPropOrConfig : // need to add this manually as getMarkConfig normally drops config.mark[channel] if vgChannel is specified
+ config.mark[filled === true && 'color']) !== null && _ref !== void 0 ? _ref : // If there is no fill, always fill symbols, bar, geoshape
// with transparent fills https://github.com/vega/vega-lite/issues/1316
transparentIfNeeded;
- const defaultStroke = getMarkPropOrConfig(filled === false ? 'color' : undefined, markDef, config, {
+ const defaultStroke = (_getMarkPropOrConfig2 = getMarkPropOrConfig(filled === false ? 'color' : undefined, markDef, config, {
vgChannel: 'stroke'
- }) ?? // need to add this manually as getMarkConfig normally drops config.mark[channel] if vgChannel is specified
+ })) !== null && _getMarkPropOrConfig2 !== void 0 ? _getMarkPropOrConfig2 : // need to add this manually as getMarkConfig normally drops config.mark[channel] if vgChannel is specified
config.mark[filled === false && 'color'];
const colorVgChannel = filled ? 'fill' : 'stroke';
const fillStrokeMarkDefAndConfig = { ...(defaultFill ? {
fill: signalOrValueRef(defaultFill)
} : {}),
@@ -10934,41 +11060,82 @@
}
/**
* Utility files for producing Vega ValueRef for marks
*/
- function getOffset(channel, markDef) {
- const offsetChannel = getOffsetChannel(channel); // TODO: in the future read from encoding channel too
+ function positionOffset(_ref) {
+ let {
+ channel: baseChannel,
+ markDef,
+ encoding = {},
+ model,
+ bandPosition
+ } = _ref;
+ const channel = "".concat(baseChannel, "Offset"); // Need to cast as the type can't be inferred automatically
- const markDefOffsetValue = markDef[offsetChannel];
+ const defaultValue = markDef[channel];
+ const channelDef = encoding[channel];
+ if ((channel === 'xOffset' || channel === 'yOffset') && channelDef) {
+ const ref = midPoint({
+ channel: channel,
+ channelDef,
+ markDef,
+ config: model === null || model === void 0 ? void 0 : model.config,
+ scaleName: model.scaleName(channel),
+ scale: model.getScaleComponent(channel),
+ stack: null,
+ defaultRef: signalOrValueRef(defaultValue),
+ bandPosition
+ });
+ return {
+ offsetType: 'encoding',
+ offset: ref
+ };
+ }
+
+ const markDefOffsetValue = markDef[channel];
+
if (markDefOffsetValue) {
- return markDefOffsetValue;
+ return {
+ offsetType: 'visual',
+ offset: markDefOffsetValue
+ };
}
- return undefined;
+ return {};
}
/**
* Return encode for point (non-band) position channels.
*/
- function pointPosition(channel, model, {
- defaultPos,
- vgChannel
- }) {
+ function pointPosition(channel, model, _ref) {
+ let {
+ defaultPos,
+ vgChannel
+ } = _ref;
const {
encoding,
markDef,
config,
stack
} = model;
const channelDef = encoding[channel];
const channel2Def = encoding[getSecondaryRangeChannel(channel)];
const scaleName = model.scaleName(channel);
const scale = model.getScaleComponent(channel);
- const offset = getOffset(channel, markDef); // Get default position or position from mark def
+ const {
+ offset,
+ offsetType
+ } = positionOffset({
+ channel,
+ markDef,
+ encoding,
+ model,
+ bandPosition: 0.5
+ }); // Get default position or position from mark def
const defaultRef = pointPositionDefaultRef({
model,
defaultPos,
channel,
@@ -10986,11 +11153,12 @@
config,
scaleName,
scale,
stack,
offset,
- defaultRef
+ defaultRef,
+ bandPosition: offsetType === 'encoding' ? 0 : undefined
});
return valueRef ? {
[vgChannel || channel]: valueRef
} : undefined;
} // TODO: we need to find a way to refactor these so that scaleName is a part of scale
@@ -11040,17 +11208,18 @@
});
}
return midPointRefWithPositionInvalidTest(params);
}
- function pointPositionDefaultRef({
- model,
- defaultPos,
- channel,
- scaleName,
- scale
- }) {
+ function pointPositionDefaultRef(_ref2) {
+ let {
+ model,
+ defaultPos,
+ channel,
+ scaleName,
+ scale
+ } = _ref2;
const {
markDef,
config
} = model;
return () => {
@@ -11092,11 +11261,11 @@
// zeroOrMax
switch (mainChannel) {
case 'radius':
// max of radius is min(width, height) / 2
return {
- signal: `min(${model.width.signal},${model.height.signal})/2`
+ signal: "min(".concat(model.width.signal, ",").concat(model.height.signal, ")/2")
};
case 'theta':
return {
signal: '2*PI'
@@ -11118,11 +11287,11 @@
break;
case 'mid':
{
- const sizeRef = model[getSizeChannel$1(channel)];
+ const sizeRef = model[getSizeChannel(channel)];
return { ...sizeRef,
mult: 0.5
};
}
} // defaultPos === null
@@ -11140,11 +11309,13 @@
const BASELINED_Y_CHANNEL = {
top: 'y',
middle: 'yc',
bottom: 'y2'
};
- function vgAlignedPositionChannel(channel, markDef, config, defaultAlign = 'middle') {
+ function vgAlignedPositionChannel(channel, markDef, config) {
+ let defaultAlign = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'middle';
+
if (channel === 'radius' || channel === 'theta') {
return getVgPositionChannel(channel);
}
const alignChannel = channel === 'x' ? 'align' : 'baseline';
@@ -11168,15 +11339,17 @@
/**
* Utility for area/rule position, which can be either point or range.
* (One of the axes should be point and the other should be range.)
*/
- function pointOrRangePosition(channel, model, {
- defaultPos,
- defaultPos2,
- range
- }) {
+ function pointOrRangePosition(channel, model, _ref) {
+ let {
+ defaultPos,
+ defaultPos2,
+ range
+ } = _ref;
+
if (range) {
return rangePosition(channel, model, {
defaultPos,
defaultPos2
});
@@ -11184,20 +11357,21 @@
return pointPosition(channel, model, {
defaultPos
});
}
- function rangePosition(channel, model, {
- defaultPos,
- defaultPos2
- }) {
+ function rangePosition(channel, model, _ref2) {
+ let {
+ defaultPos,
+ defaultPos2
+ } = _ref2;
const {
markDef,
config
} = model;
const channel2 = getSecondaryRangeChannel(channel);
- const sizeChannel = getSizeChannel$1(channel);
+ const sizeChannel = getSizeChannel(channel);
const pos2Mixins = pointPosition2OrSize(model, defaultPos2, channel2);
const vgChannel = pos2Mixins[sizeChannel] ? // If there is width/height, we need to position the marks based on the alignment.
vgAlignedPositionChannel(channel, markDef, config) : // Otherwise, make sure to apply to the right Vg Channel (for arc mark)
getVgPositionChannel(channel);
return { ...pointPosition(channel, model, {
@@ -11219,19 +11393,31 @@
markDef,
stack,
config
} = model;
const baseChannel = getMainRangeChannel(channel);
- const sizeChannel = getSizeChannel$1(channel);
+ const sizeChannel = getSizeChannel(channel);
const vgChannel = getVgPositionChannel(channel);
const channelDef = encoding[baseChannel];
const scaleName = model.scaleName(baseChannel);
const scale = model.getScaleComponent(baseChannel);
- const offset = channel in encoding || channel in markDef ? getOffset(channel, model.markDef) : getOffset(baseChannel, model.markDef);
+ const {
+ offset
+ } = channel in encoding || channel in markDef ? positionOffset({
+ channel,
+ markDef,
+ encoding,
+ model
+ }) : positionOffset({
+ channel: baseChannel,
+ markDef,
+ encoding,
+ model
+ });
if (!channelDef && (channel === 'x2' || channel === 'y2') && (encoding.latitude || encoding.longitude)) {
- const vgSizeChannel = getSizeChannel$1(channel);
+ const vgSizeChannel = getSizeChannel(channel);
const size = model.markDef[vgSizeChannel];
if (size != null) {
return {
[vgSizeChannel]: {
@@ -11281,22 +11467,24 @@
scale
})()
};
}
- function position2Ref({
- channel,
- channelDef,
- channel2Def,
- markDef,
- config,
- scaleName,
- scale,
- stack,
- offset,
- defaultRef
- }) {
+ function position2Ref(_ref3) {
+ let {
+ channel,
+ channelDef,
+ channel2Def,
+ markDef,
+ config,
+ scaleName,
+ scale,
+ stack,
+ offset,
+ defaultRef
+ } = _ref3;
+
if (isFieldOrDatumDef(channelDef) && stack && // If fieldChannel is X and channel is X2 (or Y and Y2)
channel.charAt(0) === stack.fieldChannel.charAt(0)) {
return valueRefForFieldOrDatumDef(channelDef, scaleName, {
suffix: 'start'
}, {
@@ -11316,11 +11504,11 @@
defaultRef
});
}
function position2orSize(channel, markDef) {
- const sizeChannel = getSizeChannel$1(channel);
+ const sizeChannel = getSizeChannel(channel);
const vgChannel = getVgPositionChannel(channel);
if (markDef[vgChannel] !== undefined) {
return {
[vgChannel]: widthHeightValueOrSignalRef(channel, markDef[vgChannel])
@@ -11342,53 +11530,37 @@
}
return undefined;
}
- function rectPosition(model, channel, mark) {
+ function rectPosition(model, channel) {
+ var _ref, _encoding$sizeChannel;
+
const {
config,
encoding,
markDef
} = model;
+ const mark = markDef.type;
const channel2 = getSecondaryRangeChannel(channel);
- const sizeChannel = getSizeChannel$1(channel);
+ const sizeChannel = getSizeChannel(channel);
const channelDef = encoding[channel];
const channelDef2 = encoding[channel2];
const scale = model.getScaleComponent(channel);
const scaleType = scale ? scale.get('type') : undefined;
- const scaleName = model.scaleName(channel);
const orient = markDef.orient;
- const hasSizeDef = encoding[sizeChannel] ?? encoding.size ?? getMarkPropOrConfig('size', markDef, config, {
+ const hasSizeDef = (_ref = (_encoding$sizeChannel = encoding[sizeChannel]) !== null && _encoding$sizeChannel !== void 0 ? _encoding$sizeChannel : encoding.size) !== null && _ref !== void 0 ? _ref : getMarkPropOrConfig('size', markDef, config, {
vgChannel: sizeChannel
});
const isBarBand = mark === 'bar' && (channel === 'x' ? orient === 'vertical' : orient === 'horizontal'); // x, x2, and width -- we must specify two of these in all conditions
if (isFieldDef(channelDef) && (isBinning(channelDef.bin) || isBinned(channelDef.bin) || channelDef.timeUnit && !channelDef2) && !(hasSizeDef && !isRelativeBandSize(hasSizeDef)) && !hasDiscreteDomain(scaleType)) {
- var _model$component$axes;
-
- const bandSize = getBandSize({
- channel,
- fieldDef: channelDef,
- markDef,
- config,
- scaleType
- });
- const axis = (_model$component$axes = model.component.axes[channel]) === null || _model$component$axes === void 0 ? void 0 : _model$component$axes[0];
- const axisTranslate = (axis === null || axis === void 0 ? void 0 : axis.get('translate')) ?? 0.5; // vega default is 0.5
-
return rectBinPosition({
fieldDef: channelDef,
fieldDef2: channelDef2,
channel,
- markDef,
- scaleName,
- bandSize,
- axisTranslate,
- spacing: isXorY(channel) ? getMarkPropOrConfig('binSpacing', markDef, config) : undefined,
- reverse: scale.get('reverse'),
- config
+ model
});
} else if ((isFieldOrDatumDef(channelDef) && hasDiscreteDomain(scaleType) || isBarBand) && !channelDef2) {
return positionAndSize(channelDef, channel, model);
} else {
return rangePosition(channel, model, {
@@ -11430,11 +11602,11 @@
if (scale) {
const scaleRange = scale.get('range');
- if (isVgRangeStep(scaleRange) && vegaUtil.isNumber(scaleRange.step)) {
+ if (isVgRangeStep(scaleRange) && vega.isNumber(scaleRange.step)) {
return {
value: scaleRange.step - 2
};
}
}
@@ -11457,12 +11629,14 @@
stack
} = model;
const orient = markDef.orient;
const scaleName = model.scaleName(channel);
const scale = model.getScaleComponent(channel);
- const vgSizeChannel = getSizeChannel$1(channel);
- const channel2 = getSecondaryRangeChannel(channel); // use "size" channel for bars, if there is orient and the channel matches the right orientation
+ const vgSizeChannel = getSizeChannel(channel);
+ const channel2 = getSecondaryRangeChannel(channel);
+ const offsetScaleChannel = getOffsetChannel(channel);
+ const offsetScaleName = model.scaleName(offsetScaleChannel); // use "size" channel for bars, if there is orient and the channel matches the right orientation
const useVlSizeChannel = orient === 'horizontal' && channel === 'y' || orient === 'vertical' && channel === 'x'; // Use size encoding / mark property / config if it exists
let sizeMixins;
@@ -11485,11 +11659,11 @@
config,
scaleType: scale === null || scale === void 0 ? void 0 : scale.get('type'),
useVlSizeChannel
});
sizeMixins = sizeMixins || {
- [vgSizeChannel]: defaultSizeRef(vgSizeChannel, scaleName, scale, config, bandSize)
+ [vgSizeChannel]: defaultSizeRef(vgSizeChannel, offsetScaleName || scaleName, scale, config, bandSize)
};
/*
Band scales with size value and all point scales, use xc/yc + band=0.5
Otherwise (band scales that has size based on a band ref), use x/y with position band = (1 - size_band) / 2.
In this case, size_band is the band specified in the x/y-encoding.
@@ -11498,11 +11672,20 @@
*/
const defaultBandAlign = (scale === null || scale === void 0 ? void 0 : scale.get('type')) !== 'band' || !('band' in sizeMixins[vgSizeChannel]) ? 'middle' : 'top';
const vgChannel = vgAlignedPositionChannel(channel, markDef, config, defaultBandAlign);
const center = vgChannel === 'xc' || vgChannel === 'yc';
- const offset = getOffset(channel, markDef);
+ const {
+ offset,
+ offsetType
+ } = positionOffset({
+ channel,
+ markDef,
+ encoding,
+ model,
+ bandPosition: center ? 0.5 : 0
+ });
const posRef = midPointRefWithPositionInvalidTest({
channel,
channelDef: fieldDef,
markDef,
config,
@@ -11515,12 +11698,12 @@
defaultPos: 'mid',
channel,
scaleName,
scale
}),
- bandPosition: center ? 0.5 : isSignalRef(bandSize) ? {
- signal: `(1-${bandSize})/2`
+ bandPosition: center ? offsetType === 'encoding' ? 0 : 0.5 : isSignalRef(bandSize) ? {
+ signal: "(1-".concat(bandSize, ")/2")
} : isRelativeBandSize(bandSize) ? (1 - bandSize.band) / 2 : 0
});
if (vgSizeChannel) {
return {
@@ -11536,11 +11719,11 @@
offset
} : sizeRef;
return {
[vgChannel]: posRef,
// posRef might be an array that wraps position invalid test
- [vgChannel2]: vegaUtil.isArray(posRef) ? [posRef[0], { ...posRef[1],
+ [vgChannel2]: vega.isArray(posRef) ? [posRef[0], { ...posRef[1],
offset: sizeOffset
}] : { ...posRef,
offset: sizeOffset
}
};
@@ -11556,63 +11739,82 @@
if (isSignalRef(reverse) || isSignalRef(offset) || isSignalRef(translate)) {
const reverseExpr = signalOrStringValue(reverse);
const offsetExpr = signalOrStringValue(offset);
const translateExpr = signalOrStringValue(translate);
- const t = translateExpr ? `${translateExpr} + ` : '';
- const r = reverseExpr ? `(${reverseExpr} ? -1 : 1) * ` : '';
- const o = offsetExpr ? `(${offsetExpr} + ${spacingOffset})` : spacingOffset;
+ const t = translateExpr ? "".concat(translateExpr, " + ") : '';
+ const r = reverseExpr ? "(".concat(reverseExpr, " ? -1 : 1) * ") : '';
+ const o = offsetExpr ? "(".concat(offsetExpr, " + ").concat(spacingOffset, ")") : spacingOffset;
return {
signal: t + r + o
};
} else {
offset = offset || 0;
return translate + (reverse ? -offset - spacingOffset : +offset + spacingOffset);
}
}
- function rectBinPosition({
- fieldDef,
- fieldDef2,
- channel,
- bandSize,
- scaleName,
- markDef,
- spacing = 0,
- axisTranslate,
- reverse,
- config
- }) {
+ function rectBinPosition(_ref2) {
+ var _model$component$axes, _axis$get, _getMarkPropOrConfig;
+
+ let {
+ fieldDef,
+ fieldDef2,
+ channel,
+ model
+ } = _ref2;
+ const {
+ config,
+ markDef,
+ encoding
+ } = model;
+ const scale = model.getScaleComponent(channel);
+ const scaleName = model.scaleName(channel);
+ const scaleType = scale ? scale.get('type') : undefined;
+ const reverse = scale.get('reverse');
+ const bandSize = getBandSize({
+ channel,
+ fieldDef,
+ markDef,
+ config,
+ scaleType
+ });
+ const axis = (_model$component$axes = model.component.axes[channel]) === null || _model$component$axes === void 0 ? void 0 : _model$component$axes[0];
+ const axisTranslate = (_axis$get = axis === null || axis === void 0 ? void 0 : axis.get('translate')) !== null && _axis$get !== void 0 ? _axis$get : 0.5; // vega default is 0.5
+
+ const spacing = isXorY(channel) ? (_getMarkPropOrConfig = getMarkPropOrConfig('binSpacing', markDef, config)) !== null && _getMarkPropOrConfig !== void 0 ? _getMarkPropOrConfig : 0 : 0;
const channel2 = getSecondaryRangeChannel(channel);
const vgChannel = getVgPositionChannel(channel);
const vgChannel2 = getVgPositionChannel(channel2);
- const offset = getOffset(channel, markDef);
+ const {
+ offset
+ } = positionOffset({
+ channel,
+ markDef,
+ encoding,
+ model,
+ bandPosition: 0
+ });
const bandPosition = isSignalRef(bandSize) ? {
- signal: `(1-${bandSize.signal})/2`
+ signal: "(1-".concat(bandSize.signal, ")/2")
} : isRelativeBandSize(bandSize) ? (1 - bandSize.band) / 2 : 0.5;
if (isBinning(fieldDef.bin) || fieldDef.timeUnit) {
return {
[vgChannel2]: rectBinRef({
- channel,
fieldDef,
scaleName,
- markDef,
bandPosition,
- offset: getBinSpacing(channel2, spacing, reverse, axisTranslate, offset),
- config
+ offset: getBinSpacing(channel2, spacing, reverse, axisTranslate, offset)
}),
[vgChannel]: rectBinRef({
- channel,
fieldDef,
scaleName,
- markDef,
bandPosition: isSignalRef(bandPosition) ? {
- signal: `1-${bandPosition.signal}`
+ signal: "1-".concat(bandPosition.signal)
} : 1 - bandPosition,
- offset: getBinSpacing(channel, spacing, reverse, axisTranslate, offset),
- config
+ offset: getBinSpacing(channel, spacing, reverse, axisTranslate, offset)
})
};
} else if (isBinned(fieldDef.bin)) {
const startRef = valueRefForFieldOrDatumDef(fieldDef, scaleName, {}, {
offset: getBinSpacing(channel2, spacing, reverse, axisTranslate, offset)
@@ -11627,13 +11829,13 @@
};
} else if (isBinParams(fieldDef.bin) && fieldDef.bin.step) {
return {
[vgChannel2]: startRef,
[vgChannel]: {
- signal: `scale("${scaleName}", ${vgField(fieldDef, {
- expr: 'datum'
- })} + ${fieldDef.bin.step})`,
+ signal: "scale(\"".concat(scaleName, "\", ").concat(vgField(fieldDef, {
+ expr: 'datum'
+ }), " + ").concat(fieldDef.bin.step, ")"),
offset: getBinSpacing(channel, spacing, reverse, axisTranslate, offset)
}
};
}
}
@@ -11643,32 +11845,24 @@
}
/**
* Value Ref for binned fields
*/
- function rectBinRef({
- channel,
- fieldDef,
- scaleName,
- markDef,
- bandPosition,
- offset,
- config
- }) {
- const r = interpolatedSignalRef({
+
+ function rectBinRef(_ref3) {
+ let {
+ fieldDef,
scaleName,
+ bandPosition,
+ offset
+ } = _ref3;
+ return interpolatedSignalRef({
+ scaleName,
fieldOrDatumDef: fieldDef,
bandPosition,
offset
});
- return wrapPositionInvalidTest({
- fieldDef,
- channel,
- markDef,
- ref: r,
- config
- });
}
const ALWAYS_IGNORE = new Set(['aria', 'width', 'height']);
function baseEncodeEntry(model, ignore) {
const {
@@ -11711,11 +11905,11 @@
[channel]: [// prepend the invalid case
// TODO: support custom value
{
test,
value: null
- }, ...vegaUtil.array(valueRef)]
+ }, ...vega.array(valueRef)]
};
}
}
return valueRef ? {
@@ -11731,14 +11925,15 @@
return m;
}, {});
}
- function allFieldsInvalidPredicate$1(model, {
- invalid = false,
- channels
- }) {
+ function allFieldsInvalidPredicate$1(model, _ref) {
+ let {
+ invalid = false,
+ channels
+ } = _ref;
const filterIndex = channels.reduce((aggregator, channel) => {
const scaleComponent = model.getScaleComponent(channel);
if (scaleComponent) {
const scaleType = scaleComponent.get('type');
@@ -11755,11 +11950,11 @@
}, {});
const fields = keys(filterIndex);
if (fields.length > 0) {
const op = invalid ? '||' : '&&';
- return fields.map(field => fieldInvalidPredicate(field, invalid)).join(` ${op} `);
+ return fields.map(field => fieldInvalidPredicate(field, invalid)).join(" ".concat(op, " "));
}
return undefined;
}
@@ -11785,14 +11980,15 @@
}
return {};
}
- function allFieldsInvalidPredicate(model, {
- invalid = false,
- channels
- }) {
+ function allFieldsInvalidPredicate(model, _ref) {
+ let {
+ invalid = false,
+ channels
+ } = _ref;
const filterIndex = channels.reduce((aggregator, channel) => {
const scaleComponent = model.getScaleComponent(channel);
if (scaleComponent) {
const scaleType = scaleComponent.get('type');
@@ -11809,11 +12005,11 @@
}, {});
const fields = keys(filterIndex);
if (fields.length > 0) {
const op = invalid ? '||' : '&&';
- return fields.map(field => fieldInvalidPredicate(field, invalid)).join(` ${op} `);
+ return fields.map(field => fieldInvalidPredicate(field, invalid)).join(" ".concat(op, " "));
}
return undefined;
}
@@ -11891,12 +12087,14 @@
}]
};
let index = 0;
let exists = false;
marks.forEach((mark, i) => {
- const name = mark.name ?? '';
+ var _mark$name;
+ const name = (_mark$name = mark.name) !== null && _mark$name !== void 0 ? _mark$name : '';
+
if (name === model.component.mark[0].name) {
index = i;
} else if (name.indexOf(VORONOI) >= 0) {
exists = true;
}
@@ -11921,41 +12119,43 @@
const bind = selCmpt.bind;
const init = selCmpt.init && selCmpt.init[0]; // Can only exist on single selections (one initial value).
const datum = nearest.defined(selCmpt) ? '(item().isVoronoi ? datum.datum : datum)' : 'datum';
proj.items.forEach((p, i) => {
- const sgname = varName(`${name}_${p.field}`);
+ const sgname = varName("".concat(name, "_").concat(p.field));
const hasSignal = signals.filter(s => s.name === sgname);
if (!hasSignal.length) {
+ var _ref, _bind$p$field;
+
signals.unshift({
name: sgname,
...(init ? {
init: assembleInit(init[i])
} : {
value: null
}),
on: selCmpt.events ? [{
events: selCmpt.events,
- update: `datum && item().mark.marktype !== 'group' ? ${datum}[${vegaUtil.stringValue(p.field)}] : null`
+ update: "datum && item().mark.marktype !== 'group' ? ".concat(datum, "[").concat(vega.stringValue(p.field), "] : null")
}] : [],
- bind: bind[p.field] ?? bind[p.channel] ?? bind
+ bind: (_ref = (_bind$p$field = bind[p.field]) !== null && _bind$p$field !== void 0 ? _bind$p$field : bind[p.channel]) !== null && _ref !== void 0 ? _ref : bind
});
}
});
return signals;
},
signals: (model, selCmpt, signals) => {
const name = selCmpt.name;
const proj = selCmpt.project;
const signal = signals.filter(s => s.name === name + TUPLE)[0];
const fields = name + TUPLE_FIELDS;
- const values = proj.items.map(p => varName(`${name}_${p.field}`));
- const valid = values.map(v => `${v} !== null`).join(' && ');
+ const values = proj.items.map(p => varName("".concat(name, "_").concat(p.field)));
+ const valid = values.map(v => "".concat(v, " !== null")).join(' && ');
if (values.length) {
- signal.update = `${valid} ? {fields: ${fields}, values: [${values.join(', ')}]} : null`;
+ signal.update = "".concat(valid, " ? {fields: ").concat(fields, ", values: [").concat(values.join(', '), "]} : null");
}
delete signal.value;
delete signal.on;
return signals;
@@ -11978,27 +12178,27 @@
});
},
modifyExpr: (model, selCmpt) => {
const tpl = selCmpt.name + TUPLE;
const signal = selCmpt.name + TOGGLE;
- return `${signal} ? null : ${tpl}, ` + (selCmpt.resolve === 'global' ? `${signal} ? null : true, ` : `${signal} ? null : {unit: ${unitName(model)}}, `) + `${signal} ? ${tpl} : null`;
+ return "".concat(signal, " ? null : ").concat(tpl, ", ") + (selCmpt.resolve === 'global' ? "".concat(signal, " ? null : true, ") : "".concat(signal, " ? null : {unit: ").concat(unitName(model), "}, ")) + "".concat(signal, " ? ").concat(tpl, " : null");
}
};
const clear = {
defined: selCmpt => {
return selCmpt.clear !== undefined && selCmpt.clear !== false;
},
parse: (model, selCmpt) => {
if (selCmpt.clear) {
- selCmpt.clear = vegaUtil.isString(selCmpt.clear) ? eventSelector(selCmpt.clear, 'view') : selCmpt.clear;
+ selCmpt.clear = vega.isString(selCmpt.clear) ? vega.parseSelector(selCmpt.clear, 'view') : selCmpt.clear;
}
},
topLevelSignals: (model, selCmpt, signals) => {
if (inputBindings.defined(selCmpt)) {
for (const proj of selCmpt.project.items) {
- const idx = signals.findIndex(n => n.name === varName(`${selCmpt.name}_${proj.field}`));
+ const idx = signals.findIndex(n => n.name === varName("".concat(selCmpt.name, "_").concat(proj.field)));
if (idx !== -1) {
signals[idx].on.push({
events: selCmpt.clear,
update: 'null'
@@ -12056,11 +12256,11 @@
return spec && projLen;
},
parse: (model, selCmpt, selDef) => {
// Allow legend items to be toggleable by default even though direct manipulation is disabled.
const selDef_ = duplicate(selDef);
- selDef_.select = vegaUtil.isString(selDef_.select) ? {
+ selDef_.select = vega.isString(selDef_.select) ? {
type: selDef_.select,
toggle: selCmpt.toggle
} : { ...selDef_.select,
toggle: selCmpt.toggle
};
@@ -12068,20 +12268,22 @@
if (vega.isObject(selDef.select) && (selDef.select.on || selDef.select.clear)) {
const legendFilter = 'event.item && indexof(event.item.mark.role, "legend") < 0';
for (const evt of selCmpt.events) {
- evt.filter = vegaUtil.array(evt.filter ?? []);
+ var _evt$filter;
+ evt.filter = vega.array((_evt$filter = evt.filter) !== null && _evt$filter !== void 0 ? _evt$filter : []);
+
if (!evt.filter.includes(legendFilter)) {
evt.filter.push(legendFilter);
}
}
}
const evt = isLegendStreamBinding(selCmpt.bind) ? selCmpt.bind.legend : 'click';
- const stream = vegaUtil.isString(evt) ? eventSelector(evt, 'view') : vegaUtil.array(evt);
+ const stream = vega.isString(evt) ? vega.parseSelector(evt, 'view') : vega.array(evt);
selCmpt.bind = {
legend: {
merge: stream
}
};
@@ -12096,16 +12298,16 @@
return ds;
};
for (const proj of selCmpt.project.items) {
if (!proj.hasLegend) continue;
- const prefix = `${varName(proj.field)}_legend`;
- const sgName = `${selName}_${prefix}`;
+ const prefix = "".concat(varName(proj.field), "_legend");
+ const sgName = "".concat(selName, "_").concat(prefix);
const hasSignal = signals.filter(s => s.name === sgName);
if (hasSignal.length === 0) {
- const events = stream.merge.map(markName(`${prefix}_symbols`)).concat(stream.merge.map(markName(`${prefix}_labels`))).concat(stream.merge.map(markName(`${prefix}_entries`)));
+ const events = stream.merge.map(markName("".concat(prefix, "_symbols"))).concat(stream.merge.map(markName("".concat(prefix, "_labels")))).concat(stream.merge.map(markName("".concat(prefix, "_entries"))));
signals.unshift({
name: sgName,
...(!selCmpt.init ? {
value: null
} : {}),
@@ -12114,11 +12316,11 @@
events,
update: 'datum.value || item().items[0].items[0].datum.value',
force: true
}, {
events: stream.merge,
- update: `!event.item || !datum ? null : ${sgName}`,
+ update: "!event.item || !datum ? null : ".concat(sgName),
force: true
}]
});
}
}
@@ -12128,13 +12330,13 @@
signals: (model, selCmpt, signals) => {
const name = selCmpt.name;
const proj = selCmpt.project;
const tuple = signals.find(s => s.name === name + TUPLE);
const fields = name + TUPLE_FIELDS;
- const values = proj.items.filter(p => p.hasLegend).map(p => varName(`${name}_${varName(p.field)}_legend`));
- const valid = values.map(v => `${v} !== null`).join(' && ');
- const update = `${valid} ? {fields: ${fields}, values: [${values.join(', ')}]} : null`;
+ const values = proj.items.filter(p => p.hasLegend).map(p => varName("".concat(name, "_").concat(varName(p.field), "_legend")));
+ const valid = values.map(v => "".concat(v, " !== null")).join(' && ');
+ const update = "".concat(valid, " ? {fields: ").concat(fields, ", values: [").concat(values.join(', '), "]} : null");
if (selCmpt.events && values.length > 0) {
tuple.on.push({
events: values.map(signal => ({
signal
@@ -12162,15 +12364,19 @@
function parseInteractiveLegend(model, channel, legendCmpt) {
var _model$fieldDef;
const field = (_model$fieldDef = model.fieldDef(channel)) === null || _model$fieldDef === void 0 ? void 0 : _model$fieldDef.field;
- for (const selCmpt of vals(model.component.selection ?? {})) {
- const proj = selCmpt.project.hasField[field] ?? selCmpt.project.hasChannel[channel];
+ for (const selCmpt of vals((_model$component$sele = model.component.selection) !== null && _model$component$sele !== void 0 ? _model$component$sele : {})) {
+ var _model$component$sele, _selCmpt$project$hasF;
+ const proj = (_selCmpt$project$hasF = selCmpt.project.hasField[field]) !== null && _selCmpt$project$hasF !== void 0 ? _selCmpt$project$hasF : selCmpt.project.hasChannel[channel];
+
if (proj && legendBindings.defined(selCmpt)) {
- const legendSelections = legendCmpt.get('selections') ?? [];
+ var _legendCmpt$get;
+
+ const legendSelections = (_legendCmpt$get = legendCmpt.get('selections')) !== null && _legendCmpt$get !== void 0 ? _legendCmpt$get : [];
legendSelections.push(selCmpt.name);
legendCmpt.set('selections', legendSelections, false);
proj.hasLegend = true;
}
}
@@ -12188,29 +12394,29 @@
const anchor = name + ANCHOR$1;
const {
x,
y
} = selCmpt.project.hasChannel;
- let events = eventSelector(selCmpt.translate, 'scope');
+ let events = vega.parseSelector(selCmpt.translate, 'scope');
if (!hasScales) {
events = events.map(e => (e.between[0].markname = name + BRUSH, e));
}
signals.push({
name: anchor,
value: {},
on: [{
events: events.map(e => e.between[0]),
- update: '{x: x(unit), y: y(unit)' + (x !== undefined ? `, extent_x: ${hasScales ? domain(model, X) : `slice(${x.signals.visual})`}` : '') + (y !== undefined ? `, extent_y: ${hasScales ? domain(model, Y) : `slice(${y.signals.visual})`}` : '') + '}'
+ update: '{x: x(unit), y: y(unit)' + (x !== undefined ? ", extent_x: ".concat(hasScales ? domain(model, X) : "slice(".concat(x.signals.visual, ")")) : '') + (y !== undefined ? ", extent_y: ".concat(hasScales ? domain(model, Y) : "slice(".concat(y.signals.visual, ")")) : '') + '}'
}]
}, {
name: name + DELTA$1,
value: {},
on: [{
- events: events,
- update: `{x: ${anchor}.x - x(unit), y: ${anchor}.y - y(unit)}`
+ events,
+ update: "{x: ".concat(anchor, ".x - x(unit), y: ").concat(anchor, ".y - y(unit)}")
}]
});
if (x !== undefined) {
onDelta$1(model, selCmpt, x, 'width', signals);
@@ -12223,10 +12429,12 @@
return signals;
}
};
function onDelta$1(model, selCmpt, proj, size, signals) {
+ var _scaleCmpt$get, _scaleCmpt$get2;
+
const name = selCmpt.name;
const anchor = name + ANCHOR$1;
const delta = name + DELTA$1;
const channel = proj.channel;
const hasScales = scaleBindings.defined(selCmpt);
@@ -12235,20 +12443,20 @@
const scaleCmpt = model.getScaleComponent(channel);
const scaleType = scaleCmpt.get('type');
const reversed = scaleCmpt.get('reverse'); // scale parsing sets this flag for fieldDef.sort
const sign = !hasScales ? '' : channel === X ? reversed ? '' : '-' : reversed ? '-' : '';
- const extent = `${anchor}.extent_${channel}`;
- const offset = `${sign}${delta}.${channel} / ${hasScales ? `${sizeSg}` : `span(${extent})`}`;
+ const extent = "".concat(anchor, ".extent_").concat(channel);
+ const offset = "".concat(sign).concat(delta, ".").concat(channel, " / ").concat(hasScales ? "".concat(sizeSg) : "span(".concat(extent, ")"));
const panFn = !hasScales ? 'panLinear' : scaleType === 'log' ? 'panLog' : scaleType === 'symlog' ? 'panSymlog' : scaleType === 'pow' ? 'panPow' : 'panLinear';
- const arg = !hasScales ? '' : scaleType === 'pow' ? `, ${scaleCmpt.get('exponent') ?? 1}` : scaleType === 'symlog' ? `, ${scaleCmpt.get('constant') ?? 1}` : '';
- const update = `${panFn}(${extent}, ${offset}${arg})`;
+ const arg = !hasScales ? '' : scaleType === 'pow' ? ", ".concat((_scaleCmpt$get = scaleCmpt.get('exponent')) !== null && _scaleCmpt$get !== void 0 ? _scaleCmpt$get : 1) : scaleType === 'symlog' ? ", ".concat((_scaleCmpt$get2 = scaleCmpt.get('constant')) !== null && _scaleCmpt$get2 !== void 0 ? _scaleCmpt$get2 : 1) : '';
+ const update = "".concat(panFn, "(").concat(extent, ", ").concat(offset).concat(arg, ")");
signal.on.push({
events: {
signal: delta
},
- update: hasScales ? update : `clampRange(${update}, 0, ${sizeSg})`
+ update: hasScales ? update : "clampRange(".concat(update, ", 0, ").concat(sizeSg, ")")
});
}
const ANCHOR = '_zoom_anchor';
const DELTA = '_zoom_delta';
@@ -12262,28 +12470,28 @@
const delta = name + DELTA;
const {
x,
y
} = selCmpt.project.hasChannel;
- const sx = vegaUtil.stringValue(model.scaleName(X));
- const sy = vegaUtil.stringValue(model.scaleName(Y));
- let events = eventSelector(selCmpt.zoom, 'scope');
+ const sx = vega.stringValue(model.scaleName(X));
+ const sy = vega.stringValue(model.scaleName(Y));
+ let events = vega.parseSelector(selCmpt.zoom, 'scope');
if (!hasScales) {
events = events.map(e => (e.markname = name + BRUSH, e));
}
signals.push({
name: name + ANCHOR,
on: [{
- events: events,
- update: !hasScales ? `{x: x(unit), y: y(unit)}` : '{' + [sx ? `x: invert(${sx}, x(unit))` : '', sy ? `y: invert(${sy}, y(unit))` : ''].filter(expr => !!expr).join(', ') + '}'
+ events,
+ update: !hasScales ? "{x: x(unit), y: y(unit)}" : '{' + [sx ? "x: invert(".concat(sx, ", x(unit))") : '', sy ? "y: invert(".concat(sy, ", y(unit))") : ''].filter(expr => !!expr).join(', ') + '}'
}]
}, {
name: delta,
on: [{
- events: events,
+ events,
force: true,
update: 'pow(1.001, event.deltaY * pow(16, event.deltaMode))'
}]
});
@@ -12298,28 +12506,30 @@
return signals;
}
};
function onDelta(model, selCmpt, proj, size, signals) {
+ var _scaleCmpt$get, _scaleCmpt$get2;
+
const name = selCmpt.name;
const channel = proj.channel;
const hasScales = scaleBindings.defined(selCmpt);
const signal = signals.filter(s => s.name === proj.signals[hasScales ? 'data' : 'visual'])[0];
const sizeSg = model.getSizeSignalRef(size).signal;
const scaleCmpt = model.getScaleComponent(channel);
const scaleType = scaleCmpt.get('type');
const base = hasScales ? domain(model, channel) : signal.name;
const delta = name + DELTA;
- const anchor = `${name}${ANCHOR}.${channel}`;
+ const anchor = "".concat(name).concat(ANCHOR, ".").concat(channel);
const zoomFn = !hasScales ? 'zoomLinear' : scaleType === 'log' ? 'zoomLog' : scaleType === 'symlog' ? 'zoomSymlog' : scaleType === 'pow' ? 'zoomPow' : 'zoomLinear';
- const arg = !hasScales ? '' : scaleType === 'pow' ? `, ${scaleCmpt.get('exponent') ?? 1}` : scaleType === 'symlog' ? `, ${scaleCmpt.get('constant') ?? 1}` : '';
- const update = `${zoomFn}(${base}, ${anchor}, ${delta}${arg})`;
+ const arg = !hasScales ? '' : scaleType === 'pow' ? ", ".concat((_scaleCmpt$get = scaleCmpt.get('exponent')) !== null && _scaleCmpt$get !== void 0 ? _scaleCmpt$get : 1) : scaleType === 'symlog' ? ", ".concat((_scaleCmpt$get2 = scaleCmpt.get('constant')) !== null && _scaleCmpt$get2 !== void 0 ? _scaleCmpt$get2 : 1) : '';
+ const update = "".concat(zoomFn, "(").concat(base, ", ").concat(anchor, ", ").concat(delta).concat(arg, ")");
signal.on.push({
events: {
signal: delta
},
- update: hasScales ? update : `clampRange(${update}, 0, ${sizeSg})`
+ update: hasScales ? update : "clampRange(".concat(update, ", 0, ").concat(sizeSg, ")")
});
}
const STORE = '_store';
const TUPLE = '_tuple';
@@ -12338,34 +12548,37 @@
}
return parent;
}
- function unitName(model, {
- escape
- } = {
- escape: true
- }) {
- let name = escape ? vegaUtil.stringValue(model.name) : model.name;
+ function unitName(model) {
+ let {
+ escape
+ } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
+ escape: true
+ };
+ let name = escape ? vega.stringValue(model.name) : model.name;
const facetModel = getFacetModel(model);
if (facetModel) {
const {
facet
} = facetModel;
for (const channel of FACET_CHANNELS) {
if (facet[channel]) {
- name += ` + '__facet_${channel}_' + (facet[${vegaUtil.stringValue(facetModel.vgField(channel))}])`;
+ name += " + '__facet_".concat(channel, "_' + (facet[").concat(vega.stringValue(facetModel.vgField(channel)), "])");
}
}
}
return name;
}
function requiresSelectionId(model) {
- return vals(model.component.selection ?? {}).reduce((identifier, selCmpt) => {
+ var _model$component$sele;
+
+ return vals((_model$component$sele = model.component.selection) !== null && _model$component$sele !== void 0 ? _model$component$sele : {}).reduce((identifier, selCmpt) => {
return identifier || selCmpt.project.items.some(proj => proj.field === SELECTION_ID);
}, false);
} // Binding a point selection to query widgets or legends disables default direct manipulation interaction.
// A user can choose to re-enable it by explicitly specifying triggering input events.
@@ -12373,1574 +12586,10 @@
if (vega.isString(selDef.select) || !selDef.select.on) delete selCmpt.events;
if (vega.isString(selDef.select) || !selDef.select.clear) delete selCmpt.clear;
if (vega.isString(selDef.select) || !selDef.select.toggle) delete selCmpt.toggle;
}
- const RawCode = 'RawCode';
- const Literal = 'Literal';
- const Property = 'Property';
- const Identifier = 'Identifier';
- const ArrayExpression = 'ArrayExpression';
- const BinaryExpression = 'BinaryExpression';
- const CallExpression = 'CallExpression';
- const ConditionalExpression = 'ConditionalExpression';
- const LogicalExpression = 'LogicalExpression';
- const MemberExpression = 'MemberExpression';
- const ObjectExpression = 'ObjectExpression';
- const UnaryExpression = 'UnaryExpression';
-
- function ASTNode(type) {
- this.type = type;
- }
-
- ASTNode.prototype.visit = function (visitor) {
- let c, i, n;
- if (visitor(this)) return 1;
-
- for (c = children(this), i = 0, n = c.length; i < n; ++i) {
- if (c[i].visit(visitor)) return 1;
- }
- };
-
- function children(node) {
- switch (node.type) {
- case ArrayExpression:
- return node.elements;
-
- case BinaryExpression:
- case LogicalExpression:
- return [node.left, node.right];
-
- case CallExpression:
- return [node.callee].concat(node.arguments);
-
- case ConditionalExpression:
- return [node.test, node.consequent, node.alternate];
-
- case MemberExpression:
- return [node.object, node.property];
-
- case ObjectExpression:
- return node.properties;
-
- case Property:
- return [node.key, node.value];
-
- case UnaryExpression:
- return [node.argument];
-
- case Identifier:
- case Literal:
- case RawCode:
- default:
- return [];
- }
- }
- /*
- The following expression parser is based on Esprima (http://esprima.org/).
- Original header comment and license for Esprima is included here:
-
- Copyright (C) 2013 Ariya Hidayat <ariya.hidayat@gmail.com>
- Copyright (C) 2013 Thaddee Tyl <thaddee.tyl@gmail.com>
- Copyright (C) 2013 Mathias Bynens <mathias@qiwi.be>
- Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
- Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be>
- Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
- Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
- Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
- Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
- Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-
- var TokenName, source, index, length, lookahead;
- var TokenBooleanLiteral = 1,
- TokenEOF = 2,
- TokenIdentifier = 3,
- TokenKeyword = 4,
- TokenNullLiteral = 5,
- TokenNumericLiteral = 6,
- TokenPunctuator = 7,
- TokenStringLiteral = 8,
- TokenRegularExpression = 9;
- TokenName = {};
- TokenName[TokenBooleanLiteral] = 'Boolean';
- TokenName[TokenEOF] = '<end>';
- TokenName[TokenIdentifier] = 'Identifier';
- TokenName[TokenKeyword] = 'Keyword';
- TokenName[TokenNullLiteral] = 'Null';
- TokenName[TokenNumericLiteral] = 'Numeric';
- TokenName[TokenPunctuator] = 'Punctuator';
- TokenName[TokenStringLiteral] = 'String';
- TokenName[TokenRegularExpression] = 'RegularExpression';
- var SyntaxArrayExpression = 'ArrayExpression',
- SyntaxBinaryExpression = 'BinaryExpression',
- SyntaxCallExpression = 'CallExpression',
- SyntaxConditionalExpression = 'ConditionalExpression',
- SyntaxIdentifier = 'Identifier',
- SyntaxLiteral = 'Literal',
- SyntaxLogicalExpression = 'LogicalExpression',
- SyntaxMemberExpression = 'MemberExpression',
- SyntaxObjectExpression = 'ObjectExpression',
- SyntaxProperty = 'Property',
- SyntaxUnaryExpression = 'UnaryExpression'; // Error messages should be identical to V8.
-
- var MessageUnexpectedToken = 'Unexpected token %0',
- MessageUnexpectedNumber = 'Unexpected number',
- MessageUnexpectedString = 'Unexpected string',
- MessageUnexpectedIdentifier = 'Unexpected identifier',
- MessageUnexpectedReserved = 'Unexpected reserved word',
- MessageUnexpectedEOS = 'Unexpected end of input',
- MessageInvalidRegExp = 'Invalid regular expression',
- MessageUnterminatedRegExp = 'Invalid regular expression: missing /',
- MessageStrictOctalLiteral = 'Octal literals are not allowed in strict mode.',
- MessageStrictDuplicateProperty = 'Duplicate data property in object literal not allowed in strict mode';
- var ILLEGAL = 'ILLEGAL',
- DISABLED = 'Disabled.'; // See also tools/generate-unicode-regex.py.
-
- var RegexNonAsciiIdentifierStart = new RegExp('[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0-\\u08B2\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA7AD\\uA7B0\\uA7B1\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB5F\\uAB64\\uAB65\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]'),
- // eslint-disable-next-line no-misleading-character-class
- RegexNonAsciiIdentifierPart = new RegExp('[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0300-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u0483-\\u0487\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0610-\\u061A\\u0620-\\u0669\\u066E-\\u06D3\\u06D5-\\u06DC\\u06DF-\\u06E8\\u06EA-\\u06FC\\u06FF\\u0710-\\u074A\\u074D-\\u07B1\\u07C0-\\u07F5\\u07FA\\u0800-\\u082D\\u0840-\\u085B\\u08A0-\\u08B2\\u08E4-\\u0963\\u0966-\\u096F\\u0971-\\u0983\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BC-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CE\\u09D7\\u09DC\\u09DD\\u09DF-\\u09E3\\u09E6-\\u09F1\\u0A01-\\u0A03\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A59-\\u0A5C\\u0A5E\\u0A66-\\u0A75\\u0A81-\\u0A83\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABC-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AD0\\u0AE0-\\u0AE3\\u0AE6-\\u0AEF\\u0B01-\\u0B03\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3C-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B5C\\u0B5D\\u0B5F-\\u0B63\\u0B66-\\u0B6F\\u0B71\\u0B82\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD0\\u0BD7\\u0BE6-\\u0BEF\\u0C00-\\u0C03\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C58\\u0C59\\u0C60-\\u0C63\\u0C66-\\u0C6F\\u0C81-\\u0C83\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBC-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CDE\\u0CE0-\\u0CE3\\u0CE6-\\u0CEF\\u0CF1\\u0CF2\\u0D01-\\u0D03\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4E\\u0D57\\u0D60-\\u0D63\\u0D66-\\u0D6F\\u0D7A-\\u0D7F\\u0D82\\u0D83\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DE6-\\u0DEF\\u0DF2\\u0DF3\\u0E01-\\u0E3A\\u0E40-\\u0E4E\\u0E50-\\u0E59\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB9\\u0EBB-\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EC8-\\u0ECD\\u0ED0-\\u0ED9\\u0EDC-\\u0EDF\\u0F00\\u0F18\\u0F19\\u0F20-\\u0F29\\u0F35\\u0F37\\u0F39\\u0F3E-\\u0F47\\u0F49-\\u0F6C\\u0F71-\\u0F84\\u0F86-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u1000-\\u1049\\u1050-\\u109D\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135D-\\u135F\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176C\\u176E-\\u1770\\u1772\\u1773\\u1780-\\u17D3\\u17D7\\u17DC\\u17DD\\u17E0-\\u17E9\\u180B-\\u180D\\u1810-\\u1819\\u1820-\\u1877\\u1880-\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19D9\\u1A00-\\u1A1B\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1AB0-\\u1ABD\\u1B00-\\u1B4B\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1BF3\\u1C00-\\u1C37\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1CD0-\\u1CD2\\u1CD4-\\u1CF6\\u1CF8\\u1CF9\\u1D00-\\u1DF5\\u1DFC-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u200C\\u200D\\u203F\\u2040\\u2054\\u2071\\u207F\\u2090-\\u209C\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D7F-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2DE0-\\u2DFF\\u2E2F\\u3005-\\u3007\\u3021-\\u302F\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u3099\\u309A\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA66F\\uA674-\\uA67D\\uA67F-\\uA69D\\uA69F-\\uA6F1\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA7AD\\uA7B0\\uA7B1\\uA7F7-\\uA827\\uA840-\\uA873\\uA880-\\uA8C4\\uA8D0-\\uA8D9\\uA8E0-\\uA8F7\\uA8FB\\uA900-\\uA92D\\uA930-\\uA953\\uA960-\\uA97C\\uA980-\\uA9C0\\uA9CF-\\uA9D9\\uA9E0-\\uA9FE\\uAA00-\\uAA36\\uAA40-\\uAA4D\\uAA50-\\uAA59\\uAA60-\\uAA76\\uAA7A-\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEF\\uAAF2-\\uAAF6\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB5F\\uAB64\\uAB65\\uABC0-\\uABEA\\uABEC\\uABED\\uABF0-\\uABF9\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE00-\\uFE0F\\uFE20-\\uFE2D\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF10-\\uFF19\\uFF21-\\uFF3A\\uFF3F\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]'); // Ensure the condition is true, otherwise throw an error.
- // This is only to have a better contract semantic, i.e. another safety net
- // to catch a logic error. The condition shall be fulfilled in normal case.
- // Do NOT use this to enforce a certain condition on any user input.
-
- function assert(condition, message) {
- /* istanbul ignore next */
- if (!condition) {
- throw new Error('ASSERT: ' + message);
- }
- }
-
- function isDecimalDigit(ch) {
- return ch >= 0x30 && ch <= 0x39; // 0..9
- }
-
- function isHexDigit(ch) {
- return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
- }
-
- function isOctalDigit(ch) {
- return '01234567'.indexOf(ch) >= 0;
- } // 7.2 White Space
-
-
- function isWhiteSpace(ch) {
- return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0;
- } // 7.3 Line Terminators
-
-
- function isLineTerminator(ch) {
- return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029;
- } // 7.6 Identifier Names and Identifiers
-
-
- function isIdentifierStart(ch) {
- return ch === 0x24 || ch === 0x5F || // $ (dollar) and _ (underscore)
- ch >= 0x41 && ch <= 0x5A || // A..Z
- ch >= 0x61 && ch <= 0x7A || // a..z
- ch === 0x5C || // \ (backslash)
- ch >= 0x80 && RegexNonAsciiIdentifierStart.test(String.fromCharCode(ch));
- }
-
- function isIdentifierPart(ch) {
- return ch === 0x24 || ch === 0x5F || // $ (dollar) and _ (underscore)
- ch >= 0x41 && ch <= 0x5A || // A..Z
- ch >= 0x61 && ch <= 0x7A || // a..z
- ch >= 0x30 && ch <= 0x39 || // 0..9
- ch === 0x5C || // \ (backslash)
- ch >= 0x80 && RegexNonAsciiIdentifierPart.test(String.fromCharCode(ch));
- } // 7.6.1.1 Keywords
-
-
- const keywords = {
- 'if': 1,
- 'in': 1,
- 'do': 1,
- 'var': 1,
- 'for': 1,
- 'new': 1,
- 'try': 1,
- 'let': 1,
- 'this': 1,
- 'else': 1,
- 'case': 1,
- 'void': 1,
- 'with': 1,
- 'enum': 1,
- 'while': 1,
- 'break': 1,
- 'catch': 1,
- 'throw': 1,
- 'const': 1,
- 'yield': 1,
- 'class': 1,
- 'super': 1,
- 'return': 1,
- 'typeof': 1,
- 'delete': 1,
- 'switch': 1,
- 'export': 1,
- 'import': 1,
- 'public': 1,
- 'static': 1,
- 'default': 1,
- 'finally': 1,
- 'extends': 1,
- 'package': 1,
- 'private': 1,
- 'function': 1,
- 'continue': 1,
- 'debugger': 1,
- 'interface': 1,
- 'protected': 1,
- 'instanceof': 1,
- 'implements': 1
- };
-
- function skipComment() {
- while (index < length) {
- const ch = source.charCodeAt(index);
-
- if (isWhiteSpace(ch) || isLineTerminator(ch)) {
- ++index;
- } else {
- break;
- }
- }
- }
-
- function scanHexEscape(prefix) {
- var i,
- len,
- ch,
- code = 0;
- len = prefix === 'u' ? 4 : 2;
-
- for (i = 0; i < len; ++i) {
- if (index < length && isHexDigit(source[index])) {
- ch = source[index++];
- code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
- } else {
- throwError({}, MessageUnexpectedToken, ILLEGAL);
- }
- }
-
- return String.fromCharCode(code);
- }
-
- function scanUnicodeCodePointEscape() {
- var ch, code, cu1, cu2;
- ch = source[index];
- code = 0; // At least, one hex digit is required.
-
- if (ch === '}') {
- throwError({}, MessageUnexpectedToken, ILLEGAL);
- }
-
- while (index < length) {
- ch = source[index++];
-
- if (!isHexDigit(ch)) {
- break;
- }
-
- code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
- }
-
- if (code > 0x10FFFF || ch !== '}') {
- throwError({}, MessageUnexpectedToken, ILLEGAL);
- } // UTF-16 Encoding
-
-
- if (code <= 0xFFFF) {
- return String.fromCharCode(code);
- }
-
- cu1 = (code - 0x10000 >> 10) + 0xD800;
- cu2 = (code - 0x10000 & 1023) + 0xDC00;
- return String.fromCharCode(cu1, cu2);
- }
-
- function getEscapedIdentifier() {
- var ch, id;
- ch = source.charCodeAt(index++);
- id = String.fromCharCode(ch); // '\u' (U+005C, U+0075) denotes an escaped character.
-
- if (ch === 0x5C) {
- if (source.charCodeAt(index) !== 0x75) {
- throwError({}, MessageUnexpectedToken, ILLEGAL);
- }
-
- ++index;
- ch = scanHexEscape('u');
-
- if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) {
- throwError({}, MessageUnexpectedToken, ILLEGAL);
- }
-
- id = ch;
- }
-
- while (index < length) {
- ch = source.charCodeAt(index);
-
- if (!isIdentifierPart(ch)) {
- break;
- }
-
- ++index;
- id += String.fromCharCode(ch); // '\u' (U+005C, U+0075) denotes an escaped character.
-
- if (ch === 0x5C) {
- id = id.substr(0, id.length - 1);
-
- if (source.charCodeAt(index) !== 0x75) {
- throwError({}, MessageUnexpectedToken, ILLEGAL);
- }
-
- ++index;
- ch = scanHexEscape('u');
-
- if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) {
- throwError({}, MessageUnexpectedToken, ILLEGAL);
- }
-
- id += ch;
- }
- }
-
- return id;
- }
-
- function getIdentifier() {
- var start, ch;
- start = index++;
-
- while (index < length) {
- ch = source.charCodeAt(index);
-
- if (ch === 0x5C) {
- // Blackslash (U+005C) marks Unicode escape sequence.
- index = start;
- return getEscapedIdentifier();
- }
-
- if (isIdentifierPart(ch)) {
- ++index;
- } else {
- break;
- }
- }
-
- return source.slice(start, index);
- }
-
- function scanIdentifier() {
- var start, id, type;
- start = index; // Backslash (U+005C) starts an escaped character.
-
- id = source.charCodeAt(index) === 0x5C ? getEscapedIdentifier() : getIdentifier(); // There is no keyword or literal with only one character.
- // Thus, it must be an identifier.
-
- if (id.length === 1) {
- type = TokenIdentifier;
- } else if (keywords.hasOwnProperty(id)) {
- // eslint-disable-line no-prototype-builtins
- type = TokenKeyword;
- } else if (id === 'null') {
- type = TokenNullLiteral;
- } else if (id === 'true' || id === 'false') {
- type = TokenBooleanLiteral;
- } else {
- type = TokenIdentifier;
- }
-
- return {
- type: type,
- value: id,
- start: start,
- end: index
- };
- } // 7.7 Punctuators
-
-
- function scanPunctuator() {
- var start = index,
- code = source.charCodeAt(index),
- code2,
- ch1 = source[index],
- ch2,
- ch3,
- ch4;
-
- switch (code) {
- // Check for most common single-character punctuators.
- case 0x2E: // . dot
-
- case 0x28: // ( open bracket
-
- case 0x29: // ) close bracket
-
- case 0x3B: // ; semicolon
-
- case 0x2C: // , comma
-
- case 0x7B: // { open curly brace
-
- case 0x7D: // } close curly brace
-
- case 0x5B: // [
-
- case 0x5D: // ]
-
- case 0x3A: // :
-
- case 0x3F: // ?
-
- case 0x7E:
- // ~
- ++index;
- return {
- type: TokenPunctuator,
- value: String.fromCharCode(code),
- start: start,
- end: index
- };
-
- default:
- code2 = source.charCodeAt(index + 1); // '=' (U+003D) marks an assignment or comparison operator.
-
- if (code2 === 0x3D) {
- switch (code) {
- case 0x2B: // +
-
- case 0x2D: // -
-
- case 0x2F: // /
-
- case 0x3C: // <
-
- case 0x3E: // >
-
- case 0x5E: // ^
-
- case 0x7C: // |
-
- case 0x25: // %
-
- case 0x26: // &
-
- case 0x2A:
- // *
- index += 2;
- return {
- type: TokenPunctuator,
- value: String.fromCharCode(code) + String.fromCharCode(code2),
- start: start,
- end: index
- };
-
- case 0x21: // !
-
- case 0x3D:
- // =
- index += 2; // !== and ===
-
- if (source.charCodeAt(index) === 0x3D) {
- ++index;
- }
-
- return {
- type: TokenPunctuator,
- value: source.slice(start, index),
- start: start,
- end: index
- };
- }
- }
-
- } // 4-character punctuator: >>>=
-
-
- ch4 = source.substr(index, 4);
-
- if (ch4 === '>>>=') {
- index += 4;
- return {
- type: TokenPunctuator,
- value: ch4,
- start: start,
- end: index
- };
- } // 3-character punctuators: === !== >>> <<= >>=
-
-
- ch3 = ch4.substr(0, 3);
-
- if (ch3 === '>>>' || ch3 === '<<=' || ch3 === '>>=') {
- index += 3;
- return {
- type: TokenPunctuator,
- value: ch3,
- start: start,
- end: index
- };
- } // Other 2-character punctuators: ++ -- << >> && ||
-
-
- ch2 = ch3.substr(0, 2);
-
- if (ch1 === ch2[1] && '+-<>&|'.indexOf(ch1) >= 0 || ch2 === '=>') {
- index += 2;
- return {
- type: TokenPunctuator,
- value: ch2,
- start: start,
- end: index
- };
- }
-
- if (ch2 === '//') {
- throwError({}, MessageUnexpectedToken, ILLEGAL);
- } // 1-character punctuators: < > = ! + - * % & | ^ /
-
-
- if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
- ++index;
- return {
- type: TokenPunctuator,
- value: ch1,
- start: start,
- end: index
- };
- }
-
- throwError({}, MessageUnexpectedToken, ILLEGAL);
- } // 7.8.3 Numeric Literals
-
-
- function scanHexLiteral(start) {
- let number = '';
-
- while (index < length) {
- if (!isHexDigit(source[index])) {
- break;
- }
-
- number += source[index++];
- }
-
- if (number.length === 0) {
- throwError({}, MessageUnexpectedToken, ILLEGAL);
- }
-
- if (isIdentifierStart(source.charCodeAt(index))) {
- throwError({}, MessageUnexpectedToken, ILLEGAL);
- }
-
- return {
- type: TokenNumericLiteral,
- value: parseInt('0x' + number, 16),
- start: start,
- end: index
- };
- }
-
- function scanOctalLiteral(start) {
- let number = '0' + source[index++];
-
- while (index < length) {
- if (!isOctalDigit(source[index])) {
- break;
- }
-
- number += source[index++];
- }
-
- if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {
- throwError({}, MessageUnexpectedToken, ILLEGAL);
- }
-
- return {
- type: TokenNumericLiteral,
- value: parseInt(number, 8),
- octal: true,
- start: start,
- end: index
- };
- }
-
- function scanNumericLiteral() {
- var number, start, ch;
- ch = source[index];
- assert(isDecimalDigit(ch.charCodeAt(0)) || ch === '.', 'Numeric literal must start with a decimal digit or a decimal point');
- start = index;
- number = '';
-
- if (ch !== '.') {
- number = source[index++];
- ch = source[index]; // Hex number starts with '0x'.
- // Octal number starts with '0'.
-
- if (number === '0') {
- if (ch === 'x' || ch === 'X') {
- ++index;
- return scanHexLiteral(start);
- }
-
- if (isOctalDigit(ch)) {
- return scanOctalLiteral(start);
- } // decimal number starts with '0' such as '09' is illegal.
-
-
- if (ch && isDecimalDigit(ch.charCodeAt(0))) {
- throwError({}, MessageUnexpectedToken, ILLEGAL);
- }
- }
-
- while (isDecimalDigit(source.charCodeAt(index))) {
- number += source[index++];
- }
-
- ch = source[index];
- }
-
- if (ch === '.') {
- number += source[index++];
-
- while (isDecimalDigit(source.charCodeAt(index))) {
- number += source[index++];
- }
-
- ch = source[index];
- }
-
- if (ch === 'e' || ch === 'E') {
- number += source[index++];
- ch = source[index];
-
- if (ch === '+' || ch === '-') {
- number += source[index++];
- }
-
- if (isDecimalDigit(source.charCodeAt(index))) {
- while (isDecimalDigit(source.charCodeAt(index))) {
- number += source[index++];
- }
- } else {
- throwError({}, MessageUnexpectedToken, ILLEGAL);
- }
- }
-
- if (isIdentifierStart(source.charCodeAt(index))) {
- throwError({}, MessageUnexpectedToken, ILLEGAL);
- }
-
- return {
- type: TokenNumericLiteral,
- value: parseFloat(number),
- start: start,
- end: index
- };
- } // 7.8.4 String Literals
-
-
- function scanStringLiteral() {
- var str = '',
- quote,
- start,
- ch,
- code,
- octal = false;
- quote = source[index];
- assert(quote === '\'' || quote === '"', 'String literal must starts with a quote');
- start = index;
- ++index;
-
- while (index < length) {
- ch = source[index++];
-
- if (ch === quote) {
- quote = '';
- break;
- } else if (ch === '\\') {
- ch = source[index++];
-
- if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
- switch (ch) {
- case 'u':
- case 'x':
- if (source[index] === '{') {
- ++index;
- str += scanUnicodeCodePointEscape();
- } else {
- str += scanHexEscape(ch);
- }
-
- break;
-
- case 'n':
- str += '\n';
- break;
-
- case 'r':
- str += '\r';
- break;
-
- case 't':
- str += '\t';
- break;
-
- case 'b':
- str += '\b';
- break;
-
- case 'f':
- str += '\f';
- break;
-
- case 'v':
- str += '\x0B';
- break;
-
- default:
- if (isOctalDigit(ch)) {
- code = '01234567'.indexOf(ch); // \0 is not octal escape sequence
-
- if (code !== 0) {
- octal = true;
- }
-
- if (index < length && isOctalDigit(source[index])) {
- octal = true;
- code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts
- // with 0, 1, 2, 3
-
- if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) {
- code = code * 8 + '01234567'.indexOf(source[index++]);
- }
- }
-
- str += String.fromCharCode(code);
- } else {
- str += ch;
- }
-
- break;
- }
- } else {
- if (ch === '\r' && source[index] === '\n') {
- ++index;
- }
- }
- } else if (isLineTerminator(ch.charCodeAt(0))) {
- break;
- } else {
- str += ch;
- }
- }
-
- if (quote !== '') {
- throwError({}, MessageUnexpectedToken, ILLEGAL);
- }
-
- return {
- type: TokenStringLiteral,
- value: str,
- octal: octal,
- start: start,
- end: index
- };
- }
-
- function testRegExp(pattern, flags) {
- let tmp = pattern;
-
- if (flags.indexOf('u') >= 0) {
- // Replace each astral symbol and every Unicode code point
- // escape sequence with a single ASCII symbol to avoid throwing on
- // regular expressions that are only valid in combination with the
- // `/u` flag.
- // Note: replacing with the ASCII symbol `x` might cause false
- // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
- // perfectly valid pattern that is equivalent to `[a-b]`, but it
- // would be replaced by `[x-b]` which throws an error.
- tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, ($0, $1) => {
- if (parseInt($1, 16) <= 0x10FFFF) {
- return 'x';
- }
-
- throwError({}, MessageInvalidRegExp);
- }).replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 'x');
- } // First, detect invalid regular expressions.
-
-
- try {
- new RegExp(tmp);
- } catch (e) {
- throwError({}, MessageInvalidRegExp);
- } // Return a regular expression object for this pattern-flag pair, or
- // `null` in case the current environment doesn't support the flags it
- // uses.
-
-
- try {
- return new RegExp(pattern, flags);
- } catch (exception) {
- return null;
- }
- }
-
- function scanRegExpBody() {
- var ch, str, classMarker, terminated, body;
- ch = source[index];
- assert(ch === '/', 'Regular expression literal must start with a slash');
- str = source[index++];
- classMarker = false;
- terminated = false;
-
- while (index < length) {
- ch = source[index++];
- str += ch;
-
- if (ch === '\\') {
- ch = source[index++]; // ECMA-262 7.8.5
-
- if (isLineTerminator(ch.charCodeAt(0))) {
- throwError({}, MessageUnterminatedRegExp);
- }
-
- str += ch;
- } else if (isLineTerminator(ch.charCodeAt(0))) {
- throwError({}, MessageUnterminatedRegExp);
- } else if (classMarker) {
- if (ch === ']') {
- classMarker = false;
- }
- } else {
- if (ch === '/') {
- terminated = true;
- break;
- } else if (ch === '[') {
- classMarker = true;
- }
- }
- }
-
- if (!terminated) {
- throwError({}, MessageUnterminatedRegExp);
- } // Exclude leading and trailing slash.
-
-
- body = str.substr(1, str.length - 2);
- return {
- value: body,
- literal: str
- };
- }
-
- function scanRegExpFlags() {
- var ch, str, flags;
- str = '';
- flags = '';
-
- while (index < length) {
- ch = source[index];
-
- if (!isIdentifierPart(ch.charCodeAt(0))) {
- break;
- }
-
- ++index;
-
- if (ch === '\\' && index < length) {
- throwError({}, MessageUnexpectedToken, ILLEGAL);
- } else {
- flags += ch;
- str += ch;
- }
- }
-
- if (flags.search(/[^gimuy]/g) >= 0) {
- throwError({}, MessageInvalidRegExp, flags);
- }
-
- return {
- value: flags,
- literal: str
- };
- }
-
- function scanRegExp() {
- var start, body, flags, value;
- lookahead = null;
- skipComment();
- start = index;
- body = scanRegExpBody();
- flags = scanRegExpFlags();
- value = testRegExp(body.value, flags.value);
- return {
- literal: body.literal + flags.literal,
- value: value,
- regex: {
- pattern: body.value,
- flags: flags.value
- },
- start: start,
- end: index
- };
- }
-
- function isIdentifierName(token) {
- return token.type === TokenIdentifier || token.type === TokenKeyword || token.type === TokenBooleanLiteral || token.type === TokenNullLiteral;
- }
-
- function advance() {
- skipComment();
-
- if (index >= length) {
- return {
- type: TokenEOF,
- start: index,
- end: index
- };
- }
-
- const ch = source.charCodeAt(index);
-
- if (isIdentifierStart(ch)) {
- return scanIdentifier();
- } // Very common: ( and ) and ;
-
-
- if (ch === 0x28 || ch === 0x29 || ch === 0x3B) {
- return scanPunctuator();
- } // String literal starts with single quote (U+0027) or double quote (U+0022).
-
-
- if (ch === 0x27 || ch === 0x22) {
- return scanStringLiteral();
- } // Dot (.) U+002E can also start a floating-point number, hence the need
- // to check the next character.
-
-
- if (ch === 0x2E) {
- if (isDecimalDigit(source.charCodeAt(index + 1))) {
- return scanNumericLiteral();
- }
-
- return scanPunctuator();
- }
-
- if (isDecimalDigit(ch)) {
- return scanNumericLiteral();
- }
-
- return scanPunctuator();
- }
-
- function lex() {
- const token = lookahead;
- index = token.end;
- lookahead = advance();
- index = token.end;
- return token;
- }
-
- function peek() {
- const pos = index;
- lookahead = advance();
- index = pos;
- }
-
- function finishArrayExpression(elements) {
- const node = new ASTNode(SyntaxArrayExpression);
- node.elements = elements;
- return node;
- }
-
- function finishBinaryExpression(operator, left, right) {
- const node = new ASTNode(operator === '||' || operator === '&&' ? SyntaxLogicalExpression : SyntaxBinaryExpression);
- node.operator = operator;
- node.left = left;
- node.right = right;
- return node;
- }
-
- function finishCallExpression(callee, args) {
- const node = new ASTNode(SyntaxCallExpression);
- node.callee = callee;
- node.arguments = args;
- return node;
- }
-
- function finishConditionalExpression(test, consequent, alternate) {
- const node = new ASTNode(SyntaxConditionalExpression);
- node.test = test;
- node.consequent = consequent;
- node.alternate = alternate;
- return node;
- }
-
- function finishIdentifier(name) {
- const node = new ASTNode(SyntaxIdentifier);
- node.name = name;
- return node;
- }
-
- function finishLiteral(token) {
- const node = new ASTNode(SyntaxLiteral);
- node.value = token.value;
- node.raw = source.slice(token.start, token.end);
-
- if (token.regex) {
- if (node.raw === '//') {
- node.raw = '/(?:)/';
- }
-
- node.regex = token.regex;
- }
-
- return node;
- }
-
- function finishMemberExpression(accessor, object, property) {
- const node = new ASTNode(SyntaxMemberExpression);
- node.computed = accessor === '[';
- node.object = object;
- node.property = property;
- if (!node.computed) property.member = true;
- return node;
- }
-
- function finishObjectExpression(properties) {
- const node = new ASTNode(SyntaxObjectExpression);
- node.properties = properties;
- return node;
- }
-
- function finishProperty(kind, key, value) {
- const node = new ASTNode(SyntaxProperty);
- node.key = key;
- node.value = value;
- node.kind = kind;
- return node;
- }
-
- function finishUnaryExpression(operator, argument) {
- const node = new ASTNode(SyntaxUnaryExpression);
- node.operator = operator;
- node.argument = argument;
- node.prefix = true;
- return node;
- } // Throw an exception
-
-
- function throwError(token, messageFormat) {
- var error,
- args = Array.prototype.slice.call(arguments, 2),
- msg = messageFormat.replace(/%(\d)/g, (whole, index) => {
- assert(index < args.length, 'Message reference must be in range');
- return args[index];
- });
- error = new Error(msg);
- error.index = index;
- error.description = msg;
- throw error;
- } // Throw an exception because of the token.
-
-
- function throwUnexpected(token) {
- if (token.type === TokenEOF) {
- throwError(token, MessageUnexpectedEOS);
- }
-
- if (token.type === TokenNumericLiteral) {
- throwError(token, MessageUnexpectedNumber);
- }
-
- if (token.type === TokenStringLiteral) {
- throwError(token, MessageUnexpectedString);
- }
-
- if (token.type === TokenIdentifier) {
- throwError(token, MessageUnexpectedIdentifier);
- }
-
- if (token.type === TokenKeyword) {
- throwError(token, MessageUnexpectedReserved);
- } // BooleanLiteral, NullLiteral, or Punctuator.
-
-
- throwError(token, MessageUnexpectedToken, token.value);
- } // Expect the next token to match the specified punctuator.
- // If not, an exception will be thrown.
-
-
- function expect(value) {
- const token = lex();
-
- if (token.type !== TokenPunctuator || token.value !== value) {
- throwUnexpected(token);
- }
- } // Return true if the next token matches the specified punctuator.
-
-
- function match(value) {
- return lookahead.type === TokenPunctuator && lookahead.value === value;
- } // Return true if the next token matches the specified keyword
-
-
- function matchKeyword(keyword) {
- return lookahead.type === TokenKeyword && lookahead.value === keyword;
- } // 11.1.4 Array Initialiser
-
-
- function parseArrayInitialiser() {
- const elements = [];
- index = lookahead.start;
- expect('[');
-
- while (!match(']')) {
- if (match(',')) {
- lex();
- elements.push(null);
- } else {
- elements.push(parseConditionalExpression());
-
- if (!match(']')) {
- expect(',');
- }
- }
- }
-
- lex();
- return finishArrayExpression(elements);
- } // 11.1.5 Object Initialiser
-
-
- function parseObjectPropertyKey() {
- index = lookahead.start;
- const token = lex(); // Note: This function is called only from parseObjectProperty(), where
- // EOF and Punctuator tokens are already filtered out.
-
- if (token.type === TokenStringLiteral || token.type === TokenNumericLiteral) {
- if (token.octal) {
- throwError(token, MessageStrictOctalLiteral);
- }
-
- return finishLiteral(token);
- }
-
- return finishIdentifier(token.value);
- }
-
- function parseObjectProperty() {
- var token, key, id, value;
- index = lookahead.start;
- token = lookahead;
-
- if (token.type === TokenIdentifier) {
- id = parseObjectPropertyKey();
- expect(':');
- value = parseConditionalExpression();
- return finishProperty('init', id, value);
- }
-
- if (token.type === TokenEOF || token.type === TokenPunctuator) {
- throwUnexpected(token);
- } else {
- key = parseObjectPropertyKey();
- expect(':');
- value = parseConditionalExpression();
- return finishProperty('init', key, value);
- }
- }
-
- function parseObjectInitialiser() {
- var properties = [],
- property,
- name,
- key,
- map = {},
- toString = String;
- index = lookahead.start;
- expect('{');
-
- while (!match('}')) {
- property = parseObjectProperty();
-
- if (property.key.type === SyntaxIdentifier) {
- name = property.key.name;
- } else {
- name = toString(property.key.value);
- }
-
- key = '$' + name;
-
- if (Object.prototype.hasOwnProperty.call(map, key)) {
- throwError({}, MessageStrictDuplicateProperty);
- } else {
- map[key] = true;
- }
-
- properties.push(property);
-
- if (!match('}')) {
- expect(',');
- }
- }
-
- expect('}');
- return finishObjectExpression(properties);
- } // 11.1.6 The Grouping Operator
-
-
- function parseGroupExpression() {
- expect('(');
- const expr = parseExpression$1();
- expect(')');
- return expr;
- } // 11.1 Primary Expressions
-
-
- const legalKeywords = {
- 'if': 1
- };
-
- function parsePrimaryExpression() {
- var type, token, expr;
-
- if (match('(')) {
- return parseGroupExpression();
- }
-
- if (match('[')) {
- return parseArrayInitialiser();
- }
-
- if (match('{')) {
- return parseObjectInitialiser();
- }
-
- type = lookahead.type;
- index = lookahead.start;
-
- if (type === TokenIdentifier || legalKeywords[lookahead.value]) {
- expr = finishIdentifier(lex().value);
- } else if (type === TokenStringLiteral || type === TokenNumericLiteral) {
- if (lookahead.octal) {
- throwError(lookahead, MessageStrictOctalLiteral);
- }
-
- expr = finishLiteral(lex());
- } else if (type === TokenKeyword) {
- throw new Error(DISABLED);
- } else if (type === TokenBooleanLiteral) {
- token = lex();
- token.value = token.value === 'true';
- expr = finishLiteral(token);
- } else if (type === TokenNullLiteral) {
- token = lex();
- token.value = null;
- expr = finishLiteral(token);
- } else if (match('/') || match('/=')) {
- expr = finishLiteral(scanRegExp());
- peek();
- } else {
- throwUnexpected(lex());
- }
-
- return expr;
- } // 11.2 Left-Hand-Side Expressions
-
-
- function parseArguments() {
- const args = [];
- expect('(');
-
- if (!match(')')) {
- while (index < length) {
- args.push(parseConditionalExpression());
-
- if (match(')')) {
- break;
- }
-
- expect(',');
- }
- }
-
- expect(')');
- return args;
- }
-
- function parseNonComputedProperty() {
- index = lookahead.start;
- const token = lex();
-
- if (!isIdentifierName(token)) {
- throwUnexpected(token);
- }
-
- return finishIdentifier(token.value);
- }
-
- function parseNonComputedMember() {
- expect('.');
- return parseNonComputedProperty();
- }
-
- function parseComputedMember() {
- expect('[');
- const expr = parseExpression$1();
- expect(']');
- return expr;
- }
-
- function parseLeftHandSideExpressionAllowCall() {
- var expr, args, property;
- expr = parsePrimaryExpression();
-
- for (;;) {
- if (match('.')) {
- property = parseNonComputedMember();
- expr = finishMemberExpression('.', expr, property);
- } else if (match('(')) {
- args = parseArguments();
- expr = finishCallExpression(expr, args);
- } else if (match('[')) {
- property = parseComputedMember();
- expr = finishMemberExpression('[', expr, property);
- } else {
- break;
- }
- }
-
- return expr;
- } // 11.3 Postfix Expressions
-
-
- function parsePostfixExpression() {
- const expr = parseLeftHandSideExpressionAllowCall();
-
- if (lookahead.type === TokenPunctuator) {
- if (match('++') || match('--')) {
- throw new Error(DISABLED);
- }
- }
-
- return expr;
- } // 11.4 Unary Operators
-
-
- function parseUnaryExpression() {
- var token, expr;
-
- if (lookahead.type !== TokenPunctuator && lookahead.type !== TokenKeyword) {
- expr = parsePostfixExpression();
- } else if (match('++') || match('--')) {
- throw new Error(DISABLED);
- } else if (match('+') || match('-') || match('~') || match('!')) {
- token = lex();
- expr = parseUnaryExpression();
- expr = finishUnaryExpression(token.value, expr);
- } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
- throw new Error(DISABLED);
- } else {
- expr = parsePostfixExpression();
- }
-
- return expr;
- }
-
- function binaryPrecedence(token) {
- let prec = 0;
-
- if (token.type !== TokenPunctuator && token.type !== TokenKeyword) {
- return 0;
- }
-
- switch (token.value) {
- case '||':
- prec = 1;
- break;
-
- case '&&':
- prec = 2;
- break;
-
- case '|':
- prec = 3;
- break;
-
- case '^':
- prec = 4;
- break;
-
- case '&':
- prec = 5;
- break;
-
- case '==':
- case '!=':
- case '===':
- case '!==':
- prec = 6;
- break;
-
- case '<':
- case '>':
- case '<=':
- case '>=':
- case 'instanceof':
- case 'in':
- prec = 7;
- break;
-
- case '<<':
- case '>>':
- case '>>>':
- prec = 8;
- break;
-
- case '+':
- case '-':
- prec = 9;
- break;
-
- case '*':
- case '/':
- case '%':
- prec = 11;
- break;
- }
-
- return prec;
- } // 11.5 Multiplicative Operators
- // 11.6 Additive Operators
- // 11.7 Bitwise Shift Operators
- // 11.8 Relational Operators
- // 11.9 Equality Operators
- // 11.10 Binary Bitwise Operators
- // 11.11 Binary Logical Operators
-
-
- function parseBinaryExpression() {
- var marker, markers, expr, token, prec, stack, right, operator, left, i;
- marker = lookahead;
- left = parseUnaryExpression();
- token = lookahead;
- prec = binaryPrecedence(token);
-
- if (prec === 0) {
- return left;
- }
-
- token.prec = prec;
- lex();
- markers = [marker, lookahead];
- right = parseUnaryExpression();
- stack = [left, token, right];
-
- while ((prec = binaryPrecedence(lookahead)) > 0) {
- // Reduce: make a binary expression from the three topmost entries.
- while (stack.length > 2 && prec <= stack[stack.length - 2].prec) {
- right = stack.pop();
- operator = stack.pop().value;
- left = stack.pop();
- markers.pop();
- expr = finishBinaryExpression(operator, left, right);
- stack.push(expr);
- } // Shift.
-
-
- token = lex();
- token.prec = prec;
- stack.push(token);
- markers.push(lookahead);
- expr = parseUnaryExpression();
- stack.push(expr);
- } // Final reduce to clean-up the stack.
-
-
- i = stack.length - 1;
- expr = stack[i];
- markers.pop();
-
- while (i > 1) {
- markers.pop();
- expr = finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
- i -= 2;
- }
-
- return expr;
- } // 11.12 Conditional Operator
-
-
- function parseConditionalExpression() {
- var expr, consequent, alternate;
- expr = parseBinaryExpression();
-
- if (match('?')) {
- lex();
- consequent = parseConditionalExpression();
- expect(':');
- alternate = parseConditionalExpression();
- expr = finishConditionalExpression(expr, consequent, alternate);
- }
-
- return expr;
- } // 11.14 Comma Operator
-
-
- function parseExpression$1() {
- const expr = parseConditionalExpression();
-
- if (match(',')) {
- throw new Error(DISABLED); // no sequence expressions
- }
-
- return expr;
- }
-
- function parser(code) {
- source = code;
- index = 0;
- length = source.length;
- lookahead = null;
- peek();
- const expr = parseExpression$1();
-
- if (lookahead.type !== TokenEOF) {
- throw new Error('Unexpect token after expression.');
- }
-
- return expr;
- }
-
function getName(node) {
const name = [];
if (node.type === 'Identifier') {
return [node.name];
@@ -13965,12 +12614,13 @@
return node.object.name === 'datum';
}
function getDependentFields(expression) {
- const ast = parser(expression);
- const dependents = new Set();
+ const ast = vega.parseExpression(expression);
+ const dependents = new Set(); // visit is missing in types https://github.com/vega/vega/issues/3298
+
ast.visit(node => {
if (node.type === 'MemberExpression' && startsWithDatum(node)) {
dependents.add(getName(node).slice(1).join('.'));
}
});
@@ -14011,11 +12661,11 @@
expr: this.expr
};
}
hash() {
- return `Filter ${this.expr}`;
+ return "Filter ".concat(this.expr);
}
}
function parseUnitSelection(model, selDefs) {
@@ -14024,12 +12674,12 @@
if (!selDefs || !selDefs.length) return selCmpts;
for (const def of selDefs) {
const name = varName(def.name);
const selDef = def.select;
- const type = vegaUtil.isString(selDef) ? selDef : selDef.type;
- const defaults = vegaUtil.isObject(selDef) ? duplicate(selDef) : {
+ const type = vega.isString(selDef) ? selDef : selDef.type;
+ const defaults = vega.isObject(selDef) ? duplicate(selDef) : {
type
}; // Set default values from config if a property hasn't been specified,
// or if it is true. E.g., "translate": true should use the default
// event handlers for translate. However, true may be a valid value for
// a property (e.g., "nearest": true).
@@ -14047,20 +12697,22 @@
...defaults[key]
};
}
if (defaults[key] === undefined || defaults[key] === true) {
- defaults[key] = cfg[key] ?? defaults[key];
+ var _cfg$key;
+
+ defaults[key] = (_cfg$key = cfg[key]) !== null && _cfg$key !== void 0 ? _cfg$key : defaults[key];
}
}
const selCmpt = selCmpts[name] = { ...defaults,
name,
type,
init: def.value,
bind: def.bind,
- events: vegaUtil.isString(defaults.on) ? eventSelector(defaults.on, 'scope') : vegaUtil.array(duplicate(defaults.on))
+ events: vega.isString(defaults.on) ? vega.parseSelector(defaults.on, 'scope') : vega.array(duplicate(defaults.on))
};
for (const c of selectionCompilers) {
if (c.defined(selCmpt) && c.parse) {
c.parse(model, selCmpt, def);
@@ -14068,37 +12720,38 @@
}
}
return selCmpts;
}
- function parseSelectionPredicate(model, pred, dfnode, datum = 'datum') {
- const name = vegaUtil.isString(pred) ? pred : pred.param;
+ function parseSelectionPredicate(model, pred, dfnode) {
+ let datum = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'datum';
+ const name = vega.isString(pred) ? pred : pred.param;
const vname = varName(name);
- const store = vegaUtil.stringValue(vname + STORE);
+ const store = vega.stringValue(vname + STORE);
let selCmpt;
try {
selCmpt = model.getSelectionComponent(vname, name);
} catch (e) {
// If a selection isn't found, treat as a variable parameter and coerce to boolean.
- return `!!${vname}`;
+ return "!!".concat(vname);
}
if (selCmpt.project.timeUnit) {
- const child = dfnode ?? model.component.data.raw;
+ const child = dfnode !== null && dfnode !== void 0 ? dfnode : model.component.data.raw;
const tunode = selCmpt.project.timeUnit.clone();
if (child.parent) {
tunode.insertAsParentOf(child);
} else {
child.parent = tunode;
}
}
- const test = `vlSelectionTest(${store}, ${datum}${selCmpt.resolve === 'global' ? ')' : `, ${vegaUtil.stringValue(selCmpt.resolve)})`}`;
- const length = `length(data(${store}))`;
- return pred.empty === false ? `${length} && ${test}` : `!${length} || ${test}`;
+ const test = "vlSelectionTest(".concat(store, ", ").concat(datum).concat(selCmpt.resolve === 'global' ? ')' : ", ".concat(vega.stringValue(selCmpt.resolve), ")"));
+ const length = "length(data(".concat(store, "))");
+ return pred.empty === false ? "".concat(length, " && ").concat(test) : "!".concat(length, " || ").concat(test);
}
function parseSelectionExtent(model, name, extent) {
const vname = varName(name);
const encoding = extent['encoding'];
let field = extent['field'];
@@ -14113,28 +12766,30 @@
if (!encoding && !field) {
field = selCmpt.project.items[0].field;
if (selCmpt.project.items.length > 1) {
- warn('A "field" or "encoding" must be specified when using a selection as a scale domain. ' + `Using "field": ${vegaUtil.stringValue(field)}.`);
+ warn('A "field" or "encoding" must be specified when using a selection as a scale domain. ' + "Using \"field\": ".concat(vega.stringValue(field), "."));
}
} else if (encoding && !field) {
const encodings = selCmpt.project.items.filter(p => p.channel === encoding);
if (!encodings.length || encodings.length > 1) {
field = selCmpt.project.items[0].field;
- warn((!encodings.length ? 'No ' : 'Multiple ') + `matching ${vegaUtil.stringValue(encoding)} encoding found for selection ${vegaUtil.stringValue(extent.param)}. ` + `Using "field": ${vegaUtil.stringValue(field)}.`);
+ warn((!encodings.length ? 'No ' : 'Multiple ') + "matching ".concat(vega.stringValue(encoding), " encoding found for selection ").concat(vega.stringValue(extent.param), ". ") + "Using \"field\": ".concat(vega.stringValue(field), "."));
} else {
field = encodings[0].field;
}
}
- return `${selCmpt.name}[${vegaUtil.stringValue(replacePathInField(field))}]`;
+ return "".concat(selCmpt.name, "[").concat(vega.stringValue(replacePathInField(field)), "]");
}
function materializeSelections(model, main) {
- for (const [selection, selCmpt] of entries$1(model.component.selection ?? {})) {
- const lookupName = model.getName(`lookup_${selection}`);
+ for (const [selection, selCmpt] of entries$1((_model$component$sele = model.component.selection) !== null && _model$component$sele !== void 0 ? _model$component$sele : {})) {
+ var _model$component$sele;
+
+ const lookupName = model.getName("lookup_".concat(selection));
model.component.data.outputNodes[lookupName] = selCmpt.materialized = new OutputNode(new FilterNode(main, model, {
param: selection
}), lookupName, DataSourceType.Lookup, model.component.data.outputNodeRefCounts);
}
}
@@ -14144,11 +12799,11 @@
*/
// model is only used for selection filters.
function expression(model, filterOp, node) {
return logicalExpr(filterOp, predicate => {
- if (vegaUtil.isString(predicate)) {
+ if (vega.isString(predicate)) {
return predicate;
} else if (isSelectionPredicate(predicate)) {
return parseSelectionPredicate(model, predicate, node);
} else {
// Filter Object
@@ -14160,30 +12815,31 @@
function assembleTitle(title, config) {
if (!title) {
return undefined;
}
- if (vegaUtil.isArray(title) && !isText(title)) {
+ if (vega.isArray(title) && !isText(title)) {
return title.map(fieldDef => defaultTitle(fieldDef, config)).join(', ');
}
return title;
}
function setAxisEncode(axis, part, vgProp, vgRef) {
- var _axis$encode, _axis$encode$part;
+ var _axis$encode, _axis$encode2, _axis$encode2$part, _axis$encode$part, _axis$encode$part$upd;
- axis.encode ?? (axis.encode = {});
- (_axis$encode = axis.encode)[part] ?? (_axis$encode[part] = {});
- (_axis$encode$part = axis.encode[part]).update ?? (_axis$encode$part.update = {}); // TODO: remove as any after https://github.com/prisma/nexus-prisma/issues/291
+ (_axis$encode = axis.encode) !== null && _axis$encode !== void 0 ? _axis$encode : axis.encode = {};
+ (_axis$encode2$part = (_axis$encode2 = axis.encode)[part]) !== null && _axis$encode2$part !== void 0 ? _axis$encode2$part : _axis$encode2[part] = {};
+ (_axis$encode$part$upd = (_axis$encode$part = axis.encode[part]).update) !== null && _axis$encode$part$upd !== void 0 ? _axis$encode$part$upd : _axis$encode$part.update = {}; // TODO: remove as any after https://github.com/prisma/nexus-prisma/issues/291
axis.encode[part].update[vgProp] = vgRef;
}
- function assembleAxis(axisCmpt, kind, config, opt = {
- header: false
- }) {
+ function assembleAxis(axisCmpt, kind, config) {
+ let opt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
+ header: false
+ };
const {
disable,
orient,
scale,
labelExpr,
@@ -14207,11 +12863,11 @@
// deal with conditional axis value
const {
condition,
...valueOrSignalRef
} = propValue;
- const conditions = vegaUtil.array(condition);
+ const conditions = vega.array(condition);
const propIndex = CONDITIONAL_AXIS_PROP_INDEX[prop];
if (propIndex) {
const {
vgProp,
@@ -14237,12 +12893,12 @@
signal: conditions.map(c => {
const {
test,
...valueOrSignalCRef
} = c;
- return `${expression(null, test)} ? ${exprFromValueOrSignalRef(valueOrSignalCRef)} : `;
- }).join('') + exprFromValueOrSignalRef(valueOrSignalRef)
+ return "".concat(expression(null, test), " ? ").concat(exprFromValueRefOrSignalRef(valueOrSignalCRef), " : ");
+ }).join('') + exprFromValueRefOrSignalRef(valueOrSignalRef)
};
axis[prop] = signalRef;
}
} else if (isSignalRef(propValue)) {
const propIndex = CONDITIONAL_AXIS_PROP_INDEX[prop];
@@ -14308,15 +12964,15 @@
// if mainExtracted has been extracted to a separate facet
return undefined;
}
if (labelExpr !== undefined) {
- var _axis$encode2, _axis$encode2$labels;
+ var _axis$encode3, _axis$encode3$labels;
let expr = labelExpr;
- if ((_axis$encode2 = axis.encode) !== null && _axis$encode2 !== void 0 && (_axis$encode2$labels = _axis$encode2.labels) !== null && _axis$encode2$labels !== void 0 && _axis$encode2$labels.update && isSignalRef(axis.encode.labels.update.text)) {
+ if ((_axis$encode3 = axis.encode) !== null && _axis$encode3 !== void 0 && (_axis$encode3$labels = _axis$encode3.labels) !== null && _axis$encode3$labels !== void 0 && _axis$encode3$labels.update && isSignalRef(axis.encode.labels.update.text)) {
expr = replaceAll(labelExpr, 'datum.label', axis.encode.labels.update.text.signal);
}
setAxisEncode(axis, 'labels', 'text', {
signal: expr
@@ -14377,11 +13033,11 @@
const update = model.getSizeSignalRef(sizeType).signal;
if (sizeType !== update) {
signals.push({
name: sizeType,
- update: update
+ update
});
}
}
}
}
@@ -14408,11 +13064,11 @@
const conditionalOrientAxisConfig = {};
for (const prop of props.values()) {
conditionalOrientAxisConfig[prop] = {
// orient is surely signal in this case
- signal: `${orient['signal']} === "${orient1}" ? ${signalOrStringValue(orientConfig1[prop])} : ${signalOrStringValue(orientConfig2[prop])}`
+ signal: "".concat(orient['signal'], " === \"").concat(orient1, "\" ? ").concat(signalOrStringValue(orientConfig1[prop]), " : ").concat(signalOrStringValue(orientConfig2[prop]))
};
}
return conditionalOrientAxisConfig;
}
@@ -14422,11 +13078,11 @@
}
function getAxisConfigs(channel, scaleType, orient, config) {
const typeBasedConfigTypes = scaleType === 'band' ? ['axisDiscrete', 'axisBand'] : scaleType === 'point' ? ['axisDiscrete', 'axisPoint'] : isQuantitative(scaleType) ? ['axisQuantitative'] : scaleType === 'time' || scaleType === 'utc' ? ['axisTemporal'] : [];
const axisChannel = channel === 'x' ? 'axisX' : 'axisY';
- const axisOrient = isSignalRef(orient) ? 'axisOrient' : `axis${titleCase(orient)}`; // axisTop, axisBottom, ...
+ const axisOrient = isSignalRef(orient) ? 'axisOrient' : "axis".concat(titleCase(orient)); // axisTop, axisBottom, ...
const vlOnlyConfigTypes = [// technically Vega does have axisBand, but if we make another separation here,
// it will further introduce complexity in the code
...typeBasedConfigTypes, ...typeBasedConfigTypes.map(c => axisChannel + c.substr(4))];
const vgConfigTypes = ['axis', axisOrient, axisChannel];
@@ -14444,21 +13100,22 @@
// TODO: add special casing to add conditional value based on orient signal
let style = (_config$configType = config[configType]) === null || _config$configType === void 0 ? void 0 : _config$configType.style;
if (style) {
- style = vegaUtil.array(style);
+ style = vega.array(style);
for (const s of style) {
toMerge.push(config.style[s]);
}
}
}
return Object.assign.apply(null, toMerge);
}
- function getAxisConfig(property, styleConfigIndex, style, axisConfigs = {}) {
+ function getAxisConfig(property, styleConfigIndex, style) {
+ let axisConfigs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
const styleConfig = getStyleConfig(property, style, styleConfigIndex);
if (styleConfig !== undefined) {
return {
configFrom: 'style',
@@ -14479,96 +13136,136 @@
return {};
}
const axisRules = {
- scale: ({
- model,
- channel
- }) => model.scaleName(channel),
- format: ({
- fieldOrDatumDef,
- config,
- axis
- }) => {
+ scale: _ref => {
+ let {
+ model,
+ channel
+ } = _ref;
+ return model.scaleName(channel);
+ },
+ format: _ref2 => {
+ let {
+ fieldOrDatumDef,
+ config,
+ axis
+ } = _ref2;
const {
format,
formatType
} = axis;
return guideFormat(fieldOrDatumDef, fieldOrDatumDef.type, format, formatType, config, true);
},
- formatType: ({
- axis,
- fieldOrDatumDef,
- scaleType
- }) => {
+ formatType: _ref3 => {
+ let {
+ axis,
+ fieldOrDatumDef,
+ scaleType
+ } = _ref3;
const {
formatType
} = axis;
return guideFormatType(formatType, fieldOrDatumDef, scaleType);
},
- grid: ({
- fieldOrDatumDef,
- axis,
- scaleType
- }) => axis.grid ?? defaultGrid(scaleType, fieldOrDatumDef),
- gridScale: ({
- model,
- channel
- }) => gridScale(model, channel),
- labelAlign: ({
- axis,
- labelAngle,
- orient,
- channel
- }) => axis.labelAlign || defaultLabelAlign(labelAngle, orient, channel),
- labelAngle: ({
- labelAngle
- }) => labelAngle,
+ grid: _ref4 => {
+ var _axis$grid;
+
+ let {
+ fieldOrDatumDef,
+ axis,
+ scaleType
+ } = _ref4;
+ return (_axis$grid = axis.grid) !== null && _axis$grid !== void 0 ? _axis$grid : defaultGrid(scaleType, fieldOrDatumDef);
+ },
+ gridScale: _ref5 => {
+ let {
+ model,
+ channel
+ } = _ref5;
+ return gridScale(model, channel);
+ },
+ labelAlign: _ref6 => {
+ let {
+ axis,
+ labelAngle,
+ orient,
+ channel
+ } = _ref6;
+ return axis.labelAlign || defaultLabelAlign(labelAngle, orient, channel);
+ },
+ labelAngle: _ref7 => {
+ let {
+ labelAngle
+ } = _ref7;
+ return labelAngle;
+ },
// we already calculate this in parse
- labelBaseline: ({
- axis,
- labelAngle,
- orient,
- channel
- }) => axis.labelBaseline || defaultLabelBaseline(labelAngle, orient, channel),
- labelFlush: ({
- axis,
- fieldOrDatumDef,
- channel
- }) => axis.labelFlush ?? defaultLabelFlush(fieldOrDatumDef.type, channel),
- labelOverlap: ({
- axis,
- fieldOrDatumDef,
- scaleType
- }) => axis.labelOverlap ?? defaultLabelOverlap$1(fieldOrDatumDef.type, scaleType, isFieldDef(fieldOrDatumDef) && !!fieldOrDatumDef.timeUnit, isFieldDef(fieldOrDatumDef) ? fieldOrDatumDef.sort : undefined),
+ labelBaseline: _ref8 => {
+ let {
+ axis,
+ labelAngle,
+ orient,
+ channel
+ } = _ref8;
+ return axis.labelBaseline || defaultLabelBaseline(labelAngle, orient, channel);
+ },
+ labelFlush: _ref9 => {
+ var _axis$labelFlush;
+
+ let {
+ axis,
+ fieldOrDatumDef,
+ channel
+ } = _ref9;
+ return (_axis$labelFlush = axis.labelFlush) !== null && _axis$labelFlush !== void 0 ? _axis$labelFlush : defaultLabelFlush(fieldOrDatumDef.type, channel);
+ },
+ labelOverlap: _ref10 => {
+ var _axis$labelOverlap;
+
+ let {
+ axis,
+ fieldOrDatumDef,
+ scaleType
+ } = _ref10;
+ return (_axis$labelOverlap = axis.labelOverlap) !== null && _axis$labelOverlap !== void 0 ? _axis$labelOverlap : defaultLabelOverlap$1(fieldOrDatumDef.type, scaleType, isFieldDef(fieldOrDatumDef) && !!fieldOrDatumDef.timeUnit, isFieldDef(fieldOrDatumDef) ? fieldOrDatumDef.sort : undefined);
+ },
// we already calculate orient in parse
- orient: ({
- orient
- }) => orient,
+ orient: _ref11 => {
+ let {
+ orient
+ } = _ref11;
+ return orient;
+ },
// Need to cast until Vega supports signal
- tickCount: ({
- channel,
- model,
- axis,
- fieldOrDatumDef,
- scaleType
- }) => {
+ tickCount: _ref12 => {
+ var _axis$tickCount;
+
+ let {
+ channel,
+ model,
+ axis,
+ fieldOrDatumDef,
+ scaleType
+ } = _ref12;
const sizeType = channel === 'x' ? 'width' : channel === 'y' ? 'height' : undefined;
const size = sizeType ? model.getSizeSignalRef(sizeType) : undefined;
- return axis.tickCount ?? defaultTickCount({
+ return (_axis$tickCount = axis.tickCount) !== null && _axis$tickCount !== void 0 ? _axis$tickCount : defaultTickCount({
fieldOrDatumDef,
scaleType,
size,
values: axis.values
});
},
- title: ({
- axis,
- model,
- channel
- }) => {
+ title: _ref13 => {
+ let {
+ axis,
+ model,
+ channel
+ } = _ref13;
+
if (axis.title !== undefined) {
return axis.title;
}
const fieldDefTitle = getFieldDefTitle(model, channel);
@@ -14581,19 +13278,27 @@
const channel2 = channel === 'x' ? 'x2' : 'y2';
const fieldDef2 = model.fieldDef(channel2); // If title not specified, store base parts of fieldDef (and fieldDef2 if exists)
return mergeTitleFieldDefs(fieldDef ? [toFieldDefBase(fieldDef)] : [], isFieldDef(fieldDef2) ? [toFieldDefBase(fieldDef2)] : []);
},
- values: ({
- axis,
- fieldOrDatumDef
- }) => values$1(axis, fieldOrDatumDef),
- zindex: ({
- axis,
- fieldOrDatumDef,
- mark
- }) => axis.zindex ?? defaultZindex(mark, fieldOrDatumDef)
+ values: _ref14 => {
+ let {
+ axis,
+ fieldOrDatumDef
+ } = _ref14;
+ return values$1(axis, fieldOrDatumDef);
+ },
+ zindex: _ref15 => {
+ var _axis$zindex;
+
+ let {
+ axis,
+ fieldOrDatumDef,
+ mark
+ } = _ref15;
+ return (_axis$zindex = axis.zindex) !== null && _axis$zindex !== void 0 ? _axis$zindex : defaultZindex(mark, fieldOrDatumDef);
+ }
}; // TODO: we need to refactor this method after we take care of config refactoring
/**
* Default rules for whether to show a grid should be shown for a channel.
* If `grid` is unspecified, the default value is `true` for ordinal scales that are not binned
@@ -14634,53 +13339,53 @@
return undefined;
}
}
}
function normalizeAngleExpr(angle) {
- return `(((${angle.signal} % 360) + 360) % 360)`;
+ return "(((".concat(angle.signal, " % 360) + 360) % 360)");
}
function defaultLabelBaseline(angle, orient, channel, alwaysIncludeMiddle) {
if (angle !== undefined) {
if (channel === 'x') {
if (isSignalRef(angle)) {
const a = normalizeAngleExpr(angle);
- const orientIsTop = isSignalRef(orient) ? `(${orient.signal} === "top")` : orient === 'top';
+ const orientIsTop = isSignalRef(orient) ? "(".concat(orient.signal, " === \"top\")") : orient === 'top';
return {
- signal: `(45 < ${a} && ${a} < 135) || (225 < ${a} && ${a} < 315) ? "middle" :` + `(${a} <= 45 || 315 <= ${a}) === ${orientIsTop} ? "bottom" : "top"`
+ signal: "(45 < ".concat(a, " && ").concat(a, " < 135) || (225 < ").concat(a, " && ").concat(a, " < 315) ? \"middle\" :") + "(".concat(a, " <= 45 || 315 <= ").concat(a, ") === ").concat(orientIsTop, " ? \"bottom\" : \"top\"")
};
}
if (45 < angle && angle < 135 || 225 < angle && angle < 315) {
return 'middle';
}
if (isSignalRef(orient)) {
const op = angle <= 45 || 315 <= angle ? '===' : '!==';
return {
- signal: `${orient.signal} ${op} "top" ? "bottom" : "top"`
+ signal: "".concat(orient.signal, " ").concat(op, " \"top\" ? \"bottom\" : \"top\"")
};
}
return (angle <= 45 || 315 <= angle) === (orient === 'top') ? 'bottom' : 'top';
} else {
if (isSignalRef(angle)) {
const a = normalizeAngleExpr(angle);
- const orientIsLeft = isSignalRef(orient) ? `(${orient.signal} === "left")` : orient === 'left';
+ const orientIsLeft = isSignalRef(orient) ? "(".concat(orient.signal, " === \"left\")") : orient === 'left';
const middle = alwaysIncludeMiddle ? '"middle"' : 'null';
return {
- signal: `${a} <= 45 || 315 <= ${a} || (135 <= ${a} && ${a} <= 225) ? ${middle} : (45 <= ${a} && ${a} <= 135) === ${orientIsLeft} ? "top" : "bottom"`
+ signal: "".concat(a, " <= 45 || 315 <= ").concat(a, " || (135 <= ").concat(a, " && ").concat(a, " <= 225) ? ").concat(middle, " : (45 <= ").concat(a, " && ").concat(a, " <= 135) === ").concat(orientIsLeft, " ? \"top\" : \"bottom\"")
};
}
if (angle <= 45 || 315 <= angle || 135 <= angle && angle <= 225) {
return alwaysIncludeMiddle ? 'middle' : null;
}
if (isSignalRef(orient)) {
const op = 45 <= angle && angle <= 135 ? '===' : '!==';
return {
- signal: `${orient.signal} ${op} "left" ? "top" : "bottom"`
+ signal: "".concat(orient.signal, " ").concat(op, " \"left\" ? \"top\" : \"bottom\"")
};
}
return (45 <= angle && angle <= 135) === (orient === 'left') ? 'top' : 'bottom';
}
@@ -14697,26 +13402,26 @@
const startAngle = isX ? 0 : 90;
const mainOrient = isX ? 'bottom' : 'left';
if (isSignalRef(angle)) {
const a = normalizeAngleExpr(angle);
- const orientIsMain = isSignalRef(orient) ? `(${orient.signal} === "${mainOrient}")` : orient === mainOrient;
+ const orientIsMain = isSignalRef(orient) ? "(".concat(orient.signal, " === \"").concat(mainOrient, "\")") : orient === mainOrient;
return {
- signal: `(${startAngle ? `(${a} + 90)` : a} % 180 === 0) ? ${isX ? null : '"center"'} :` + `(${startAngle} < ${a} && ${a} < ${180 + startAngle}) === ${orientIsMain} ? "left" : "right"`
+ signal: "(".concat(startAngle ? "(".concat(a, " + 90)") : a, " % 180 === 0) ? ").concat(isX ? null : '"center"', " :") + "(".concat(startAngle, " < ").concat(a, " && ").concat(a, " < ").concat(180 + startAngle, ") === ").concat(orientIsMain, " ? \"left\" : \"right\"")
};
}
if ((angle + startAngle) % 180 === 0) {
// For bottom, use default label align so label flush still works
return isX ? null : 'center';
}
if (isSignalRef(orient)) {
const op = startAngle < angle && angle < 180 + startAngle ? '===' : '!==';
- const orientIsMain = `${orient.signal} ${op} "${mainOrient}"`;
+ const orientIsMain = "".concat(orient.signal, " ").concat(op, " \"").concat(mainOrient, "\"");
return {
- signal: `${orientIsMain} ? "left" : "right"`
+ signal: "".concat(orientIsMain, " ? \"left\" : \"right\"")
};
}
if ((startAngle < angle && angle < 180 + startAngle) === (orient === mainOrient)) {
return 'left';
@@ -14731,11 +13436,11 @@
return undefined;
}
function defaultLabelOverlap$1(type, scaleType, hasTimeUnit, sort) {
// do not prevent overlap for nominal data because there is no way to infer what the missing labels are
- if (hasTimeUnit && !vegaUtil.isObject(sort) || type !== 'nominal' && type !== 'ordinal') {
+ if (hasTimeUnit && !vega.isObject(sort) || type !== 'nominal' && type !== 'ordinal') {
if (scaleType === 'log' || scaleType === 'symlog') {
return 'greedy';
}
return true;
@@ -14744,34 +13449,36 @@
return undefined;
}
function defaultOrient(channel) {
return channel === 'x' ? 'bottom' : 'left';
}
- function defaultTickCount({
- fieldOrDatumDef,
- scaleType,
- size,
- values: vals
- }) {
+ function defaultTickCount(_ref16) {
+ let {
+ fieldOrDatumDef,
+ scaleType,
+ size,
+ values: vals
+ } = _ref16;
+
if (!vals && !hasDiscreteDomain(scaleType) && scaleType !== 'log') {
if (isFieldDef(fieldOrDatumDef)) {
var _normalizeTimeUnit;
if (isBinning(fieldOrDatumDef.bin)) {
// for binned data, we don't want more ticks than maxbins
return {
- signal: `ceil(${size.signal}/10)`
+ signal: "ceil(".concat(size.signal, "/10)")
};
}
if (fieldOrDatumDef.timeUnit && contains(['month', 'hours', 'day', 'quarter'], (_normalizeTimeUnit = normalizeTimeUnit(fieldOrDatumDef.timeUnit)) === null || _normalizeTimeUnit === void 0 ? void 0 : _normalizeTimeUnit.unit)) {
return undefined;
}
}
return {
- signal: `ceil(${size.signal}/40)`
+ signal: "ceil(".concat(size.signal, "/40)")
};
}
return undefined;
}
@@ -14799,11 +13506,11 @@
return undefined;
}
function values$1(axis, fieldOrDatumDef) {
const vals = axis.values;
- if (vegaUtil.isArray(vals)) {
+ if (vega.isArray(vals)) {
return valueArray(fieldOrDatumDef, vals);
} else if (isSignalRef(vals)) {
return vals;
}
@@ -14844,15 +13551,15 @@
timeUnit
} = fieldDef;
const sort = fieldDef.sort; // generate `datum["a"] === val0 ? 0 : datum["a"] === val1 ? 1 : ... : n` via FieldEqualPredicate
const calculate = sort.map((sortValue, i) => {
- return `${fieldFilterExpression({
- field,
- timeUnit,
- equal: sortValue
- })} ? ${i} : `;
+ return "".concat(fieldFilterExpression({
+ field,
+ timeUnit,
+ equal: sortValue
+ }), " ? ").concat(i, " : ");
}).join('') + sort.length;
parent = new CalculateNode(parent, {
calculate,
as: sortArrayIndexField(fieldDef, channel, {
forAs: true
@@ -14878,19 +13585,19 @@
as: this.transform.as
};
}
hash() {
- return `Calculate ${hash(this.transform)}`;
+ return "Calculate ".concat(hash(this.transform));
}
}
function sortArrayIndexField(fieldDef, channel, opt) {
return vgField(fieldDef, {
prefix: channel,
suffix: 'sort_index',
- ...(opt ?? {})
+ ...(opt !== null && opt !== void 0 ? opt : {})
});
}
/**
* Get header channel, which can be different from facet channel when orient is specified or when the facet channel is facet.
@@ -14942,13 +13649,13 @@
titleOrient
} = getHeaderProperties(['titleAnchor', 'titleAngle', 'titleOrient'], facetFieldDef.header, config, channel);
const headerChannel = getHeaderChannel(channel, titleOrient);
const titleAngle = normalizeAngle(ta);
return {
- name: `${channel}-title`,
+ name: "".concat(channel, "-title"),
type: 'group',
- role: `${headerChannel}-title`,
+ role: "".concat(headerChannel, "-title"),
title: {
text: title,
...(channel === 'row' ? {
orient: 'left'
} : {}),
@@ -14957,11 +13664,13 @@
...defaultHeaderGuideAlign(headerChannel, titleAngle, titleAnchor),
...assembleHeaderProperties(config, facetFieldDef, channel, HEADER_TITLE_PROPERTIES, HEADER_TITLE_PROPERTIES_MAP)
}
};
}
- function defaultHeaderGuideAlign(headerChannel, angle, anchor = 'middle') {
+ function defaultHeaderGuideAlign(headerChannel, angle) {
+ let anchor = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'middle';
+
switch (anchor) {
case 'start':
return {
align: 'left'
};
@@ -15006,17 +13715,19 @@
const {
sort
} = facetFieldDef;
if (isSortField(sort)) {
+ var _sort$order;
+
return {
field: vgField(sort, {
expr: 'datum'
}),
- order: sort.order ?? 'ascending'
+ order: (_sort$order = sort.order) !== null && _sort$order !== void 0 ? _sort$order : 'ascending'
};
- } else if (vegaUtil.isArray(sort)) {
+ } else if (vega.isArray(sort)) {
return {
field: sortArrayIndexField(facetFieldDef, channel, {
expr: 'datum'
}),
order: 'ascending'
@@ -15024,11 +13735,11 @@
} else {
return {
field: vgField(facetFieldDef, {
expr: 'datum'
}),
- order: sort ?? 'ascending'
+ order: sort !== null && sort !== void 0 ? sort : 'ascending'
};
}
}
function assembleLabelTitle(facetFieldDef, channel, config) {
@@ -15087,22 +13798,22 @@
const hasAxes = (axes === null || axes === void 0 ? void 0 : axes.length) > 0;
if (title || hasAxes) {
const sizeChannel = channel === 'row' ? 'height' : 'width';
return {
- name: model.getName(`${channel}_${headerType}`),
+ name: model.getName("".concat(channel, "_").concat(headerType)),
type: 'group',
- role: `${channel}-${headerType}`,
+ role: "".concat(channel, "-").concat(headerType),
...(layoutHeader.facetFieldDef ? {
from: {
- data: model.getName(`${channel}_domain`)
+ data: model.getName("".concat(channel, "_domain"))
},
sort: getSort$1(facetFieldDef, channel)
} : {}),
...(hasAxes && isFacetWithoutRowCol ? {
from: {
- data: model.getName(`facet_domain_${channel}`)
+ data: model.getName("facet_domain_".concat(channel))
}
} : {}),
...(title ? {
title
} : {}),
@@ -15210,11 +13921,11 @@
}
}
return [stepSignal(scaleName, range), {
name,
- update: sizeExpr(scaleName, scaleComponent, `domain('${scaleName}').length`)
+ update: sizeExpr(scaleName, scaleComponent, "domain('".concat(scaleName, "').length"))
}];
}
}
/* istanbul ignore next: Condition should not happen -- only for warning in development. */
@@ -15222,11 +13933,11 @@
throw new Error('layout size is step although width/height is not step.');
} else if (size == 'container') {
const isWidth = name.endsWith('width');
const expr = isWidth ? 'containerSize()[0]' : 'containerSize()[1]';
const defaultValue = getViewConfigContinuousSize(model.config.view, isWidth ? 'width' : 'height');
- const safeExpr = `isFinite(${expr}) ? ${expr} : ${defaultValue}`;
+ const safeExpr = "isFinite(".concat(expr, ") ? ").concat(expr, " : ").concat(defaultValue);
return [{
name,
init: safeExpr,
on: [{
update: safeExpr,
@@ -15240,14 +13951,23 @@
}];
}
}
function stepSignal(scaleName, range) {
- return {
- name: `${scaleName}_step`,
- value: range.step
- };
+ const name = "".concat(scaleName, "_step");
+
+ if (isSignalRef(range.step)) {
+ return {
+ name,
+ update: range.step.signal
+ };
+ } else {
+ return {
+ name,
+ value: range.step
+ };
+ }
}
function sizeExpr(scaleName, scaleComponent, cardinality) {
const type = scaleComponent.get('type');
const padding = scaleComponent.get('padding');
@@ -15255,11 +13975,11 @@
let paddingInner = scaleComponent.get('paddingInner');
paddingInner = type === 'band' ? // only band has real paddingInner
paddingInner !== undefined ? paddingInner : padding : // For point, as calculated in https://github.com/vega/vega-scale/blob/master/src/band.js#L128,
// it's equivalent to have paddingInner = 1 since there is only n-1 steps between n points.
1;
- return `bandspace(${cardinality}, ${signalOrStringValue(paddingInner)}, ${signalOrStringValue(paddingOuter)}) * ${scaleName}_step`;
+ return "bandspace(".concat(cardinality, ", ").concat(signalOrStringValue(paddingInner), ", ").concat(signalOrStringValue(paddingOuter), ") * ").concat(scaleName, "_step");
}
function getSizeTypeFromLayoutSizeType(layoutSizeType) {
return layoutSizeType === 'childWidth' ? 'width' : layoutSizeType === 'childHeight' ? 'height' : layoutSizeType;
}
@@ -15323,17 +14043,21 @@
symbols,
gradient,
labels: labels$1,
entries
};
- function symbols(symbolsSpec, {
- fieldOrDatumDef,
- model,
- channel,
- legendCmpt,
- legendType
- }) {
+ function symbols(symbolsSpec, _ref) {
+ var _legendCmpt$get, _legendCmpt$get2, _legendCmpt$get3, _getMaxValue;
+
+ let {
+ fieldOrDatumDef,
+ model,
+ channel,
+ legendCmpt,
+ legendType
+ } = _ref;
+
if (legendType !== 'symbol') {
return undefined;
}
const {
@@ -15347,14 +14071,14 @@
...color(model, {
filled
})
}; // FIXME: remove this when VgEncodeEntry is compatible with SymbolEncodeEntry
- const symbolOpacity = legendCmpt.get('symbolOpacity') ?? config.legend.symbolOpacity;
- const symbolFillColor = legendCmpt.get('symbolFillColor') ?? config.legend.symbolFillColor;
- const symbolStrokeColor = legendCmpt.get('symbolStrokeColor') ?? config.legend.symbolStrokeColor;
- const opacity = symbolOpacity === undefined ? getMaxValue(encoding.opacity) ?? markDef.opacity : undefined;
+ const symbolOpacity = (_legendCmpt$get = legendCmpt.get('symbolOpacity')) !== null && _legendCmpt$get !== void 0 ? _legendCmpt$get : config.legend.symbolOpacity;
+ const symbolFillColor = (_legendCmpt$get2 = legendCmpt.get('symbolFillColor')) !== null && _legendCmpt$get2 !== void 0 ? _legendCmpt$get2 : config.legend.symbolFillColor;
+ const symbolStrokeColor = (_legendCmpt$get3 = legendCmpt.get('symbolStrokeColor')) !== null && _legendCmpt$get3 !== void 0 ? _legendCmpt$get3 : config.legend.symbolStrokeColor;
+ const opacity = symbolOpacity === undefined ? (_getMaxValue = getMaxValue(encoding.opacity)) !== null && _getMaxValue !== void 0 ? _getMaxValue : markDef.opacity : undefined;
if (out.fill) {
// for fill legend, we don't want any fill in symbol
if (channel === 'fill' || filled && channel === COLOR) {
delete out.fill;
@@ -15362,16 +14086,20 @@
if (out.fill['field']) {
// For others, set fill to some opaque value (or nothing if a color is already set)
if (symbolFillColor) {
delete out.fill;
} else {
- out.fill = signalOrValueRef(config.legend.symbolBaseFillColor ?? 'black');
- out.fillOpacity = signalOrValueRef(opacity ?? 1);
+ var _config$legend$symbol;
+
+ out.fill = signalOrValueRef((_config$legend$symbol = config.legend.symbolBaseFillColor) !== null && _config$legend$symbol !== void 0 ? _config$legend$symbol : 'black');
+ out.fillOpacity = signalOrValueRef(opacity !== null && opacity !== void 0 ? opacity : 1);
}
- } else if (vegaUtil.isArray(out.fill)) {
- const fill = getFirstConditionValue(encoding.fill ?? encoding.color) ?? markDef.fill ?? (filled && markDef.color);
+ } else if (vega.isArray(out.fill)) {
+ var _ref2, _getFirstConditionVal, _encoding$fill;
+ const fill = (_ref2 = (_getFirstConditionVal = getFirstConditionValue((_encoding$fill = encoding.fill) !== null && _encoding$fill !== void 0 ? _encoding$fill : encoding.color)) !== null && _getFirstConditionVal !== void 0 ? _getFirstConditionVal : markDef.fill) !== null && _ref2 !== void 0 ? _ref2 : filled && markDef.color;
+
if (fill) {
out.fill = signalOrValueRef(fill);
}
}
}
@@ -15382,11 +14110,11 @@
delete out.stroke;
} else {
if (out.stroke['field'] || symbolStrokeColor) {
// For others, remove stroke field
delete out.stroke;
- } else if (vegaUtil.isArray(out.stroke)) {
+ } else if (vega.isArray(out.stroke)) {
const stroke = getFirstDefined(getFirstConditionValue(encoding.stroke || encoding.color), markDef.stroke, filled ? markDef.color : undefined);
if (stroke) {
out.stroke = {
value: stroke
@@ -15400,11 +14128,11 @@
const condition = isFieldDef(fieldOrDatumDef) && selectedCondition(model, legendCmpt, fieldOrDatumDef);
if (condition) {
out.opacity = [{
test: condition,
- ...signalOrValueRef(opacity ?? 1)
+ ...signalOrValueRef(opacity !== null && opacity !== void 0 ? opacity : 1)
}, signalOrValueRef(config.legend.unselectedOpacity)];
} else if (opacity) {
out.opacity = signalOrValueRef(opacity);
}
}
@@ -15412,26 +14140,30 @@
out = { ...out,
...symbolsSpec
};
return isEmpty(out) ? undefined : out;
}
- function gradient(gradientSpec, {
- model,
- legendType,
- legendCmpt
- }) {
+ function gradient(gradientSpec, _ref3) {
+ var _legendCmpt$get4;
+
+ let {
+ model,
+ legendType,
+ legendCmpt
+ } = _ref3;
+
if (legendType !== 'gradient') {
return undefined;
}
const {
config,
markDef,
encoding
} = model;
let out = {};
- const gradientOpacity = legendCmpt.get('gradientOpacity') ?? config.legend.gradientOpacity;
+ const gradientOpacity = (_legendCmpt$get4 = legendCmpt.get('gradientOpacity')) !== null && _legendCmpt$get4 !== void 0 ? _legendCmpt$get4 : config.legend.gradientOpacity;
const opacity = gradientOpacity === undefined ? getMaxValue(encoding.opacity) || markDef.opacity : undefined;
if (opacity) {
// only apply opacity if it is neither zero or undefined
out.opacity = signalOrValueRef(opacity);
@@ -15440,16 +14172,17 @@
out = { ...out,
...gradientSpec
};
return isEmpty(out) ? undefined : out;
}
- function labels$1(specifiedlabelsSpec, {
- fieldOrDatumDef,
- model,
- channel,
- legendCmpt
- }) {
+ function labels$1(specifiedlabelsSpec, _ref4) {
+ let {
+ fieldOrDatumDef,
+ model,
+ channel,
+ legendCmpt
+ } = _ref4;
const legend = model.legend(channel) || {};
const config = model.config;
const condition = isFieldDef(fieldOrDatumDef) ? selectedCondition(model, legendCmpt, fieldOrDatumDef) : undefined;
const opacity = condition ? [{
test: condition,
@@ -15476,13 +14209,14 @@
} : {}),
...specifiedlabelsSpec
};
return isEmpty(labelsSpec) ? undefined : labelsSpec;
}
- function entries(entriesSpec, {
- legendCmpt
- }) {
+ function entries(entriesSpec, _ref5) {
+ let {
+ legendCmpt
+ } = _ref5;
const selections = legendCmpt.get('selections');
return selections !== null && selections !== void 0 && selections.length ? { ...entriesSpec,
fill: {
value: 'transparent'
}
@@ -15499,82 +14233,104 @@
});
}
function getConditionValue(channelDef, reducer) {
if (hasConditionalValueDef(channelDef)) {
- return vegaUtil.array(channelDef.condition).reduce(reducer, channelDef.value);
+ return vega.array(channelDef.condition).reduce(reducer, channelDef.value);
} else if (isValueDef(channelDef)) {
return channelDef.value;
}
return undefined;
}
function selectedCondition(model, legendCmpt, fieldDef) {
const selections = legendCmpt.get('selections');
if (!(selections !== null && selections !== void 0 && selections.length)) return undefined;
- const field = vegaUtil.stringValue(fieldDef.field);
+ const field = vega.stringValue(fieldDef.field);
return selections.map(name => {
- const store = vegaUtil.stringValue(varName(name) + STORE);
- return `(!length(data(${store})) || (${name}[${field}] && indexof(${name}[${field}], datum.value) >= 0))`;
+ const store = vega.stringValue(varName(name) + STORE);
+ return "(!length(data(".concat(store, ")) || (").concat(name, "[").concat(field, "] && indexof(").concat(name, "[").concat(field, "], datum.value) >= 0))");
}).join(' || ');
}
const legendRules = {
- direction: ({
- direction
- }) => direction,
- format: ({
- fieldOrDatumDef,
- legend,
- config
- }) => {
+ direction: _ref => {
+ let {
+ direction
+ } = _ref;
+ return direction;
+ },
+ format: _ref2 => {
+ let {
+ fieldOrDatumDef,
+ legend,
+ config
+ } = _ref2;
const {
format,
formatType
} = legend;
return guideFormat(fieldOrDatumDef, fieldOrDatumDef.type, format, formatType, config, false);
},
- formatType: ({
- legend,
- fieldOrDatumDef,
- scaleType
- }) => {
+ formatType: _ref3 => {
+ let {
+ legend,
+ fieldOrDatumDef,
+ scaleType
+ } = _ref3;
const {
formatType
} = legend;
return guideFormatType(formatType, fieldOrDatumDef, scaleType);
},
gradientLength: params => {
+ var _ref4, _legend$gradientLengt;
+
const {
legend,
legendConfig
} = params;
- return legend.gradientLength ?? legendConfig.gradientLength ?? defaultGradientLength(params);
+ return (_ref4 = (_legend$gradientLengt = legend.gradientLength) !== null && _legend$gradientLengt !== void 0 ? _legend$gradientLengt : legendConfig.gradientLength) !== null && _ref4 !== void 0 ? _ref4 : defaultGradientLength(params);
},
- labelOverlap: ({
- legend,
- legendConfig,
- scaleType
- }) => legend.labelOverlap ?? legendConfig.labelOverlap ?? defaultLabelOverlap(scaleType),
- symbolType: ({
- legend,
- markDef,
- channel,
- encoding
- }) => legend.symbolType ?? defaultSymbolType(markDef.type, channel, encoding.shape, markDef.shape),
- title: ({
- fieldOrDatumDef,
- config
- }) => title(fieldOrDatumDef, config, {
- allowDisabling: true
- }),
- type: ({
- legendType,
- scaleType,
- channel
- }) => {
+ labelOverlap: _ref5 => {
+ var _ref6, _legend$labelOverlap;
+
+ let {
+ legend,
+ legendConfig,
+ scaleType
+ } = _ref5;
+ return (_ref6 = (_legend$labelOverlap = legend.labelOverlap) !== null && _legend$labelOverlap !== void 0 ? _legend$labelOverlap : legendConfig.labelOverlap) !== null && _ref6 !== void 0 ? _ref6 : defaultLabelOverlap(scaleType);
+ },
+ symbolType: _ref7 => {
+ var _legend$symbolType;
+
+ let {
+ legend,
+ markDef,
+ channel,
+ encoding
+ } = _ref7;
+ return (_legend$symbolType = legend.symbolType) !== null && _legend$symbolType !== void 0 ? _legend$symbolType : defaultSymbolType(markDef.type, channel, encoding.shape, markDef.shape);
+ },
+ title: _ref8 => {
+ let {
+ fieldOrDatumDef,
+ config
+ } = _ref8;
+ return title(fieldOrDatumDef, config, {
+ allowDisabling: true
+ });
+ },
+ type: _ref9 => {
+ let {
+ legendType,
+ scaleType,
+ channel
+ } = _ref9;
+
if (isColorChannel(channel) && isContinuousToContinuous(scaleType)) {
if (legendType === 'gradient') {
return undefined;
}
} else if (legendType === 'symbol') {
@@ -15582,30 +14338,35 @@
}
return legendType;
},
// depended by other property, let's define upfront
- values: ({
- fieldOrDatumDef,
- legend
- }) => values(legend, fieldOrDatumDef)
+ values: _ref10 => {
+ let {
+ fieldOrDatumDef,
+ legend
+ } = _ref10;
+ return values(legend, fieldOrDatumDef);
+ }
};
function values(legend, fieldOrDatumDef) {
const vals = legend.values;
- if (vegaUtil.isArray(vals)) {
+ if (vega.isArray(vals)) {
return valueArray(fieldOrDatumDef, vals);
} else if (isSignalRef(vals)) {
return vals;
}
return undefined;
}
function defaultSymbolType(mark, channel, shapeChannelDef, markShape) {
if (channel !== 'shape') {
+ var _getFirstConditionVal;
+
// use the value from the shape encoding or the mark config if they exist
- const shape = getFirstConditionValue(shapeChannelDef) ?? markShape;
+ const shape = (_getFirstConditionVal = getFirstConditionValue(shapeChannelDef)) !== null && _getFirstConditionVal !== void 0 ? _getFirstConditionVal : markShape;
if (shape) {
return shape;
}
}
@@ -15636,15 +14397,17 @@
const {
legend
} = params;
return getFirstDefined(legend.type, defaultType$1(params));
}
- function defaultType$1({
- channel,
- timeUnit,
- scaleType
- }) {
+ function defaultType$1(_ref11) {
+ let {
+ channel,
+ timeUnit,
+ scaleType
+ } = _ref11;
+
// Following the logic in https://github.com/vega/vega-parser/blob/master/src/parsers/legend.js
if (isColorChannel(channel)) {
if (contains(['quarter', 'month', 'day'], timeUnit)) {
return 'symbol';
}
@@ -15654,17 +14417,20 @@
}
}
return 'symbol';
}
- function getDirection({
- legendConfig,
- legendType,
- orient,
- legend
- }) {
- return legend.direction ?? legendConfig[legendType ? 'gradientDirection' : 'symbolDirection'] ?? defaultDirection(orient, legendType);
+ function getDirection(_ref12) {
+ var _ref13, _legend$direction;
+
+ let {
+ legendConfig,
+ legendType,
+ orient,
+ legend
+ } = _ref12;
+ return (_ref13 = (_legend$direction = legend.direction) !== null && _legend$direction !== void 0 ? _legend$direction : legendConfig[legendType ? 'gradientDirection' : 'symbolDirection']) !== null && _ref13 !== void 0 ? _ref13 : defaultDirection(orient, legendType);
}
function defaultDirection(orient, legendType) {
switch (orient) {
case 'top':
case 'bottom':
@@ -15682,17 +14448,18 @@
// top-left / ...
// For inner legend, uses compact layout like Tableau
return legendType === 'gradient' ? 'horizontal' : undefined;
}
}
- function defaultGradientLength({
- legendConfig,
- model,
- direction,
- orient,
- scaleType
- }) {
+ function defaultGradientLength(_ref14) {
+ let {
+ legendConfig,
+ model,
+ direction,
+ orient,
+ scaleType
+ } = _ref14;
const {
gradientHorizontalMaxLength,
gradientHorizontalMinLength,
gradientVerticalMaxLength,
gradientVerticalMinLength
@@ -15715,11 +14482,11 @@
}
function gradientLengthSignal(model, sizeType, min, max) {
const sizeSignal = model.getSizeSignalRef(sizeType).signal;
return {
- signal: `clamp(${sizeSignal}, ${min}, ${max})`
+ signal: "clamp(".concat(sizeSignal, ", ").concat(min, ", ").concat(max, ")")
};
}
function defaultLabelOverlap(scaleType) {
if (contains(['quantile', 'threshold', 'log', 'symlog'], scaleType)) {
@@ -15809,11 +14576,11 @@
return value === (legend || {})[property];
}
function parseLegendForChannel(model, channel) {
- var _normalizeTimeUnit, _legend;
+ var _normalizeTimeUnit, _legend$encoding, _legend;
let legend = model.legend(channel);
const {
markDef,
encoding,
@@ -15875,11 +14642,11 @@
legendCmpt.set(property, value, explicit);
}
}
}
- const legendEncoding = ((_legend = legend) === null || _legend === void 0 ? void 0 : _legend.encoding) ?? {};
+ const legendEncoding = (_legend$encoding = (_legend = legend) === null || _legend === void 0 ? void 0 : _legend.encoding) !== null && _legend$encoding !== void 0 ? _legend$encoding : {};
const selections = legendCmpt.get('selections');
const legendEncode = {};
const legendEncodeParams = {
fieldOrDatumDef,
model,
@@ -15887,17 +14654,19 @@
legendCmpt,
legendType
};
for (const part of ['labels', 'legend', 'title', 'symbols', 'gradient', 'entries']) {
- const legendEncodingPart = guideEncodeEntry(legendEncoding[part] ?? {}, model);
+ var _legendEncoding$part;
+
+ const legendEncodingPart = guideEncodeEntry((_legendEncoding$part = legendEncoding[part]) !== null && _legendEncoding$part !== void 0 ? _legendEncoding$part : {}, model);
const value = part in legendEncodeRules ? legendEncodeRules[part](legendEncodingPart, legendEncodeParams) // apply rule
: legendEncodingPart; // no rule -- just default values
if (value !== undefined && !isEmpty(value)) {
legendEncode[part] = { ...(selections !== null && selections !== void 0 && selections.length && isFieldDef(fieldOrDatumDef) ? {
- name: `${varName(fieldOrDatumDef.field)}_legend_${part}`
+ name: "".concat(varName(fieldOrDatumDef.field), "_legend_").concat(part)
} : {}),
...(selections !== null && selections !== void 0 && selections.length ? {
interactive: !!selections
} : {}),
update: value
@@ -16018,15 +14787,15 @@
return st1;
}
function setLegendEncode(legend, part, vgProp, vgRef) {
- var _legend$encode, _legend$encode$part;
+ var _legend$encode, _legend$encode2, _legend$encode2$part, _legend$encode$part, _legend$encode$part$u;
- legend.encode ?? (legend.encode = {});
- (_legend$encode = legend.encode)[part] ?? (_legend$encode[part] = {});
- (_legend$encode$part = legend.encode[part]).update ?? (_legend$encode$part.update = {}); // TODO: remove as any after https://github.com/prisma/nexus-prisma/issues/291
+ (_legend$encode = legend.encode) !== null && _legend$encode !== void 0 ? _legend$encode : legend.encode = {};
+ (_legend$encode2$part = (_legend$encode2 = legend.encode)[part]) !== null && _legend$encode2$part !== void 0 ? _legend$encode2$part : _legend$encode2[part] = {};
+ (_legend$encode$part$u = (_legend$encode$part = legend.encode[part]).update) !== null && _legend$encode$part$u !== void 0 ? _legend$encode$part$u : _legend$encode$part.update = {}; // TODO: remove as any after https://github.com/prisma/nexus-prisma/issues/291
legend.encode[part].update[vgProp] = vgRef;
}
function assembleLegends(model) {
@@ -16053,11 +14822,11 @@
const legends = vals(legendByDomain).flat().map(l => assembleLegend(l, model.config)).filter(l => l !== undefined);
return legends;
}
function assembleLegend(legendCmpt, config) {
- var _legend$encode2;
+ var _legend$encode3;
const {
disable,
labelExpr,
selections,
@@ -16070,11 +14839,11 @@
if (config.aria === false && legend.aria == undefined) {
legend.aria = false;
}
- if ((_legend$encode2 = legend.encode) !== null && _legend$encode2 !== void 0 && _legend$encode2.symbols) {
+ if ((_legend$encode3 = legend.encode) !== null && _legend$encode3 !== void 0 && _legend$encode3.symbols) {
const out = legend.encode.symbols.update;
if (out.fill && out.fill['value'] !== 'transparent' && !out.stroke && !legend.stroke) {
// For non color channel's legend, we need to override symbol stroke config from Vega config if stroke channel is not used.
out.stroke = {
@@ -16094,15 +14863,15 @@
// title schema doesn't include null, ''
delete legend.title;
}
if (labelExpr !== undefined) {
- var _legend$encode3, _legend$encode3$label;
+ var _legend$encode4, _legend$encode4$label;
let expr = labelExpr;
- if ((_legend$encode3 = legend.encode) !== null && _legend$encode3 !== void 0 && (_legend$encode3$label = _legend$encode3.labels) !== null && _legend$encode3$label !== void 0 && _legend$encode3$label.update && isSignalRef(legend.encode.labels.update.text)) {
+ if ((_legend$encode4 = legend.encode) !== null && _legend$encode4 !== void 0 && (_legend$encode4$label = _legend$encode4.labels) !== null && _legend$encode4$label !== void 0 && _legend$encode4$label.update && isSignalRef(legend.encode.labels.update.text)) {
expr = replaceAll(labelExpr, 'datum.label', legend.encode.labels.update.text.signal);
}
setLegendEncode(legend, 'labels', 'text', {
signal: expr
@@ -16150,14 +14919,14 @@
...projection
}];
} else {
// generate projection that uses extent fitting
const size = {
- signal: `[${component.size.map(ref => ref.signal).join(', ')}]`
+ signal: "[".concat(component.size.map(ref => ref.signal).join(', '), "]")
};
const fits = component.data.reduce((sources, data) => {
- const source = isSignalRef(data) ? data.signal : `data('${model.lookupDataSource(data)}')`;
+ const source = isSignalRef(data) ? data.signal : "data('".concat(model.lookupDataSource(data), "')");
if (!contains(sources, source)) {
// build a unique list of sources
sources.push(source);
}
@@ -16171,11 +14940,11 @@
return [{
name,
size,
fit: {
- signal: fits.length > 1 ? `[${fits.join(', ')}]` : fits[0]
+ signal: fits.length > 1 ? "[".concat(fits.join(', '), "]") : fits[0]
},
...projection
}];
}
}
@@ -16214,16 +14983,18 @@
model.component.projection = isUnitModel(model) ? parseUnitProjection(model) : parseNonUnitProjections(model);
}
function parseUnitProjection(model) {
if (model.hasProjection) {
+ var _replaceExprRef;
+
const proj = replaceExprRef(model.specifiedProjection);
const fit = !(proj && (proj.scale != null || proj.translate != null));
const size = fit ? [model.getSizeSignalRef('width'), model.getSizeSignalRef('height')] : undefined;
const data = fit ? gatherFitData(model) : undefined;
- const projComp = new ProjectionComponent(model.projectionName(true), { ...(replaceExprRef(model.config.projection) ?? {}),
- ...(proj ?? {})
+ const projComp = new ProjectionComponent(model.projectionName(true), { ...((_replaceExprRef = replaceExprRef(model.config.projection)) !== null && _replaceExprRef !== void 0 ? _replaceExprRef : {}),
+ ...(proj !== null && proj !== void 0 ? proj : {})
}, size, data);
if (!projComp.get('type')) {
projComp.set('type', 'equalEarth', false);
}
@@ -16241,18 +15012,18 @@
} = model;
for (const posssiblePair of [[LONGITUDE, LATITUDE], [LONGITUDE2, LATITUDE2]]) {
if (getFieldOrDatumDef(encoding[posssiblePair[0]]) || getFieldOrDatumDef(encoding[posssiblePair[1]])) {
data.push({
- signal: model.getName(`geojson_${data.length}`)
+ signal: model.getName("geojson_".concat(data.length))
});
}
}
if (model.channelHasField(SHAPE) && model.typedFieldDef(SHAPE).type === GEOJSON) {
data.push({
- signal: model.getName(`geojson_${data.length}`)
+ signal: model.getName("geojson_".concat(data.length))
});
}
if (data.length === 0) {
// main source is geojson, so we can just use that
@@ -16263,16 +15034,16 @@
}
function mergeIfNoConflict(first, second) {
const allPropertiesShared = every(PROJECTION_PROPERTIES, prop => {
// neither has the property
- if (!vegaUtil.hasOwnProperty(first.explicit, prop) && !vegaUtil.hasOwnProperty(second.explicit, prop)) {
+ if (!vega.hasOwnProperty(first.explicit, prop) && !vega.hasOwnProperty(second.explicit, prop)) {
return true;
} // both have property and an equal value for property
- if (vegaUtil.hasOwnProperty(first.explicit, prop) && vegaUtil.hasOwnProperty(second.explicit, prop) && // some properties might be signals or objects and require hashing for comparison
+ if (vega.hasOwnProperty(first.explicit, prop) && vega.hasOwnProperty(second.explicit, prop) && // some properties might be signals or objects and require hashing for comparison
deepEqual(first.get(prop), second.get(prop))) {
return true;
}
return false;
@@ -16350,12 +15121,14 @@
return undefined;
}
function rangeFormula(model, fieldDef, channel, config) {
if (binRequiresRange(fieldDef, channel)) {
+ var _ref, _model$axis;
+
// read format from axis or legend, if there is no format then use config.numberFormat
- const guide = isUnitModel(model) ? model.axis(channel) ?? model.legend(channel) ?? {} : {};
+ const guide = isUnitModel(model) ? (_ref = (_model$axis = model.axis(channel)) !== null && _model$axis !== void 0 ? _model$axis : model.legend(channel)) !== null && _ref !== void 0 ? _ref : {} : {};
const startField = vgField(fieldDef, {
expr: 'datum'
});
const endField = vgField(fieldDef, {
expr: 'datum',
@@ -16372,24 +15145,26 @@
return {};
}
function binKey(bin, field) {
- return `${binToString(bin)}_${field}`;
+ return "".concat(binToString(bin), "_").concat(field);
}
function getSignalsFromModel(model, key) {
return {
- signal: model.getName(`${key}_bins`),
- extentSignal: model.getName(`${key}_extent`)
+ signal: model.getName("".concat(key, "_bins")),
+ extentSignal: model.getName("".concat(key, "_extent"))
};
}
function getBinSignalName(model, field, bin) {
- const normalizedBin = normalizeBin(bin, undefined) ?? {};
+ var _normalizeBin;
+
+ const normalizedBin = (_normalizeBin = normalizeBin(bin, undefined)) !== null && _normalizeBin !== void 0 ? _normalizeBin : {};
const key = binKey(normalizedBin, field);
- return model.getName(`${key}_bins`);
+ return model.getName("".concat(key, "_bins"));
}
function isBinTransform(t) {
return 'as' in t;
}
@@ -16397,11 +15172,11 @@
function createBinComponent(t, bin, model) {
let as;
let span;
if (isBinTransform(t)) {
- as = vegaUtil.isString(t.as) ? [t.as, `${t.as}_end`] : [t.as[0], t.as[1]];
+ as = vega.isString(t.as) ? [t.as, "".concat(t.as, "_end")] : [t.as[0], t.as[1]];
} else {
as = [vgField(t, {
forAs: true
}), vgField(t, {
binSuffix: 'end',
@@ -16522,11 +15297,11 @@
dependentFields() {
return new Set(vals(this.bins).map(c => c.field));
}
hash() {
- return `Bin ${hash(this.bins)}`;
+ return "Bin ".concat(hash(this.bins));
}
assemble() {
return vals(this.bins).flatMap(bin => {
const transform = [];
@@ -16545,11 +15320,11 @@
} : {
extent: null
}),
...(bin.span ? {
span: {
- signal: `span(${bin.span})`
+ signal: "span(".concat(bin.span, ")")
}
} : {}),
...params
};
@@ -16629,12 +15404,14 @@
// when we merge a measure, we either have to add an aggregation operator or even a new field
const ops = childMeasures[field];
for (const op of keys(ops)) {
if (field in parentMeasures) {
+ var _parentMeasures$field;
+
// add operator to existing measure field
- parentMeasures[field][op] = new Set([...(parentMeasures[field][op] ?? []), ...ops[op]]);
+ parentMeasures[field][op] = new Set([...((_parentMeasures$field = parentMeasures[field][op]) !== null && _parentMeasures$field !== void 0 ? _parentMeasures$field : []), ...ops[op]]);
} else {
parentMeasures[field] = {
[op]: ops[op]
};
}
@@ -16683,37 +15460,43 @@
field
} = fieldDef;
if (aggregate) {
if (aggregate === 'count') {
- var _;
+ var _, _meas$_;
- meas[_ = '*'] ?? (meas[_] = {});
+ (_meas$_ = meas[_ = '*']) !== null && _meas$_ !== void 0 ? _meas$_ : meas[_] = {};
meas['*']['count'] = new Set([vgField(fieldDef, {
forAs: true
})]);
} else {
if (isArgminDef(aggregate) || isArgmaxDef(aggregate)) {
+ var _meas$argField;
+
const op = isArgminDef(aggregate) ? 'argmin' : 'argmax';
const argField = aggregate[op];
- meas[argField] ?? (meas[argField] = {});
+ (_meas$argField = meas[argField]) !== null && _meas$argField !== void 0 ? _meas$argField : meas[argField] = {};
meas[argField][op] = new Set([vgField({
op,
field: argField
}, {
forAs: true
})]);
} else {
- meas[field] ?? (meas[field] = {});
+ var _meas$field;
+
+ (_meas$field = meas[field]) !== null && _meas$field !== void 0 ? _meas$field : meas[field] = {};
meas[field][aggregate] = new Set([vgField(fieldDef, {
forAs: true
})]);
} // For scale channel with domain === 'unaggregated', add min/max so we can use their union as unaggregated domain
if (isScaleChannel(channel) && model.scaleDomain(channel) === 'unaggregated') {
- meas[field] ?? (meas[field] = {});
+ var _meas$field2;
+
+ (_meas$field2 = meas[field]) !== null && _meas$field2 !== void 0 ? _meas$field2 : meas[field] = {};
meas[field]['min'] = new Set([vgField({
field,
aggregate: 'min'
}, {
forAs: true
@@ -16749,26 +15532,30 @@
as
} = s;
if (op) {
if (op === 'count') {
- var _2;
+ var _2, _meas$_2;
- meas[_2 = '*'] ?? (meas[_2] = {});
+ (_meas$_2 = meas[_2 = '*']) !== null && _meas$_2 !== void 0 ? _meas$_2 : meas[_2] = {};
meas['*']['count'] = new Set([as ? as : vgField(s, {
forAs: true
})]);
} else {
- meas[field] ?? (meas[field] = {});
+ var _meas$field3;
+
+ (_meas$field3 = meas[field]) !== null && _meas$field3 !== void 0 ? _meas$field3 : meas[field] = {};
meas[field][op] = new Set([as ? as : vgField(s, {
forAs: true
})]);
}
}
}
- for (const s of t.groupby ?? []) {
+ for (const s of (_t$groupby = t.groupby) !== null && _t$groupby !== void 0 ? _t$groupby : []) {
+ var _t$groupby;
+
dims.add(s);
}
if (dims.size + keys(meas).length === 0) {
return null;
@@ -16779,14 +15566,14 @@
merge(other) {
if (setEqual(this.dimensions, other.dimensions)) {
mergeMeasures(this.measures, other.measures);
return true;
- } else {
- debug('different dimensions, cannot merge');
- return false;
}
+
+ debug('different dimensions, cannot merge');
+ return false;
}
addDimensions(fields) {
fields.forEach(this.dimensions.add, this.dimensions);
}
@@ -16801,25 +15588,25 @@
for (const field of keys(this.measures)) {
for (const op of keys(this.measures[field])) {
const m = this.measures[field][op];
if (m.size === 0) {
- out.add(`${op}_${field}`);
+ out.add("".concat(op, "_").concat(field));
} else {
m.forEach(out.add, out);
}
}
}
return out;
}
hash() {
- return `Aggregate ${hash({
- dimensions: this.dimensions,
- measures: this.measures
- })}`;
+ return "Aggregate ".concat(hash({
+ dimensions: this.dimensions,
+ measures: this.measures
+ }));
}
assemble() {
const ops = [];
const fields = [];
@@ -16877,32 +15664,32 @@
const {
bin,
sort
} = fieldDef;
this[channel] = {
- name: model.getName(`${channel}_domain`),
+ name: model.getName("".concat(channel, "_domain")),
fields: [vgField(fieldDef), ...(isBinning(bin) ? [vgField(fieldDef, {
binSuffix: 'end'
})] : [])],
...(isSortField(sort) ? {
sortField: sort
- } : vegaUtil.isArray(sort) ? {
+ } : vega.isArray(sort) ? {
sortIndexField: sortArrayIndexField(fieldDef, channel)
} : {})
};
}
}
this.childModel = model.child;
}
hash() {
- let out = `Facet`;
+ let out = "Facet";
for (const channel of FACET_CHANNELS) {
if (this[channel]) {
- out += ` ${channel.charAt(0)}:${hash(this[channel])}`;
+ out += " ".concat(channel.charAt(0), ":").concat(hash(this[channel]));
}
}
return out;
}
@@ -16989,20 +15776,20 @@
const as = [];
if (childChannel && childIndependentFieldsWithStep && childIndependentFieldsWithStep[childChannel]) {
if (crossedDataName) {
// If there is a crossed data, calculate max
- fields.push(`distinct_${childIndependentFieldsWithStep[childChannel]}`);
+ fields.push("distinct_".concat(childIndependentFieldsWithStep[childChannel]));
ops.push('max');
} else {
// If there is no crossed data, just calculate distinct
fields.push(childIndependentFieldsWithStep[childChannel]);
ops.push('distinct');
} // Although it is technically a max, just name it distinct so it's easier to refer to it
- as.push(`distinct_${childIndependentFieldsWithStep[childChannel]}`);
+ as.push("distinct_".concat(childIndependentFieldsWithStep[childChannel]));
}
const {
sortField,
sortIndexField
@@ -17025,11 +15812,11 @@
}
return {
name: this[channel].name,
// Use data from the crossed one if it exist
- source: crossedDataName ?? this.data,
+ source: crossedDataName !== null && crossedDataName !== void 0 ? crossedDataName : this.data,
transform: [{
type: 'aggregate',
groupby: this[channel].fields,
...(fields.length ? {
fields,
@@ -17050,12 +15837,14 @@
const data = [];
const hasSharedAxis = {};
for (const headerChannel of HEADER_CHANNELS) {
for (const headerType of HEADER_TYPES) {
- const headers = (layoutHeaders[headerChannel] && layoutHeaders[headerChannel][headerType]) ?? [];
+ var _ref;
+ const headers = (_ref = layoutHeaders[headerChannel] && layoutHeaders[headerChannel][headerType]) !== null && _ref !== void 0 ? _ref : [];
+
for (const header of headers) {
var _header$axes;
if (((_header$axes = header.axes) === null || _header$axes === void 0 ? void 0 : _header$axes.length) > 0) {
hasSharedAxis[headerChannel] = true;
@@ -17063,20 +15852,20 @@
}
}
}
if (hasSharedAxis[headerChannel]) {
- const cardinality = `length(data("${this.facet.name}"))`;
+ const cardinality = "length(data(\"".concat(this.facet.name, "\"))");
const stop = headerChannel === 'row' ? columns ? {
- signal: `ceil(${cardinality} / ${columns})`
+ signal: "ceil(".concat(cardinality, " / ").concat(columns, ")")
} : 1 : columns ? {
- signal: `min(${cardinality}, ${columns})`
+ signal: "min(".concat(cardinality, ", ").concat(columns, ")")
} : {
signal: cardinality
};
data.push({
- name: `${this.facet.name}_${headerChannel}`,
+ name: "".concat(this.facet.name, "_").concat(headerChannel),
transform: [{
type: 'sequence',
start: 0,
stop
}]
@@ -17105,13 +15894,15 @@
row,
facet
} = this;
if (column && row && (childIndependentFieldsWithStep.x || childIndependentFieldsWithStep.y)) {
+ var _childIndependentFiel, _childIndependentFiel2;
+
// Need to create a cross dataset to correctly calculate cardinality
- crossedDataName = `cross_${this.column.name}_${this.row.name}`;
- const fields = [].concat(childIndependentFieldsWithStep.x ?? [], childIndependentFieldsWithStep.y ?? []);
+ crossedDataName = "cross_".concat(this.column.name, "_").concat(this.row.name);
+ const fields = [].concat((_childIndependentFiel = childIndependentFieldsWithStep.x) !== null && _childIndependentFiel !== void 0 ? _childIndependentFiel : [], (_childIndependentFiel2 = childIndependentFieldsWithStep.y) !== null && _childIndependentFiel2 !== void 0 ? _childIndependentFiel2 : []);
const ops = fields.map(() => 'distinct');
data.push({
name: crossedDataName,
source: this.data,
transform: [{
@@ -17145,11 +15936,11 @@
/**
* Remove quotes from a string.
*/
function unquote(pattern) {
- if (pattern[0] === "'" && pattern[pattern.length - 1] === "'" || pattern[0] === '"' && pattern[pattern.length - 1] === '"') {
+ if (pattern.startsWith("'") && pattern.endsWith("'") || pattern.startsWith('"') && pattern.endsWith('"')) {
return pattern.slice(1, -1);
}
return pattern;
}
@@ -17161,25 +15952,25 @@
function parseExpression(field, parse) {
const f = accessPathWithDatum(field);
if (parse === 'number') {
- return `toNumber(${f})`;
+ return "toNumber(".concat(f, ")");
} else if (parse === 'boolean') {
- return `toBoolean(${f})`;
+ return "toBoolean(".concat(f, ")");
} else if (parse === 'string') {
- return `toString(${f})`;
+ return "toString(".concat(f, ")");
} else if (parse === 'date') {
- return `toDate(${f})`;
+ return "toDate(".concat(f, ")");
} else if (parse === 'flatten') {
return f;
} else if (parse.startsWith('date:')) {
const specifier = unquote(parse.slice(5, parse.length));
- return `timeParse(${f},'${specifier}')`;
+ return "timeParse(".concat(f, ",'").concat(specifier, "')");
} else if (parse.startsWith('utc:')) {
const specifier = unquote(parse.slice(4, parse.length));
- return `utcParse(${f},'${specifier}')`;
+ return "utcParse(".concat(f, ",'").concat(specifier, "')");
} else {
warn(unrecognizedParse(parse));
return null;
}
}
@@ -17204,20 +15995,22 @@
} else if (isFieldGTEPredicate(filter)) {
val = signalRefOrValue(filter.gte);
} else if (isFieldRangePredicate(filter)) {
val = filter.range[0];
} else if (isFieldOneOfPredicate(filter)) {
- val = (filter.oneOf ?? filter['in'])[0];
+ var _filter$oneOf;
+
+ val = ((_filter$oneOf = filter.oneOf) !== null && _filter$oneOf !== void 0 ? _filter$oneOf : filter['in'])[0];
} // else -- for filter expression, we can't infer anything
if (val) {
if (isDateTime(val)) {
implicit[filter.field] = 'date';
- } else if (vegaUtil.isNumber(val)) {
+ } else if (vega.isNumber(val)) {
implicit[filter.field] = 'number';
- } else if (vegaUtil.isString(val)) {
+ } else if (vega.isString(val)) {
implicit[filter.field] = 'string';
}
}
if (filter.timeUnit) {
@@ -17323,11 +16116,11 @@
this._parse = parse;
}
hash() {
- return `Parse ${hash(this._parse)}`;
+ return "Parse ".concat(hash(this._parse));
}
/**
* Creates a parse node from a data.format.parse and updates ancestorParse.
*/
@@ -17435,11 +16228,12 @@
dependentFields() {
return new Set(keys(this._parse));
}
- assembleTransforms(onlyNested = false) {
+ assembleTransforms() {
+ let onlyNested = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
return keys(this._parse).filter(field => onlyNested ? accessPathDepth(field) > 1 : true).map(field => {
const expr = parseExpression(field, this._parse[field]);
if (!expr) {
return null;
@@ -17504,11 +16298,11 @@
producedFields() {
return undefined; // there should never be a node before graticule
}
hash() {
- return `Graticule ${hash(this.params)}`;
+ return "Graticule ".concat(hash(this.params));
}
assemble() {
return {
type: 'graticule',
@@ -17531,15 +16325,17 @@
dependentFields() {
return new Set();
}
producedFields() {
- return new Set([this.params.as ?? 'data']);
+ var _this$params$as;
+
+ return new Set([(_this$params$as = this.params.as) !== null && _this$params$as !== void 0 ? _this$params$as : 'data']);
}
hash() {
- return `Hash ${hash(this.params)}`;
+ return "Hash ".concat(hash(this.params));
}
assemble() {
return {
type: 'sequence',
@@ -17549,21 +16345,23 @@
}
class SourceNode extends DataFlowNode {
constructor(data) {
+ var _data;
+
super(null); // source cannot have parent
_defineProperty(this, "_data", void 0);
_defineProperty(this, "_name", void 0);
_defineProperty(this, "_generator", void 0);
- data ?? (data = {
+ (_data = data) !== null && _data !== void 0 ? _data : data = {
name: 'source'
- });
+ };
let format;
if (!isGenerator(data)) {
format = data.format ? { ...omit(data.format, ['parse'])
} : {};
@@ -17677,11 +16475,11 @@
var _modified = /*#__PURE__*/new WeakMap();
class Optimizer {
constructor() {
- _modified.set(this, {
+ _classPrivateFieldInitSpec(this, _modified, {
writable: true,
value: void 0
});
_classPrivateFieldSet(this, _modified, false);
@@ -18191,15 +16989,17 @@
producedFields() {
return new Set(this.transform.joinaggregate.map(this.getDefaultName));
}
getDefaultName(joinAggregateFieldDef) {
- return joinAggregateFieldDef.as ?? vgField(joinAggregateFieldDef);
+ var _joinAggregateFieldDe;
+
+ return (_joinAggregateFieldDe = joinAggregateFieldDef.as) !== null && _joinAggregateFieldDe !== void 0 ? _joinAggregateFieldDe : vgField(joinAggregateFieldDef);
}
hash() {
- return `JoinAggregateTransform ${hash(this.transform)}`;
+ return "JoinAggregateTransform ".concat(hash(this.transform));
}
assemble() {
const fields = [];
const ops = [];
@@ -18238,11 +17038,11 @@
return fields;
}, []);
}
function isValidAsArray(as) {
- return vegaUtil.isArray(as) && as.every(s => vegaUtil.isString(s)) && as.length > 1;
+ return vega.isArray(as) && as.every(s => vega.isString(s)) && as.length > 1;
}
class StackNode extends DataFlowNode {
clone() {
return new StackNode(null, duplicate(this._stack));
@@ -18279,17 +17079,18 @@
};
let normalizedAs;
if (isValidAsArray(as)) {
normalizedAs = as;
- } else if (vegaUtil.isString(as)) {
- normalizedAs = [as, `${as}_end`];
+ } else if (vega.isString(as)) {
+ normalizedAs = [as, "".concat(as, "_end")];
} else {
- normalizedAs = [`${stackTransform.stack}_start`, `${stackTransform.stack}_end`];
+ normalizedAs = ["".concat(stackTransform.stack, "_start"), "".concat(stackTransform.stack, "_end")];
}
return new StackNode(parent, {
+ dimensionFieldDefs: [],
stackField: stack,
groupby,
offset,
sort,
facetby: [],
@@ -18306,27 +17107,24 @@
if (!stackProperties) {
return null;
}
const {
- groupbyChannel,
+ groupbyChannels,
fieldChannel,
offset,
impute
} = stackProperties;
- let dimensionFieldDef;
-
- if (groupbyChannel) {
+ const dimensionFieldDefs = groupbyChannels.map(groupbyChannel => {
const cDef = encoding[groupbyChannel];
- dimensionFieldDef = getFieldDef(cDef); // Fair to cast as groupByChannel is always either x or y
- }
-
+ return getFieldDef(cDef);
+ }).filter(def => !!def);
const stackby = getStackByFields(model);
const orderDef = model.encoding.order;
let sort;
- if (vegaUtil.isArray(orderDef) || isFieldDef(orderDef)) {
+ if (vega.isArray(orderDef) || isFieldDef(orderDef)) {
sort = sortParams(orderDef);
} else {
// default = descending by stackFields
// FIXME is the default here correct for binned fields?
sort = stackby.reduce((s, field) => {
@@ -18338,11 +17136,11 @@
order: []
});
}
return new StackNode(parent, {
- dimensionFieldDef,
+ dimensionFieldDefs,
stackField: model.vgField(fieldChannel),
facetby: [],
stackby,
sort,
offset,
@@ -18380,89 +17178,95 @@
producedFields() {
return new Set(this._stack.as);
}
hash() {
- return `Stack ${hash(this._stack)}`;
+ return "Stack ".concat(hash(this._stack));
}
getGroupbyFields() {
const {
- dimensionFieldDef,
+ dimensionFieldDefs,
impute,
groupby
} = this._stack;
- if (dimensionFieldDef) {
- if (dimensionFieldDef.bin) {
- if (impute) {
- // For binned group by field with impute, we calculate bin_mid
- // as we cannot impute two fields simultaneously
- return [vgField(dimensionFieldDef, {
- binSuffix: 'mid'
+ if (dimensionFieldDefs.length > 0) {
+ return dimensionFieldDefs.map(dimensionFieldDef => {
+ if (dimensionFieldDef.bin) {
+ if (impute) {
+ // For binned group by field with impute, we calculate bin_mid
+ // as we cannot impute two fields simultaneously
+ return [vgField(dimensionFieldDef, {
+ binSuffix: 'mid'
+ })];
+ }
+
+ return [// For binned group by field without impute, we need both bin (start) and bin_end
+ vgField(dimensionFieldDef, {}), vgField(dimensionFieldDef, {
+ binSuffix: 'end'
})];
}
- return [// For binned group by field without impute, we need both bin (start) and bin_end
- vgField(dimensionFieldDef, {}), vgField(dimensionFieldDef, {
- binSuffix: 'end'
- })];
- }
-
- return [vgField(dimensionFieldDef)];
+ return [vgField(dimensionFieldDef)];
+ }).flat();
}
- return groupby ?? [];
+ return groupby !== null && groupby !== void 0 ? groupby : [];
}
assemble() {
const transform = [];
const {
facetby,
- dimensionFieldDef,
+ dimensionFieldDefs,
stackField: field,
stackby,
sort,
offset,
impute,
as
} = this._stack; // Impute
- if (impute && dimensionFieldDef) {
- const {
- bandPosition = 0.5,
- bin
- } = dimensionFieldDef;
+ if (impute) {
+ for (const dimensionFieldDef of dimensionFieldDefs) {
+ const {
+ bandPosition = 0.5,
+ bin
+ } = dimensionFieldDef;
- if (bin) {
- // As we can only impute one field at a time, we need to calculate
- // mid point for a binned field
- transform.push({
- type: 'formula',
- expr: `${bandPosition}*` + vgField(dimensionFieldDef, {
+ if (bin) {
+ // As we can only impute one field at a time, we need to calculate
+ // mid point for a binned field
+ const binStart = vgField(dimensionFieldDef, {
expr: 'datum'
- }) + `+${1 - bandPosition}*` + vgField(dimensionFieldDef, {
+ });
+ const binEnd = vgField(dimensionFieldDef, {
expr: 'datum',
binSuffix: 'end'
+ });
+ transform.push({
+ type: 'formula',
+ expr: "".concat(bandPosition, "*").concat(binStart, "+").concat(1 - bandPosition, "*").concat(binEnd),
+ as: vgField(dimensionFieldDef, {
+ binSuffix: 'mid',
+ forAs: true
+ })
+ });
+ }
+
+ transform.push({
+ type: 'impute',
+ field,
+ groupby: [...stackby, ...facetby],
+ key: vgField(dimensionFieldDef, {
+ binSuffix: 'mid'
}),
- as: vgField(dimensionFieldDef, {
- binSuffix: 'mid',
- forAs: true
- })
+ method: 'value',
+ value: 0
});
}
-
- transform.push({
- type: 'impute',
- field,
- groupby: [...stackby, ...facetby],
- key: vgField(dimensionFieldDef, {
- binSuffix: 'mid'
- }),
- method: 'value',
- value: 0
- });
} // Stack
transform.push({
type: 'stack',
@@ -18494,27 +17298,31 @@
addDimensions(fields) {
this.transform.groupby = unique(this.transform.groupby.concat(fields), d => d);
}
dependentFields() {
+ var _this$transform$group, _this$transform$sort;
+
const out = new Set();
- (this.transform.groupby ?? []).forEach(out.add, out);
- (this.transform.sort ?? []).forEach(m => out.add(m.field));
+ ((_this$transform$group = this.transform.groupby) !== null && _this$transform$group !== void 0 ? _this$transform$group : []).forEach(out.add, out);
+ ((_this$transform$sort = this.transform.sort) !== null && _this$transform$sort !== void 0 ? _this$transform$sort : []).forEach(m => out.add(m.field));
this.transform.window.map(w => w.field).filter(f => f !== undefined).forEach(out.add, out);
return out;
}
producedFields() {
return new Set(this.transform.window.map(this.getDefaultName));
}
getDefaultName(windowFieldDef) {
- return windowFieldDef.as ?? vgField(windowFieldDef);
+ var _windowFieldDef$as;
+
+ return (_windowFieldDef$as = windowFieldDef.as) !== null && _windowFieldDef$as !== void 0 ? _windowFieldDef$as : vgField(windowFieldDef);
}
hash() {
- return `WindowTransform ${hash(this.transform)}`;
+ return "WindowTransform ".concat(hash(this.transform));
}
assemble() {
const fields = [];
const ops = [];
@@ -18547,12 +17355,14 @@
const sortFields = [];
const sortOrder = [];
if (this.transform.sort !== undefined) {
for (const sortField of this.transform.sort) {
+ var _sortField$order;
+
sortFields.push(sortField.field);
- sortOrder.push(sortField.order ?? 'ascending');
+ sortOrder.push((_sortField$order = sortField.order) !== null && _sortField$order !== void 0 ? _sortField$order : 'ascending');
}
}
const sort = {
field: sortFields,
@@ -18754,11 +17564,11 @@
checkLinks(data.sources);
if (Math.max(firstPassCounter, secondPassCounter) === MAX_OPTIMIZATION_RUNS) {
- warn(`Maximum optimization runs(${MAX_OPTIMIZATION_RUNS}) reached.`);
+ warn("Maximum optimization runs(".concat(MAX_OPTIMIZATION_RUNS, ") reached."));
}
}
/**
* A class that behaves like a SignalRef but lazily generates the signal.
@@ -18926,11 +17736,11 @@
const data = valueExpr(v, {
timeUnit,
type
});
return {
- signal: `{data: ${data}}`
+ signal: "{data: ".concat(data, "}")
};
});
}
function convertDomainIfItIsDateTime(domain, type, timeUnit) {
@@ -19030,11 +17840,11 @@
// Use range if we added it and the scale does not support computing a range as a signal.
field: model.vgField(channel, binRequiresRange(fieldDef, channel) ? {
binSuffix: 'range'
} : {}),
// we have to use a sort object if sort = true to make the sort correct by bin start
- sort: sort === true || !vegaUtil.isObject(sort) ? {
+ sort: sort === true || !vega.isObject(sort) ? {
field: model.vgField(channel, {}),
op: 'min' // min or max doesn't matter since we sort by the start of the bin range
} : sort
}]);
@@ -19046,11 +17856,11 @@
if (isBinning(bin)) {
const binSignal = getBinSignalName(model, fieldDef.field, bin);
return makeImplicit([new SignalRefWrapper(() => {
const signal = model.getSignalName(binSignal);
- return `[${signal}.start, ${signal}.stop]`;
+ return "[".concat(signal, ".start, ").concat(signal, ".stop]");
})]);
} else {
return makeImplicit([{
data: model.requestDataName(DataSourceType.Main),
field: model.vgField(channel, {})
@@ -19072,11 +17882,11 @@
return makeImplicit([{
// If sort by aggregation of a specified sort field, we need to use RAW table,
// so we can aggregate values for the scale independently from the main aggregation.
data: isBoolean(sort) ? model.requestDataName(DataSourceType.Main) : model.requestDataName(DataSourceType.Raw),
field: model.vgField(channel),
- sort: sort
+ sort
}]);
} else {
return makeImplicit([{
data: model.requestDataName(DataSourceType.Main),
field: model.vgField(channel)
@@ -19090,11 +17900,11 @@
field,
order
} = sort;
return {
// Apply default op
- op: op ?? (isStackedMeasure ? 'sum' : DEFAULT_SORT_OP),
+ op: op !== null && op !== void 0 ? op : isStackedMeasure ? 'sum' : DEFAULT_SORT_OP,
// flatten nested fields
...(field ? {
field: replacePathInField(field)
} : {}),
...(order ? {
@@ -19114,11 +17924,11 @@
if (domain || extent) {
// As scale parsing occurs before selection parsing, we cannot set
// domainRaw directly. So instead, we store the selectionExtent on
// the scale component, and then add domainRaw during scale assembly.
- scale.set('selectionExtent', domain ?? extent, true);
+ scale.set('selectionExtent', domain !== null && domain !== void 0 ? domain : extent, true);
}
}
function domainSort(model, channel, scaleType) {
if (!hasDiscreteDomain(scaleType)) {
@@ -19138,14 +17948,14 @@
}
const {
stack
} = model;
- const stackDimensions = stack ? [...(stack.groupbyField ? [stack.groupbyField] : []), ...stack.stackBy.map(s => s.fieldDef.field)] : undefined; // Sorted based on an aggregate calculation over a specified sort field (only for ordinal scale)
+ const stackDimensions = stack ? new Set([...stack.groupbyFields, ...stack.stackBy.map(s => s.fieldDef.field)]) : undefined; // Sorted based on an aggregate calculation over a specified sort field (only for ordinal scale)
if (isSortField(sort)) {
- const isStackedMeasure = stack && !contains(stackDimensions, sort.field);
+ const isStackedMeasure = stack && !stackDimensions.has(sort.field);
return normalizeSortField(sort, isStackedMeasure);
} else if (isSortByEncoding(sort)) {
const {
encoding,
order
@@ -19153,11 +17963,11 @@
const fieldDefToSortBy = model.fieldDef(encoding);
const {
aggregate,
field
} = fieldDefToSortBy;
- const isStackedMeasure = stack && !contains(stackDimensions, field);
+ const isStackedMeasure = stack && !stackDimensions.has(field);
if (isArgminDef(aggregate) || isArgmaxDef(aggregate)) {
return normalizeSortField({
field: vgField(fieldDefToSortBy),
order
@@ -19204,11 +18014,11 @@
valid: false,
reason: unaggregateDomainHasNoEffectForRawField(fieldDef)
};
}
- if (vegaUtil.isString(aggregate) && !SHARED_DOMAIN_OP_INDEX[aggregate]) {
+ if (vega.isString(aggregate) && !SHARED_DOMAIN_OPS.has(aggregate)) {
return {
valid: false,
reason: unaggregateDomainWithNonSharedDomainOp(aggregate)
};
}
@@ -19292,11 +18102,11 @@
if (sorts.length > 1) {
warn(MORE_THAN_ONE_SORT);
sort = true;
} else {
// Simplify domain sort by removing field and op when the field is the same as the domain field.
- if (vegaUtil.isObject(sort) && 'field' in sort) {
+ if (vega.isObject(sort) && 'field' in sort) {
const sortField = sort.field;
if (domain.field === sortField) {
sort = sort.order ? {
order: sort.order
@@ -19313,11 +18123,11 @@
return domain;
} // only keep sort properties that work with unioned domains
const unionDomainSorts = unique(sorts.map(s => {
- if (isBoolean(s) || !('op' in s) || vegaUtil.isString(s.op) && s.op in MULTIDOMAIN_SORT_OP_INDEX) {
+ if (isBoolean(s) || !('op' in s) || vega.isString(s.op) && s.op in MULTIDOMAIN_SORT_OP_INDEX) {
return s;
}
warn(domainSortDropped(s));
return true;
@@ -19362,17 +18172,17 @@
* Return a field if a scale uses a single field.
* Return `undefined` otherwise.
*/
function getFieldFromDomain(domain) {
- if (isDataRefDomain(domain) && vegaUtil.isString(domain.field)) {
+ if (isDataRefDomain(domain) && vega.isString(domain.field)) {
return domain.field;
} else if (isDataRefUnionedDomain(domain)) {
let field;
for (const nonUnionDomain of domain.fields) {
- if (isDataRefDomain(nonUnionDomain) && vegaUtil.isString(nonUnionDomain.field)) {
+ if (isDataRefDomain(nonUnionDomain) && vega.isString(nonUnionDomain.field)) {
if (!field) {
field = nonUnionDomain.field;
} else if (field !== nonUnionDomain.field) {
warn(FACETED_INDEPENDENT_DIFFERENT_SOURCES);
return field;
@@ -19383,11 +18193,11 @@
warn(FACETED_INDEPENDENT_SAME_FIELDS_DIFFERENT_SOURCES);
return field;
} else if (isFieldRefUnionDomain(domain)) {
warn(FACETED_INDEPENDENT_SAME_SOURCE);
const field = domain.fields[0];
- return vegaUtil.isString(field) ? field : undefined;
+ return vega.isString(field) ? field : undefined;
}
return undefined;
}
function assembleDomain(model, channel) {
@@ -19463,15 +18273,15 @@
if (isXorY(channel)) {
if (isVgRangeStep(scaleRange)) {
// For width/height step, use a signal created in layout assemble instead of a constant step.
return {
step: {
- signal: `${scaleName}_step`
+ signal: "".concat(scaleName, "_step")
}
};
}
- } else if (vegaUtil.isObject(scaleRange) && isDataRefDomain(scaleRange)) {
+ } else if (vega.isObject(scaleRange) && isDataRefDomain(scaleRange)) {
return { ...scaleRange,
data: model.lookupDataSource(scaleRange.data)
};
}
@@ -19503,21 +18313,16 @@
domainDefinitelyIncludesZero() {
if (this.get('zero') !== false) {
return true;
}
- return some(this.get('domains'), d => vegaUtil.isArray(d) && d.length === 2 && d[0] <= 0 && d[1] >= 0);
+ return some(this.get('domains'), d => vega.isArray(d) && d.length === 2 && d[0] <= 0 && d[1] >= 0);
}
}
const RANGE_PROPERTIES = ['range', 'scheme'];
-
- function getSizeChannel(channel) {
- return channel === 'x' ? 'width' : channel === 'y' ? 'height' : undefined;
- }
-
function parseUnitScaleRange(model) {
const localScaleComponents = model.component.scales; // use SCALE_CHANNELS instead of scales[channel] to ensure that x, y come first!
for (const channel of SCALE_CHANNELS) {
const localScaleCmpt = localScaleComponents[channel];
@@ -19540,23 +18345,23 @@
field
} = fieldDef;
const sizeType = getSizeChannel(channel);
const sizeSignal = model.getName(sizeType);
- if (vegaUtil.isObject(bin) && bin.binned && bin.step !== undefined) {
+ if (vega.isObject(bin) && bin.binned && bin.step !== undefined) {
return new SignalRefWrapper(() => {
const scaleName = model.scaleName(channel);
- const binCount = `(domain("${scaleName}")[1] - domain("${scaleName}")[0]) / ${bin.step}`;
- return `${model.getSignalName(sizeSignal)} / (${binCount})`;
+ const binCount = "(domain(\"".concat(scaleName, "\")[1] - domain(\"").concat(scaleName, "\")[0]) / ").concat(bin.step);
+ return "".concat(model.getSignalName(sizeSignal), " / (").concat(binCount, ")");
});
} else if (isBinning(bin)) {
const binSignal = getBinSignalName(model, field, bin); // TODO: extract this to be range step signal
return new SignalRefWrapper(() => {
const updatedName = model.getSignalName(binSignal);
- const binCount = `(${updatedName}.stop - ${updatedName}.start) / ${updatedName}.step`;
- return `${model.getSignalName(sizeSignal)} / (${binCount})`;
+ const binCount = "(".concat(updatedName, ".stop - ").concat(updatedName, ".start) / ").concat(updatedName, ".step");
+ return "".concat(model.getSignalName(sizeSignal), " / (").concat(binCount, ")");
});
}
}
return undefined;
@@ -19589,11 +18394,11 @@
switch (property) {
case 'range':
{
const range = specifiedScale.range;
- if (vegaUtil.isArray(range)) {
+ if (vega.isArray(range)) {
if (isXorY(channel)) {
return makeExplicit(range.map(v => {
if (v === 'width' || v === 'height') {
// get signal for width/height
// Just like default range logic below, we use SignalRefWrapper to account for potential merges and renames.
@@ -19603,11 +18408,11 @@
}
return v;
}));
}
- } else if (vegaUtil.isObject(range)) {
+ } else if (vega.isObject(range)) {
return makeExplicit({
data: model.requestDataName(DataSourceType.Main),
field: range.field,
sort: {
op: 'min',
@@ -19624,34 +18429,50 @@
}
}
}
}
- if (channel === X || channel === Y) {
- const sizeChannel = channel === X ? 'width' : 'height';
- const sizeValue = size[sizeChannel];
+ const sizeChannel = channel === X || channel === 'xOffset' ? 'width' : 'height';
+ const sizeValue = size[sizeChannel];
- if (isStep(sizeValue)) {
+ if (isStep(sizeValue)) {
+ if (isXorY(channel)) {
if (hasDiscreteDomain(scaleType)) {
- return makeExplicit({
- step: sizeValue.step
- });
+ const step = getPositionStep(sizeValue, model, channel); // Need to be explicit so layer with step wins over layer without step
+
+ if (step) {
+ return makeExplicit({
+ step
+ });
+ }
} else {
warn(stepDropped(sizeChannel));
}
+ } else if (isXorYOffset(channel)) {
+ const positionChannel = channel === XOFFSET ? 'x' : 'y';
+ const positionScaleCmpt = model.getScaleComponent(positionChannel);
+ const positionScaleType = positionScaleCmpt.get('type');
+
+ if (positionScaleType === 'band') {
+ const step = getOffsetStep(sizeValue, scaleType);
+
+ if (step) {
+ return makeExplicit(step);
+ }
+ }
}
}
const {
rangeMin,
rangeMax
} = specifiedScale;
const d = defaultRange(channel, model);
if ((rangeMin !== undefined || rangeMax !== undefined) && // it's ok to check just rangeMin's compatibility since rangeMin/rangeMax are the same
- scaleTypeSupportProperty(scaleType, 'rangeMin') && vegaUtil.isArray(d) && d.length === 2) {
- return makeExplicit([rangeMin ?? d[0], rangeMax ?? d[1]]);
+ scaleTypeSupportProperty(scaleType, 'rangeMin') && vega.isArray(d) && d.length === 2) {
+ return makeExplicit([rangeMin !== null && rangeMin !== void 0 ? rangeMin : d[0], rangeMax !== null && rangeMax !== void 0 ? rangeMax : d[1]]);
}
return makeImplicit(d);
}
@@ -19662,11 +18483,11 @@
...omit(scheme, ['name'])
};
}
return {
- scheme: scheme
+ scheme
};
}
function defaultRange(channel, model) {
const {
@@ -19690,22 +18511,17 @@
case X:
case Y:
{
// If there is no explicit width/height for discrete x/y scales
if (contains(['point', 'band'], scaleType)) {
- if (channel === X && !size.width) {
- const w = getViewConfigDiscreteSize(config.view, 'width');
+ const positionSize = getDiscretePositionSize(channel, size, config.view);
- if (isStep(w)) {
- return w;
- }
- } else if (channel === Y && !size.height) {
- const h = getViewConfigDiscreteSize(config.view, 'height');
-
- if (isStep(h)) {
- return h;
- }
+ if (isStep(positionSize)) {
+ const step = getPositionStep(positionSize, model, channel);
+ return {
+ step
+ };
}
} // If step is null, use zero to width or height.
// Note that we use SignalRefWrapper to account for potential merges and renames.
@@ -19718,10 +18534,14 @@
} else {
return [0, SignalRefWrapper.fromName(getSignalName, sizeSignal)];
}
}
+ case XOFFSET:
+ case YOFFSET:
+ return getOffsetRange(channel, model, scaleType);
+
case SIZE:
{
// TODO: support custom rangeMin, rangeMax
const zero = model.component.scales[channel].get('zero');
const rangeMin = sizeRangeMin(mark, zero, config);
@@ -19746,11 +18566,11 @@
{
// max radius = half od min(width,height)
return [0, new SignalRefWrapper(() => {
const w = model.getSignalName('width');
const h = model.getSignalName('height');
- return `min(${w},${h})/2`;
+ return "min(".concat(w, ",").concat(h, ")/2");
})];
}
case STROKEWIDTH:
// TODO: support custom rangeMin, rangeMax
@@ -19781,26 +18601,112 @@
case FILLOPACITY:
case STROKEOPACITY:
// TODO: support custom rangeMin, rangeMax
return [config.scale.minOpacity, config.scale.maxOpacity];
}
- /* istanbul ignore next: should never reach here */
+ }
+ function getPositionStep(step, model, channel) {
+ const {
+ encoding
+ } = model;
+ const mergedScaleCmpt = model.getScaleComponent(channel);
+ const offsetChannel = getOffsetScaleChannel(channel);
+ const offsetDef = encoding[offsetChannel];
+ const stepFor = getStepFor({
+ step,
+ offsetIsDiscrete: isFieldOrDatumDef(offsetDef) && isDiscrete$1(offsetDef.type)
+ });
- throw new Error(`Scale range undefined for channel ${channel}`);
+ if (stepFor === 'offset' && channelHasFieldOrDatum(encoding, offsetChannel)) {
+ var _mergedScaleCmpt$get;
+
+ const offsetScaleCmpt = model.getScaleComponent(offsetChannel);
+ const offsetScaleName = model.scaleName(offsetChannel);
+ let stepCount = "domain('".concat(offsetScaleName, "').length");
+
+ if (offsetScaleCmpt.get('type') === 'band') {
+ var _ref, _offsetScaleCmpt$get, _ref2, _offsetScaleCmpt$get2;
+
+ const offsetPaddingInner = (_ref = (_offsetScaleCmpt$get = offsetScaleCmpt.get('paddingInner')) !== null && _offsetScaleCmpt$get !== void 0 ? _offsetScaleCmpt$get : offsetScaleCmpt.get('padding')) !== null && _ref !== void 0 ? _ref : 0;
+ const offsetPaddingOuter = (_ref2 = (_offsetScaleCmpt$get2 = offsetScaleCmpt.get('paddingOuter')) !== null && _offsetScaleCmpt$get2 !== void 0 ? _offsetScaleCmpt$get2 : offsetScaleCmpt.get('padding')) !== null && _ref2 !== void 0 ? _ref2 : 0;
+ stepCount = "bandspace(".concat(stepCount, ", ").concat(offsetPaddingInner, ", ").concat(offsetPaddingOuter, ")");
+ }
+
+ const paddingInner = (_mergedScaleCmpt$get = mergedScaleCmpt.get('paddingInner')) !== null && _mergedScaleCmpt$get !== void 0 ? _mergedScaleCmpt$get : mergedScaleCmpt.get('padding');
+ return {
+ signal: "".concat(step.step, " * ").concat(stepCount, " / (1-").concat(exprFromSignalRefOrValue(paddingInner), ")")
+ };
+ } else {
+ return step.step;
+ }
}
+ function getOffsetStep(step, offsetScaleType) {
+ const stepFor = getStepFor({
+ step,
+ offsetIsDiscrete: hasDiscreteDomain(offsetScaleType)
+ });
+
+ if (stepFor === 'offset') {
+ return {
+ step: step.step
+ };
+ }
+
+ return undefined;
+ }
+
+ function getOffsetRange(channel, model, offsetScaleType) {
+ const positionChannel = channel === XOFFSET ? 'x' : 'y';
+ const positionScaleCmpt = model.getScaleComponent(positionChannel);
+ const positionScaleType = positionScaleCmpt.get('type');
+ const positionScaleName = model.scaleName(positionChannel);
+
+ if (positionScaleType === 'band') {
+ const size = getDiscretePositionSize(positionChannel, model.size, model.config.view);
+
+ if (isStep(size)) {
+ // step is for offset
+ const step = getOffsetStep(size, offsetScaleType);
+
+ if (step) {
+ return step;
+ }
+ } // otherwise use the position
+
+
+ return [0, {
+ signal: "bandwidth('".concat(positionScaleName, "')")
+ }];
+ } else {
+ // continuous scale
+ return never("Cannot use ".concat(channel, " scale if ").concat(positionChannel, " scale is not discrete."));
+ }
+ }
+
+ function getDiscretePositionSize(channel, size, viewConfig) {
+ const sizeChannel = channel === X ? 'width' : 'height';
+ const sizeValue = size[sizeChannel];
+
+ if (sizeValue) {
+ return sizeValue;
+ }
+
+ return getViewConfigDiscreteSize(viewConfig, sizeChannel);
+ }
+
function defaultContinuousToDiscreteCount(scaleType, config, domain, channel) {
switch (scaleType) {
case 'quantile':
return config.scale.quantileCount;
case 'quantize':
return config.scale.quantizeCount;
case 'threshold':
- if (domain !== undefined && vegaUtil.isArray(domain)) {
+ if (domain !== undefined && vega.isArray(domain)) {
return domain.length + 1;
} else {
warn(domainRequiredForThresholdScale(channel)); // default threshold boundaries for threshold scale since domain has cardinality of 2
return 3;
@@ -19819,12 +18725,12 @@
function interpolateRange(rangeMin, rangeMax, cardinality) {
// always return a signal since it's better to compute the sequence in Vega later
const f = () => {
const rMax = signalOrStringValue(rangeMax);
const rMin = signalOrStringValue(rangeMin);
- const step = `(${rMax} - ${rMin}) / (${cardinality} - 1)`;
- return `sequence(${rMin}, ${rMax} + ${step}, ${step})`;
+ const step = "(".concat(rMax, " - ").concat(rMin, ") / (").concat(cardinality, " - 1)");
+ return "sequence(".concat(rMin, ", ").concat(rMax, " + ").concat(step, ", ").concat(step, ")");
};
if (isSignalRef(rangeMax)) {
return new SignalRefWrapper(f);
} else {
@@ -19836,11 +18742,11 @@
function sizeRangeMin(mark, zero, config) {
if (zero) {
if (isSignalRef(zero)) {
return {
- signal: `${zero.signal} ? 0 : ${sizeRangeMin(mark, false, config)}`
+ signal: "".concat(zero.signal, " ? 0 : ").concat(sizeRangeMin(mark, false, config))
};
} else {
return 0;
}
}
@@ -19886,14 +18792,14 @@
return config.scale.maxBandSize;
}
const min = minXYStep(size, xyStepSignals, config.view);
- if (vegaUtil.isNumber(min)) {
+ if (vega.isNumber(min)) {
return min - 1;
} else {
- return new SignalRefWrapper(() => `${min.signal} - 1`);
+ return new SignalRefWrapper(() => "".concat(min.signal, " - 1"));
}
}
case 'line':
case 'trail':
@@ -19911,14 +18817,14 @@
return config.scale.maxSize;
}
const pointStep = minXYStep(size, xyStepSignals, config.view);
- if (vegaUtil.isNumber(pointStep)) {
+ if (vega.isNumber(pointStep)) {
return Math.pow(MAX_SIZE_RANGE_STEP_RATIO * pointStep, 2);
} else {
- return new SignalRefWrapper(() => `pow(${MAX_SIZE_RANGE_STEP_RATIO} * ${pointStep.signal}, 2)`);
+ return new SignalRefWrapper(() => "pow(".concat(MAX_SIZE_RANGE_STEP_RATIO, " * ").concat(pointStep.signal, ", 2)"));
}
}
}
/* istanbul ignore next: should never reach here */
// sizeRangeMax not implemented for the mark
@@ -19936,11 +18842,11 @@
const heightStep = isStep(size.height) ? size.height.step : getViewConfigDiscreteStep(viewConfig, 'height');
if (xyStepSignals.x || xyStepSignals.y) {
return new SignalRefWrapper(() => {
const exprs = [xyStepSignals.x ? xyStepSignals.x.signal : widthStep, xyStepSignals.y ? xyStepSignals.y.signal : heightStep];
- return `min(${exprs.join(', ')})`;
+ return "min(".concat(exprs.join(', '), ")");
});
}
return Math.min(widthStep, heightStep);
}
@@ -20016,12 +18922,15 @@
fieldOrDatumDef,
scaleType,
scalePadding,
scalePaddingInner,
domain: specifiedScale.domain,
+ domainMin: specifiedScale.domainMin,
+ domainMax: specifiedScale.domainMax,
markDef,
- config
+ config,
+ hasNestedOffsetScale: channelHasNestedOffsetScale(encoding, channel)
}) : config.scale[property];
if (value !== undefined) {
localScaleCmpt.set(property, value, false);
}
@@ -20029,61 +18938,87 @@
}
}
}
const scaleRules = {
- bins: ({
- model,
- fieldOrDatumDef
- }) => isFieldDef(fieldOrDatumDef) ? bins(model, fieldOrDatumDef) : undefined,
- interpolate: ({
- channel,
- fieldOrDatumDef
- }) => interpolate(channel, fieldOrDatumDef.type),
- nice: ({
- scaleType,
- channel,
- domain,
- fieldOrDatumDef
- }) => nice(scaleType, channel, domain, fieldOrDatumDef),
- padding: ({
- channel,
- scaleType,
- fieldOrDatumDef,
- markDef,
- config
- }) => padding(channel, scaleType, config.scale, fieldOrDatumDef, markDef, config.bar),
- paddingInner: ({
- scalePadding,
- channel,
- markDef,
- config
- }) => paddingInner(scalePadding, channel, markDef.type, config.scale),
- paddingOuter: ({
- scalePadding,
- channel,
- scaleType,
- markDef,
- scalePaddingInner,
- config
- }) => paddingOuter(scalePadding, channel, scaleType, markDef.type, scalePaddingInner, config.scale),
- reverse: ({
- fieldOrDatumDef,
- scaleType,
- channel,
- config
- }) => {
+ bins: _ref => {
+ let {
+ model,
+ fieldOrDatumDef
+ } = _ref;
+ return isFieldDef(fieldOrDatumDef) ? bins(model, fieldOrDatumDef) : undefined;
+ },
+ interpolate: _ref2 => {
+ let {
+ channel,
+ fieldOrDatumDef
+ } = _ref2;
+ return interpolate(channel, fieldOrDatumDef.type);
+ },
+ nice: _ref3 => {
+ let {
+ scaleType,
+ channel,
+ domain,
+ domainMin,
+ domainMax,
+ fieldOrDatumDef
+ } = _ref3;
+ return nice(scaleType, channel, domain, domainMin, domainMax, fieldOrDatumDef);
+ },
+ padding: _ref4 => {
+ let {
+ channel,
+ scaleType,
+ fieldOrDatumDef,
+ markDef,
+ config
+ } = _ref4;
+ return padding(channel, scaleType, config.scale, fieldOrDatumDef, markDef, config.bar);
+ },
+ paddingInner: _ref5 => {
+ let {
+ scalePadding,
+ channel,
+ markDef,
+ scaleType,
+ config,
+ hasNestedOffsetScale
+ } = _ref5;
+ return paddingInner(scalePadding, channel, markDef.type, scaleType, config.scale, hasNestedOffsetScale);
+ },
+ paddingOuter: _ref6 => {
+ let {
+ scalePadding,
+ channel,
+ scaleType,
+ scalePaddingInner,
+ config,
+ hasNestedOffsetScale
+ } = _ref6;
+ return paddingOuter(scalePadding, channel, scaleType, scalePaddingInner, config.scale, hasNestedOffsetScale);
+ },
+ reverse: _ref7 => {
+ let {
+ fieldOrDatumDef,
+ scaleType,
+ channel,
+ config
+ } = _ref7;
const sort = isFieldDef(fieldOrDatumDef) ? fieldOrDatumDef.sort : undefined;
return reverse(scaleType, sort, channel, config.scale);
},
- zero: ({
- channel,
- fieldOrDatumDef,
- domain,
- markDef,
- scaleType
- }) => zero(channel, fieldOrDatumDef, domain, markDef, scaleType)
+ zero: _ref8 => {
+ let {
+ channel,
+ fieldOrDatumDef,
+ domain,
+ markDef,
+ scaleType
+ } = _ref8;
+ return zero(channel, fieldOrDatumDef, domain, markDef, scaleType);
+ }
}; // This method is here rather than in range.ts to avoid circular dependency.
function parseScaleRange(model) {
if (isUnitModel(model)) {
parseUnitScaleRange(model);
@@ -20152,21 +19087,21 @@
return 'hcl';
}
return undefined;
}
- function nice(scaleType, channel, specifiedDomain, fieldOrDatumDef) {
+ function nice(scaleType, channel, specifiedDomain, domainMin, domainMax, fieldOrDatumDef) {
var _getFieldDef;
- if ((_getFieldDef = getFieldDef(fieldOrDatumDef)) !== null && _getFieldDef !== void 0 && _getFieldDef.bin || vegaUtil.isArray(specifiedDomain) || contains([ScaleType.TIME, ScaleType.UTC], scaleType)) {
+ if ((_getFieldDef = getFieldDef(fieldOrDatumDef)) !== null && _getFieldDef !== void 0 && _getFieldDef.bin || vega.isArray(specifiedDomain) || domainMax != null || domainMin != null || contains([ScaleType.TIME, ScaleType.UTC], scaleType)) {
return undefined;
}
- return channel in POSITION_SCALE_CHANNEL_INDEX ? true : undefined;
+ return isXorY(channel) ? true : undefined;
}
function padding(channel, scaleType, scaleConfig, fieldOrDatumDef, markDef, barConfig) {
- if (channel in POSITION_SCALE_CHANNEL_INDEX) {
+ if (isXorY(channel)) {
if (isContinuousToContinuous(scaleType)) {
if (scaleConfig.continuousPadding !== undefined) {
return scaleConfig.continuousPadding;
}
@@ -20187,62 +19122,88 @@
}
}
return undefined;
}
- function paddingInner(paddingValue, channel, mark, scaleConfig) {
+ function paddingInner(paddingValue, channel, mark, scaleType, scaleConfig) {
+ let hasNestedOffsetScale = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
+
if (paddingValue !== undefined) {
// If user has already manually specified "padding", no need to add default paddingInner.
return undefined;
}
- if (channel in POSITION_SCALE_CHANNEL_INDEX) {
+ if (isXorY(channel)) {
// Padding is only set for X and Y by default.
// Basically it doesn't make sense to add padding for color and size.
// paddingOuter would only be called if it's a band scale, just return the default for bandScale.
const {
bandPaddingInner,
barBandPaddingInner,
- rectBandPaddingInner
+ rectBandPaddingInner,
+ bandWithNestedOffsetPaddingInner
} = scaleConfig;
+
+ if (hasNestedOffsetScale) {
+ return bandWithNestedOffsetPaddingInner;
+ }
+
return getFirstDefined(bandPaddingInner, mark === 'bar' ? barBandPaddingInner : rectBandPaddingInner);
+ } else if (isXorYOffset(channel)) {
+ if (scaleType === ScaleType.BAND) {
+ return scaleConfig.offsetBandPaddingInner;
+ }
}
return undefined;
}
- function paddingOuter(paddingValue, channel, scaleType, mark, paddingInnerValue, scaleConfig) {
+ function paddingOuter(paddingValue, channel, scaleType, paddingInnerValue, scaleConfig) {
+ let hasNestedOffsetScale = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
+
if (paddingValue !== undefined) {
// If user has already manually specified "padding", no need to add default paddingOuter.
return undefined;
}
- if (channel in POSITION_SCALE_CHANNEL_INDEX) {
- // Padding is only set for X and Y by default.
+ if (isXorY(channel)) {
+ const {
+ bandPaddingOuter,
+ bandWithNestedOffsetPaddingOuter
+ } = scaleConfig;
+
+ if (hasNestedOffsetScale) {
+ return bandWithNestedOffsetPaddingOuter;
+ } // Padding is only set for X and Y by default.
// Basically it doesn't make sense to add padding for color and size.
+
+
if (scaleType === ScaleType.BAND) {
- const {
- bandPaddingOuter
- } = scaleConfig;
return getFirstDefined(bandPaddingOuter,
/* By default, paddingOuter is paddingInner / 2. The reason is that
size (width/height) = step * (cardinality - paddingInner + 2 * paddingOuter).
and we want the width/height to be integer by default.
Note that step (by default) and cardinality are integers.) */
isSignalRef(paddingInnerValue) ? {
- signal: `${paddingInnerValue.signal}/2`
+ signal: "".concat(paddingInnerValue.signal, "/2")
} : paddingInnerValue / 2);
}
+ } else if (isXorYOffset(channel)) {
+ if (scaleType === ScaleType.POINT) {
+ return 0.5; // so the point positions align with centers of band scales.
+ } else if (scaleType === ScaleType.BAND) {
+ return scaleConfig.offsetBandPaddingOuter;
+ }
}
return undefined;
}
function reverse(scaleType, sort, channel, scaleConfig) {
if (channel === 'x' && scaleConfig.xReverse !== undefined) {
if (hasContinuousDomain(scaleType) && sort === 'descending') {
if (isSignalRef(scaleConfig.xReverse)) {
return {
- signal: `!${scaleConfig.xReverse.signal}`
+ signal: "!".concat(scaleConfig.xReverse.signal)
};
} else {
return !scaleConfig.xReverse;
}
}
@@ -20262,11 +19223,11 @@
// If users explicitly provide a domain, we should not augment zero as that will be unexpected.
const hasCustomDomain = !!specifiedDomain && specifiedDomain !== 'unaggregated';
if (hasCustomDomain) {
if (hasContinuousDomain(scaleType)) {
- if (vegaUtil.isArray(specifiedDomain)) {
+ if (vega.isArray(specifiedDomain)) {
const first = specifiedDomain[0];
const last = specifiedDomain[specifiedDomain.length - 1];
if (first <= 0 && last >= 0) {
// if the domain includes zero, make zero remains true
@@ -20311,11 +19272,12 @@
* Determine if there is a specified scale type and if it is appropriate,
* or determine default type if type is unspecified or inappropriate.
*/
// NOTE: CompassQL uses this method.
function scaleType(specifiedScale, channel, fieldDef, mark) {
- const defaultScaleType = defaultType(channel, fieldDef, mark);
+ let hasNestedOffsetScale = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
+ const defaultScaleType = defaultType(channel, fieldDef, mark, hasNestedOffsetScale);
const {
type
} = specifiedScale;
if (!isScaleChannel(channel)) {
@@ -20344,11 +19306,11 @@
/**
* Determine appropriate default scale type.
*/
// NOTE: Voyager uses this method.
- function defaultType(channel, fieldDef, mark) {
+ function defaultType(channel, fieldDef, mark, hasNestedOffsetScale) {
switch (fieldDef.type) {
case 'nominal':
case 'ordinal':
{
var _fieldDef$axis;
@@ -20359,21 +19321,26 @@
}
return 'ordinal';
}
- if (channel in POSITION_SCALE_CHANNEL_INDEX) {
+ if (isXorY(channel) || isXorYOffset(channel)) {
if (contains(['rect', 'bar', 'image', 'rule'], mark.type)) {
// The rect/bar mark should fit into a band.
// For rule, using band scale to make rule align with axis ticks better https://github.com/vega/vega-lite/issues/3429
return 'band';
}
+
+ if (hasNestedOffsetScale) {
+ // If there is a nested offset scale, then there is a "band" for the span of the nested scale.
+ return 'band';
+ }
} else if (mark.type === 'arc' && channel in POLAR_POSITION_SCALE_CHANNEL_INDEX) {
return 'band';
}
- const dimensionSize = mark[getSizeChannel$1(channel)];
+ const dimensionSize = mark[getSizeChannel(channel)];
if (isRelativeBandSize(dimensionSize)) {
return 'band';
}
@@ -20420,13 +19387,14 @@
throw new Error(invalidFieldType(fieldDef.type));
}
- function parseScales(model, {
- ignoreRange
- } = {}) {
+ function parseScales(model) {
+ let {
+ ignoreRange
+ } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
parseScaleCore(model);
parseScaleDomain(model);
for (const prop of NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES) {
parseScaleProperty(model, prop);
@@ -20452,31 +19420,49 @@
const {
encoding,
mark,
markDef
} = model;
- return SCALE_CHANNELS.reduce((scaleComponents, channel) => {
+ const scaleComponents = {};
+
+ for (const channel of SCALE_CHANNELS) {
const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]); // must be typed def to have scale
// Don't generate scale for shape of geoshape
if (fieldOrDatumDef && mark === GEOSHAPE && channel === SHAPE && fieldOrDatumDef.type === GEOJSON) {
- return scaleComponents;
+ continue;
}
let specifiedScale = fieldOrDatumDef && fieldOrDatumDef['scale'];
+ if (isXorYOffset(channel)) {
+ const mainChannel = getMainChannelFromOffsetChannel(channel);
+
+ if (!channelHasNestedOffsetScale(encoding, mainChannel)) {
+ // Don't generate scale when the offset encoding shouldn't yield a nested scale
+ if (specifiedScale) {
+ warn(offsetEncodingScaleIgnored(channel));
+ }
+
+ continue;
+ }
+ }
+
if (fieldOrDatumDef && specifiedScale !== null && specifiedScale !== false) {
- specifiedScale ?? (specifiedScale = {});
- const sType = scaleType(specifiedScale, channel, fieldOrDatumDef, markDef);
- scaleComponents[channel] = new ScaleComponent(model.scaleName(`${channel}`, true), {
+ var _specifiedScale;
+
+ (_specifiedScale = specifiedScale) !== null && _specifiedScale !== void 0 ? _specifiedScale : specifiedScale = {};
+ const hasNestedOffsetScale = channelHasNestedOffsetScale(encoding, channel);
+ const sType = scaleType(specifiedScale, channel, fieldOrDatumDef, markDef, hasNestedOffsetScale);
+ scaleComponents[channel] = new ScaleComponent(model.scaleName("".concat(channel), true), {
value: sType,
explicit: specifiedScale.type === sType
});
}
+ }
- return scaleComponents;
- }, {});
+ return scaleComponents;
}
const scaleTypeTieBreaker = tieBreakByComparing((st1, st2) => scaleTypePrecedence(st1) - scaleTypePrecedence(st2));
function parseNonUnitScaleCore(model) {
@@ -20486,14 +19472,14 @@
for (const child of model.children) {
parseScaleCore(child); // Instead of always merging right away -- check if it is compatible to merge first!
for (const channel of keys(child.component.scales)) {
- var _resolve$scale;
+ var _resolve$scale, _resolve$scale$channe;
// if resolve is undefined, set default first
- (_resolve$scale = resolve.scale)[channel] ?? (_resolve$scale[channel] = defaultScaleResolve(channel, model));
+ (_resolve$scale$channe = (_resolve$scale = resolve.scale)[channel]) !== null && _resolve$scale$channe !== void 0 ? _resolve$scale$channe : _resolve$scale[channel] = defaultScaleResolve(channel, model);
if (resolve.scale[channel] === 'shared') {
const explicitScaleType = scaleTypeWithExplicitIndex[channel];
const childScaleType = child.component.scales[channel].getWithExplicit('type');
@@ -20587,10 +19573,12 @@
/** Name map for projections, which can be renamed by a model's parent. */
/** Name map for signals, which can be renamed by a model's parent. */
constructor(spec, type, parent, parentGivenName, config, resolve, view) {
+ var _spec$name, _spec$transform;
+
this.type = type;
this.parent = parent;
this.config = config;
_defineProperty(this, "name", void 0);
@@ -20638,29 +19626,29 @@
this.parent = parent;
this.config = config;
this.view = replaceExprRef(view); // If name is not provided, always use parent's givenName to avoid name conflicts.
- this.name = spec.name ?? parentGivenName;
+ this.name = (_spec$name = spec.name) !== null && _spec$name !== void 0 ? _spec$name : parentGivenName;
this.title = isText(spec.title) ? {
text: spec.title
} : spec.title ? replaceExprRef(spec.title) : undefined; // Shared name maps
this.scaleNameMap = parent ? parent.scaleNameMap : new NameMap();
this.projectionNameMap = parent ? parent.projectionNameMap : new NameMap();
this.signalNameMap = parent ? parent.signalNameMap : new NameMap();
this.data = spec.data;
this.description = spec.description;
- this.transforms = normalizeTransform(spec.transform ?? []);
+ this.transforms = normalizeTransform((_spec$transform = spec.transform) !== null && _spec$transform !== void 0 ? _spec$transform : []);
this.layout = type === 'layer' || type === 'unit' ? {} : extractCompositionLayout(spec, type, config);
this.component = {
data: {
sources: parent ? parent.component.data.sources : [],
outputNodes: parent ? parent.component.data.outputNodes : {},
outputNodeRefCounts: parent ? parent.component.data.outputNodeRefCounts : {},
// data is faceted if the spec is a facet spec or the parent has faceted data and data is undefined
- isFaceted: isFacetSpec(spec) || parent && parent.component.data.isFaceted && spec.data === undefined
+ isFaceted: isFacetSpec(spec) || (parent === null || parent === void 0 ? void 0 : parent.component.data.isFaceted) && spec.data === undefined
},
layoutSize: new Split(),
layoutHeaders: {
row: {},
column: {},
@@ -20765,14 +19753,16 @@
} // For top-level spec, we can set the global width and height signal to adjust the group size.
// For other child specs, we have to manually set width and height in the encode entry.
if (this.type === 'unit' || this.type === 'layer') {
+ var _encodeEntry;
+
return {
width: this.getSizeSignalRef('width'),
height: this.getSizeSignalRef('height'),
- ...(encodeEntry ?? {})
+ ...((_encodeEntry = encodeEntry) !== null && _encodeEntry !== void 0 ? _encodeEntry : {})
};
}
}
return isEmpty(encodeEntry) ? undefined : encodeEntry;
@@ -20836,14 +19826,16 @@
assembleProjections() {
return assembleProjections(this);
}
assembleTitle() {
+ var _this$title;
+
const {
encoding,
...titleNoEncoding
- } = this.title ?? {};
+ } = (_this$title = this.title) !== null && _this$title !== void 0 ? _this$title : {};
const title = { ...extractTitleConfig(this.config.title).nonMarkTitleProperties,
...titleNoEncoding,
...(encoding ? {
encode: {
update: encoding
@@ -20853,17 +19845,21 @@
if (title.text) {
if (contains(['unit', 'layer'], this.type)) {
// Unit/Layer
if (contains(['middle', undefined], title.anchor)) {
- title.frame ?? (title.frame = 'group');
+ var _title$frame;
+
+ (_title$frame = title.frame) !== null && _title$frame !== void 0 ? _title$frame : title.frame = 'group';
}
} else {
+ var _title$anchor;
+
// composition with Vega layout
// Set title = "start" by default for composition as "middle" does not look nice
// https://github.com/vega/vega/issues/960#issuecomment-471360328
- title.anchor ?? (title.anchor = 'start');
+ (_title$anchor = title.anchor) !== null && _title$anchor !== void 0 ? _title$anchor : title.anchor = 'start';
}
return isEmpty(title) ? undefined : title;
}
@@ -20872,11 +19868,12 @@
/**
* Assemble the mark group for this model. We accept optional `signals` so that we can include concat top-level signals with the top-level model's local signals.
*/
- assembleGroup(signals = []) {
+ assembleGroup() {
+ let signals = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
const group = {};
signals = signals.concat(this.assembleSignals());
if (signals.length > 0) {
group.signals = signals;
@@ -20911,11 +19908,11 @@
return group;
}
getName(text) {
- return varName((this.name ? `${this.name}_` : '') + text);
+ return varName((this.name ? "".concat(this.name, "_") : '') + text);
}
getDataName(type) {
return this.getName(DataSourceType[type].toLowerCase());
}
@@ -21101,11 +20098,12 @@
}
/** Abstract class for UnitModel and FacetModel. Both of which can contain fieldDefs as a part of its own specification. */
class ModelWithField extends Model {
/** Get "field" reference for Vega */
- vgField(channel, opt = {}) {
+ vgField(channel) {
+ let opt = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const fieldDef = this.fieldDef(channel);
if (!fieldDef) {
return undefined;
}
@@ -21145,28 +20143,32 @@
clone() {
return new DensityTransformNode(null, duplicate(this.transform));
}
constructor(parent, transform) {
+ var _this$transform$as, _specifiedAs$, _specifiedAs$2;
+
super(parent);
this.transform = transform;
this.transform = duplicate(transform); // duplicate to prevent side effects
- const specifiedAs = this.transform.as ?? [undefined, undefined];
- this.transform.as = [specifiedAs[0] ?? 'value', specifiedAs[1] ?? 'density'];
+ const specifiedAs = (_this$transform$as = this.transform.as) !== null && _this$transform$as !== void 0 ? _this$transform$as : [undefined, undefined];
+ this.transform.as = [(_specifiedAs$ = specifiedAs[0]) !== null && _specifiedAs$ !== void 0 ? _specifiedAs$ : 'value', (_specifiedAs$2 = specifiedAs[1]) !== null && _specifiedAs$2 !== void 0 ? _specifiedAs$2 : 'density'];
}
dependentFields() {
- return new Set([this.transform.density, ...(this.transform.groupby ?? [])]);
+ var _this$transform$group;
+
+ return new Set([this.transform.density, ...((_this$transform$group = this.transform.groupby) !== null && _this$transform$group !== void 0 ? _this$transform$group : [])]);
}
producedFields() {
return new Set(this.transform.as);
}
hash() {
- return `DensityTransform ${hash(this.transform)}`;
+ return "DensityTransform ".concat(hash(this.transform));
}
assemble() {
const {
density,
@@ -21235,11 +20237,11 @@
producedFields() {
return new Set(); // filter does not produce any new fields
}
hash() {
- return `FilterInvalid ${hash(this.filter)}`;
+ return "FilterInvalid ".concat(hash(this.filter));
}
/**
* Create the VgTransforms for each of the filtered fields.
*/
@@ -21251,14 +20253,14 @@
expr: 'datum'
});
if (fieldDef !== null) {
if (fieldDef.type === 'temporal') {
- vegaFilters.push(`(isDate(${ref}) || (isValid(${ref}) && isFinite(+${ref})))`);
+ vegaFilters.push("(isDate(".concat(ref, ") || (isValid(").concat(ref, ") && isFinite(+").concat(ref, ")))"));
} else if (fieldDef.type === 'quantitative') {
- vegaFilters.push(`isValid(${ref})`);
- vegaFilters.push(`isFinite(+${ref})`);
+ vegaFilters.push("isValid(".concat(ref, ")"));
+ vegaFilters.push("isFinite(+".concat(ref, ")"));
} else ;
}
return vegaFilters;
}, []);
@@ -21286,11 +20288,15 @@
const {
flatten,
as = []
} = this.transform;
- this.transform.as = flatten.map((f, i) => as[i] ?? f);
+ this.transform.as = flatten.map((f, i) => {
+ var _as$i;
+
+ return (_as$i = as[i]) !== null && _as$i !== void 0 ? _as$i : f;
+ });
}
dependentFields() {
return new Set(this.transform.flatten);
}
@@ -21298,11 +20304,11 @@
producedFields() {
return new Set(this.transform.as);
}
hash() {
- return `FlattenTransform ${hash(this.transform)}`;
+ return "FlattenTransform ".concat(hash(this.transform));
}
assemble() {
const {
flatten: fields,
@@ -21326,16 +20332,18 @@
clone() {
return new FoldTransformNode(null, duplicate(this.transform));
}
constructor(parent, transform) {
+ var _this$transform$as, _specifiedAs$, _specifiedAs$2;
+
super(parent);
this.transform = transform;
this.transform = duplicate(transform); // duplicate to prevent side effects
- const specifiedAs = this.transform.as ?? [undefined, undefined];
- this.transform.as = [specifiedAs[0] ?? 'key', specifiedAs[1] ?? 'value'];
+ const specifiedAs = (_this$transform$as = this.transform.as) !== null && _this$transform$as !== void 0 ? _this$transform$as : [undefined, undefined];
+ this.transform.as = [(_specifiedAs$ = specifiedAs[0]) !== null && _specifiedAs$ !== void 0 ? _specifiedAs$ : 'key', (_specifiedAs$2 = specifiedAs[1]) !== null && _specifiedAs$2 !== void 0 ? _specifiedAs$2 : 'value'];
}
dependentFields() {
return new Set(this.transform.fold);
}
@@ -21343,11 +20351,11 @@
producedFields() {
return new Set(this.transform.as);
}
hash() {
- return `FoldTransform ${hash(this.transform)}`;
+ return "FoldTransform ".concat(hash(this.transform));
}
assemble() {
const {
fold,
@@ -21377,26 +20385,26 @@
for (const coordinates of [[LONGITUDE, LATITUDE], [LONGITUDE2, LATITUDE2]]) {
const pair = coordinates.map(channel => {
const def = getFieldOrDatumDef(model.encoding[channel]);
return isFieldDef(def) ? def.field : isDatumDef(def) ? {
- expr: `${def.datum}`
+ expr: "".concat(def.datum)
} : isValueDef(def) ? {
- expr: `${def['value']}`
+ expr: "".concat(def['value'])
} : undefined;
});
if (pair[0] || pair[1]) {
- parent = new GeoJSONNode(parent, pair, null, model.getName(`geojson_${geoJsonCounter++}`));
+ parent = new GeoJSONNode(parent, pair, null, model.getName("geojson_".concat(geoJsonCounter++)));
}
}
if (model.channelHasField(SHAPE)) {
const fieldDef = model.typedFieldDef(SHAPE);
if (fieldDef.type === GEOJSON) {
- parent = new GeoJSONNode(parent, null, fieldDef.field, model.getName(`geojson_${geoJsonCounter++}`));
+ parent = new GeoJSONNode(parent, null, fieldDef.field, model.getName("geojson_".concat(geoJsonCounter++)));
}
}
return parent;
}
@@ -21407,26 +20415,28 @@
this.geojson = geojson;
this.signal = signal;
}
dependentFields() {
- const fields = (this.fields ?? []).filter(vegaUtil.isString);
+ var _this$fields;
+
+ const fields = ((_this$fields = this.fields) !== null && _this$fields !== void 0 ? _this$fields : []).filter(vega.isString);
return new Set([...(this.geojson ? [this.geojson] : []), ...fields]);
}
producedFields() {
return new Set();
}
hash() {
- return `GeoJSON ${this.geojson} ${this.signal} ${hash(this.fields)}`;
+ return "GeoJSON ".concat(this.geojson, " ").concat(this.signal, " ").concat(hash(this.fields));
}
assemble() {
return [...(this.geojson ? [{
type: 'filter',
- expr: `isValid(datum["${this.geojson}"])`
+ expr: "isValid(datum[\"".concat(this.geojson, "\"])")
}] : []), {
type: 'geojson',
...(this.fields ? {
fields: this.fields
} : {}),
@@ -21458,35 +20468,35 @@
for (const coordinates of [[LONGITUDE, LATITUDE], [LONGITUDE2, LATITUDE2]]) {
const pair = coordinates.map(channel => {
const def = getFieldOrDatumDef(model.encoding[channel]);
return isFieldDef(def) ? def.field : isDatumDef(def) ? {
- expr: `${def.datum}`
+ expr: "".concat(def.datum)
} : isValueDef(def) ? {
- expr: `${def['value']}`
+ expr: "".concat(def['value'])
} : undefined;
});
const suffix = coordinates[0] === LONGITUDE2 ? '2' : '';
if (pair[0] || pair[1]) {
- parent = new GeoPointNode(parent, model.projectionName(), pair, [model.getName(`x${suffix}`), model.getName(`y${suffix}`)]);
+ parent = new GeoPointNode(parent, model.projectionName(), pair, [model.getName("x".concat(suffix)), model.getName("y".concat(suffix))]);
}
}
return parent;
}
dependentFields() {
- return new Set(this.fields.filter(vegaUtil.isString));
+ return new Set(this.fields.filter(vega.isString));
}
producedFields() {
return new Set(this.as);
}
hash() {
- return `Geopoint ${this.projection} ${hash(this.fields)} ${hash(this.as)}`;
+ return "Geopoint ".concat(this.projection, " ").concat(hash(this.fields), " ").concat(hash(this.as));
}
assemble() {
return {
type: 'geopoint',
@@ -21507,11 +20517,13 @@
super(parent);
this.transform = transform;
}
dependentFields() {
- return new Set([this.transform.impute, this.transform.key, ...(this.transform.groupby ?? [])]);
+ var _this$transform$group;
+
+ return new Set([this.transform.impute, this.transform.key, ...((_this$transform$group = this.transform.groupby) !== null && _this$transform$group !== void 0 ? _this$transform$group : [])]);
}
producedFields() {
return new Set([this.transform.impute]);
}
@@ -21522,11 +20534,11 @@
stop,
step
} = keyvals;
const result = [start, stop, ...(step ? [step] : [])].join(',');
return {
- signal: `sequence(${result})`
+ signal: "sequence(".concat(result, ")")
};
}
static makeFromTransform(parent, imputeTransform) {
return new ImputeNode(parent, imputeTransform);
@@ -21575,11 +20587,11 @@
return null;
}
hash() {
- return `Impute ${hash(this.transform)}`;
+ return "Impute ".concat(hash(this.transform));
}
assemble() {
const {
impute,
@@ -21605,22 +20617,22 @@
};
if (method && method !== 'value') {
const deriveNewField = {
type: 'window',
- as: [`imputed_${impute}_value`],
+ as: ["imputed_".concat(impute, "_value")],
ops: [method],
fields: [impute],
frame,
ignorePeers: false,
...(groupby ? {
groupby
} : {})
};
const replaceOriginal = {
type: 'formula',
- expr: `datum.${impute} === null ? datum.imputed_${impute}_value : datum.${impute}`,
+ expr: "datum.".concat(impute, " === null ? datum.imputed_").concat(impute, "_value : datum.").concat(impute),
as: impute
};
return [imputeTransform, deriveNewField, replaceOriginal];
} else {
return [imputeTransform];
@@ -21637,28 +20649,32 @@
clone() {
return new LoessTransformNode(null, duplicate(this.transform));
}
constructor(parent, transform) {
+ var _this$transform$as, _specifiedAs$, _specifiedAs$2;
+
super(parent);
this.transform = transform;
this.transform = duplicate(transform); // duplicate to prevent side effects
- const specifiedAs = this.transform.as ?? [undefined, undefined];
- this.transform.as = [specifiedAs[0] ?? transform.on, specifiedAs[1] ?? transform.loess];
+ const specifiedAs = (_this$transform$as = this.transform.as) !== null && _this$transform$as !== void 0 ? _this$transform$as : [undefined, undefined];
+ this.transform.as = [(_specifiedAs$ = specifiedAs[0]) !== null && _specifiedAs$ !== void 0 ? _specifiedAs$ : transform.on, (_specifiedAs$2 = specifiedAs[1]) !== null && _specifiedAs$2 !== void 0 ? _specifiedAs$2 : transform.loess];
}
dependentFields() {
- return new Set([this.transform.loess, this.transform.on, ...(this.transform.groupby ?? [])]);
+ var _this$transform$group;
+
+ return new Set([this.transform.loess, this.transform.on, ...((_this$transform$group = this.transform.groupby) !== null && _this$transform$group !== void 0 ? _this$transform$group : [])]);
}
producedFields() {
return new Set(this.transform.as);
}
hash() {
- return `LoessTransform ${hash(this.transform)}`;
+ return "LoessTransform ".concat(hash(this.transform));
}
assemble() {
const {
loess,
@@ -21700,11 +20716,11 @@
if (!fromSource) {
fromSource = new SourceNode(from.data);
sources.push(fromSource);
}
- const fromOutputName = model.getName(`lookup_${counter}`);
+ const fromOutputName = model.getName("lookup_".concat(counter));
fromOutputNode = new OutputNode(fromSource, fromOutputName, DataSourceType.Lookup, model.component.data.outputNodeRefCounts);
model.component.data.outputNodes[fromOutputName] = fromOutputNode;
} else if (isLookupSelection(from)) {
const selName = from.param;
transform = {
@@ -21732,36 +20748,36 @@
dependentFields() {
return new Set([this.transform.lookup]);
}
producedFields() {
- return new Set(this.transform.as ? vegaUtil.array(this.transform.as) : this.transform.from.fields);
+ return new Set(this.transform.as ? vega.array(this.transform.as) : this.transform.from.fields);
}
hash() {
- return `Lookup ${hash({
- transform: this.transform,
- secondary: this.secondary
- })}`;
+ return "Lookup ".concat(hash({
+ transform: this.transform,
+ secondary: this.secondary
+ }));
}
assemble() {
let foreign;
if (this.transform.from.fields) {
// lookup a few fields and add create a flat output
foreign = {
values: this.transform.from.fields,
...(this.transform.as ? {
- as: vegaUtil.array(this.transform.as)
+ as: vega.array(this.transform.as)
} : {})
};
} else {
// lookup full record and nest it
let asName = this.transform.as;
- if (!vegaUtil.isString(asName)) {
+ if (!vega.isString(asName)) {
warn(NO_FIELDS_NEEDS_AS);
asName = '_lookup';
}
foreign = {
@@ -21791,28 +20807,32 @@
clone() {
return new QuantileTransformNode(null, duplicate(this.transform));
}
constructor(parent, transform) {
+ var _this$transform$as, _specifiedAs$, _specifiedAs$2;
+
super(parent);
this.transform = transform;
this.transform = duplicate(transform); // duplicate to prevent side effects
- const specifiedAs = this.transform.as ?? [undefined, undefined];
- this.transform.as = [specifiedAs[0] ?? 'prob', specifiedAs[1] ?? 'value'];
+ const specifiedAs = (_this$transform$as = this.transform.as) !== null && _this$transform$as !== void 0 ? _this$transform$as : [undefined, undefined];
+ this.transform.as = [(_specifiedAs$ = specifiedAs[0]) !== null && _specifiedAs$ !== void 0 ? _specifiedAs$ : 'prob', (_specifiedAs$2 = specifiedAs[1]) !== null && _specifiedAs$2 !== void 0 ? _specifiedAs$2 : 'value'];
}
dependentFields() {
- return new Set([this.transform.quantile, ...(this.transform.groupby ?? [])]);
+ var _this$transform$group;
+
+ return new Set([this.transform.quantile, ...((_this$transform$group = this.transform.groupby) !== null && _this$transform$group !== void 0 ? _this$transform$group : [])]);
}
producedFields() {
return new Set(this.transform.as);
}
hash() {
- return `QuantileTransform ${hash(this.transform)}`;
+ return "QuantileTransform ".concat(hash(this.transform));
}
assemble() {
const {
quantile,
@@ -21836,28 +20856,32 @@
clone() {
return new RegressionTransformNode(null, duplicate(this.transform));
}
constructor(parent, transform) {
+ var _this$transform$as, _specifiedAs$, _specifiedAs$2;
+
super(parent);
this.transform = transform;
this.transform = duplicate(transform); // duplicate to prevent side effects
- const specifiedAs = this.transform.as ?? [undefined, undefined];
- this.transform.as = [specifiedAs[0] ?? transform.on, specifiedAs[1] ?? transform.regression];
+ const specifiedAs = (_this$transform$as = this.transform.as) !== null && _this$transform$as !== void 0 ? _this$transform$as : [undefined, undefined];
+ this.transform.as = [(_specifiedAs$ = specifiedAs[0]) !== null && _specifiedAs$ !== void 0 ? _specifiedAs$ : transform.on, (_specifiedAs$2 = specifiedAs[1]) !== null && _specifiedAs$2 !== void 0 ? _specifiedAs$2 : transform.regression];
}
dependentFields() {
- return new Set([this.transform.regression, this.transform.on, ...(this.transform.groupby ?? [])]);
+ var _this$transform$group;
+
+ return new Set([this.transform.regression, this.transform.on, ...((_this$transform$group = this.transform.groupby) !== null && _this$transform$group !== void 0 ? _this$transform$group : [])]);
}
producedFields() {
return new Set(this.transform.as);
}
hash() {
- return `RegressionTransform ${hash(this.transform)}`;
+ return "RegressionTransform ".concat(hash(this.transform));
}
assemble() {
const {
regression,
@@ -21888,23 +20912,27 @@
super(parent);
this.transform = transform;
}
addDimensions(fields) {
- this.transform.groupby = unique((this.transform.groupby ?? []).concat(fields), d => d);
+ var _this$transform$group;
+
+ this.transform.groupby = unique(((_this$transform$group = this.transform.groupby) !== null && _this$transform$group !== void 0 ? _this$transform$group : []).concat(fields), d => d);
}
producedFields() {
return undefined; // return undefined so that potentially everything can depend on the pivot
}
dependentFields() {
- return new Set([this.transform.pivot, this.transform.value, ...(this.transform.groupby ?? [])]);
+ var _this$transform$group2;
+
+ return new Set([this.transform.pivot, this.transform.value, ...((_this$transform$group2 = this.transform.groupby) !== null && _this$transform$group2 !== void 0 ? _this$transform$group2 : [])]);
}
hash() {
- return `PivotTransform ${hash(this.transform)}`;
+ return "PivotTransform ".concat(hash(this.transform));
}
assemble() {
const {
pivot,
@@ -21952,11 +20980,11 @@
producedFields() {
return new Set();
}
hash() {
- return `SampleTransform ${hash(this.transform)}`;
+ return "SampleTransform ".concat(hash(this.transform));
}
assemble() {
return {
type: 'sample',
@@ -21988,12 +21016,14 @@
}
}
if (node instanceof ParseNode) {
if (node.parent instanceof SourceNode && !dataSource.source) {
+ var _dataSource$format;
+
// If node's parent is a root source and the data source does not refer to another data source, use normal format parse
- dataSource.format = { ...(dataSource.format ?? {}),
+ dataSource.format = { ...((_dataSource$format = dataSource.format) !== null && _dataSource$format !== void 0 ? _dataSource$format : {}),
parse: node.assembleFormatParse()
}; // add calculates for all nested fields
dataSource.transform.push(...node.assembleTransforms(true));
} else {
@@ -22002,11 +21032,11 @@
}
}
if (node instanceof FacetNode) {
if (!dataSource.name) {
- dataSource.name = `data_${datasetIndex++}`;
+ dataSource.name = "data_".concat(datasetIndex++);
}
if (!dataSource.source || dataSource.transform.length > 0) {
data.push(dataSource);
node.data = dataSource.name;
@@ -22034,11 +21064,11 @@
// Note that an output node may be required but we still do not assemble a
// separate data source for it.
node.setSource(dataSource.name);
} else {
if (!dataSource.name) {
- dataSource.name = `data_${datasetIndex++}`;
+ dataSource.name = "data_".concat(datasetIndex++);
} // Here we set the name of the datasource we generated. From now on
// other assemblers can use it.
node.setSource(dataSource.name); // if this node has more than one child, we will add a datasource automatically
@@ -22070,11 +21100,11 @@
break;
default:
{
if (!dataSource.name) {
- dataSource.name = `data_${datasetIndex++}`;
+ dataSource.name = "data_".concat(datasetIndex++);
}
let source = dataSource.name;
if (!dataSource.source || dataSource.transform.length > 0) {
@@ -22084,11 +21114,11 @@
}
for (const child of node.children) {
const newData = {
name: null,
- source: source,
+ source,
transform: []
};
walkTree(child, newData);
}
@@ -22134,11 +21164,11 @@
let sourceIndex = 0;
for (const root of dataComponent.sources) {
// assign a name if the source does not have a name yet
if (!root.hasName()) {
- root.dataName = `source_${sourceIndex++}`;
+ root.dataName = "source_".concat(sourceIndex++);
}
const newData = root.assemble();
walkTree(root, newData);
} // remove empty transform arrays for cleaner output
@@ -22152,18 +21182,22 @@
let whereTo = 0;
for (const [i, d] of data.entries()) {
- if ((d.transform ?? []).length === 0 && !d.source) {
+ var _d$transform;
+
+ if (((_d$transform = d.transform) !== null && _d$transform !== void 0 ? _d$transform : []).length === 0 && !d.source) {
data.splice(whereTo++, 0, data.splice(i, 1)[0]);
}
} // now fix the from references in lookup transforms
for (const d of data) {
- for (const t of d.transform ?? []) {
+ for (const t of (_d$transform2 = d.transform) !== null && _d$transform2 !== void 0 ? _d$transform2 : []) {
+ var _d$transform2;
+
if (t.type === 'lookup') {
t.from = dataComponent.outputNodes[t.from].getSource();
}
}
} // inline values for datasets that are in the datastore
@@ -22213,13 +21247,13 @@
includeDefault: titleConfig === undefined || !!titleConfig
});
if (child.component.layoutHeaders[channel].title) {
// TODO: better handle multiline titles
- title$1 = vegaUtil.isArray(title$1) ? title$1.join(', ') : title$1; // merge title with child to produce "Title / Subtitle / Sub-subtitle"
+ title$1 = vega.isArray(title$1) ? title$1.join(', ') : title$1; // merge title with child to produce "Title / Subtitle / Sub-subtitle"
- title$1 += ` / ${child.component.layoutHeaders[channel].title}`;
+ title$1 += " / ".concat(child.component.layoutHeaders[channel].title);
child.component.layoutHeaders[channel].title = null;
}
const labelOrient = getHeaderProperty('labelOrient', fieldDef.header, config, channel);
const labels = fieldDef.header !== null ? getFirstDefined((_fieldDef$header = fieldDef.header) === null || _fieldDef$header === void 0 ? void 0 : _fieldDef$header.labels, config.header.labels, true) : false;
@@ -22257,12 +21291,14 @@
// For shared axis, move the axes to facet's header or footer
const headerChannel = channel === 'x' ? 'column' : 'row';
const layoutHeader = layoutHeaders[headerChannel];
for (const axisComponent of child.component.axes[channel]) {
+ var _layoutHeader$headerT;
+
const headerType = getHeaderType(axisComponent.get('orient'));
- layoutHeader[headerType] ?? (layoutHeader[headerType] = [makeHeaderComponent(model, headerChannel, false)]); // FIXME: assemble shouldn't be called here, but we do it this way so we only extract the main part of the axes
+ (_layoutHeader$headerT = layoutHeader[headerType]) !== null && _layoutHeader$headerT !== void 0 ? _layoutHeader$headerT : layoutHeader[headerType] = [makeHeaderComponent(model, headerChannel, false)]; // FIXME: assemble shouldn't be called here, but we do it this way so we only extract the main part of the axes
const mainAxis = assembleAxis(axisComponent, 'main', model.config, {
header: true
});
@@ -22313,12 +21349,14 @@
const resolve = model.component.resolve;
const layoutSizeCmpt = model.component.layoutSize;
let mergedSize; // Try to merge layout size
for (const child of model.children) {
+ var _resolve$scale$channe;
+
const childSize = child.component.layoutSize.getWithExplicit(sizeType);
- const scaleResolve = resolve.scale[channel] ?? defaultScaleResolve(channel, model);
+ const scaleResolve = (_resolve$scale$channe = resolve.scale[channel]) !== null && _resolve$scale$channe !== void 0 ? _resolve$scale$channe : defaultScaleResolve(channel, model);
if (scaleResolve === 'independent' && childSize.value === 'step') {
// Do not merge independent scales with range-step as their size depends
// on the scale domains, which can be different between scales.
mergedSize = undefined;
@@ -22360,11 +21398,11 @@
size,
component
} = model;
for (const channel of POSITION_SCALE_CHANNELS) {
- const sizeType = getSizeChannel$1(channel);
+ const sizeType = getSizeChannel(channel);
if (size[sizeType]) {
const specifiedSize = size[sizeType];
component.layoutSize.set(sizeType, isStep(specifiedSize) ? 'step' : specifiedSize, true);
} else {
@@ -22404,12 +21442,12 @@
}
}
function facetSortFieldName(fieldDef, sort, opt) {
return vgField(sort, {
- suffix: `by_${vgField(fieldDef)}`,
- ...(opt ?? {})
+ suffix: "by_".concat(vgField(fieldDef)),
+ ...(opt !== null && opt !== void 0 ? opt : {})
});
}
class FacetModel extends ModelWithField {
constructor(spec, parent, parentGivenName, config) {
super(spec, 'facet', parent, parentGivenName, config, spec.resolve);
@@ -22530,29 +21568,35 @@
if (facetFieldDef) {
const titleOrient = getHeaderProperty('titleOrient', facetFieldDef.header, this.config, channel);
if (['right', 'bottom'].includes(titleOrient)) {
+ var _layoutMixins$titleAn;
+
const headerChannel = getHeaderChannel(channel, titleOrient);
- layoutMixins.titleAnchor ?? (layoutMixins.titleAnchor = {});
+ (_layoutMixins$titleAn = layoutMixins.titleAnchor) !== null && _layoutMixins$titleAn !== void 0 ? _layoutMixins$titleAn : layoutMixins.titleAnchor = {};
layoutMixins.titleAnchor[headerChannel] = 'end';
}
}
if (headerComponent !== null && headerComponent !== void 0 && headerComponent[0]) {
// set header/footerBand
const sizeType = channel === 'row' ? 'height' : 'width';
const bandType = headerType === 'header' ? 'headerBand' : 'footerBand';
if (channel !== 'facet' && !this.child.component.layoutSize.get(sizeType)) {
+ var _layoutMixins$bandTyp;
+
// If facet child does not have size signal, then apply headerBand
- layoutMixins[bandType] ?? (layoutMixins[bandType] = {});
+ (_layoutMixins$bandTyp = layoutMixins[bandType]) !== null && _layoutMixins$bandTyp !== void 0 ? _layoutMixins$bandTyp : layoutMixins[bandType] = {};
layoutMixins[bandType][channel] = 0.5;
}
if (layoutHeaderComponent.title) {
- layoutMixins.offset ?? (layoutMixins.offset = {});
+ var _layoutMixins$offset;
+
+ (_layoutMixins$offset = layoutMixins.offset) !== null && _layoutMixins$offset !== void 0 ? _layoutMixins$offset : layoutMixins.offset = {};
layoutMixins.offset[channel === 'row' ? 'rowTitle' : 'columnTitle'] = 10;
}
}
}
}
@@ -22597,11 +21641,11 @@
return undefined;
} else {
// In facetNode.assemble(), the name is always this.getName('column') + '_layout'.
const facetLayoutDataName = this.getName('column_domain');
return {
- signal: `length(data('${facetLayoutDataName}'))`
+ signal: "length(data('".concat(facetLayoutDataName, "'))")
};
}
}
assembleGroupStyle() {
@@ -22645,11 +21689,11 @@
if (this.child instanceof FacetModel) {
if (this.child.channelHasField('column')) {
const field = vgField(this.child.facet.column);
fields.push(field);
ops.push('distinct');
- as.push(`distinct_${field}`);
+ as.push("distinct_".concat(field));
}
} else {
for (const channel of POSITION_SCALE_CHANNELS) {
const childScaleComponent = this.child.component.scales[channel];
@@ -22662,11 +21706,11 @@
const field = getFieldFromDomain(domain);
if (field) {
fields.push(field);
ops.push('distinct');
- as.push(`distinct_${field}`);
+ as.push("distinct_".concat(field));
} else {
warn(unknownField(channel));
}
}
}
@@ -22729,11 +21773,11 @@
} else {
fields.push(field);
ops.push(op);
as.push(outputName);
}
- } else if (vegaUtil.isArray(sort)) {
+ } else if (vega.isArray(sort)) {
const outputName = sortArrayIndexField(fieldDef, channel);
fields.push(outputName);
ops.push('max');
as.push(outputName);
}
@@ -22768,11 +21812,11 @@
if (fieldDef) {
if (isSortField(fieldDef.sort)) {
return [facetSortFieldName(fieldDef, fieldDef.sort, {
expr: 'datum'
})];
- } else if (vegaUtil.isArray(fieldDef.sort)) {
+ } else if (vega.isArray(fieldDef.sort)) {
return [sortArrayIndexField(fieldDef, channel, {
expr: 'datum'
})];
}
@@ -22792,11 +21836,11 @@
if (fieldDef) {
const {
sort
} = fieldDef;
- const order = (isSortField(sort) ? sort.order : !vegaUtil.isArray(sort) && sort) || 'ascending';
+ const order = (isSortField(sort) ? sort.order : !vega.isArray(sort) && sort) || 'ascending';
return [order];
}
return [];
}
@@ -22860,11 +21904,11 @@
sort: {
field: FACET_CHANNELS.map(c => this.facetSortFields(c)).flat(),
order: FACET_CHANNELS.map(c => this.facetSortOrder(c)).flat()
},
...(data.length > 0 ? {
- data: data
+ data
} : {}),
...(encodeEntry ? {
encode: {
update: encodeEntry
}
@@ -23011,12 +22055,14 @@
if (isCalculate(t)) {
transformNode = head = new CalculateNode(head, t);
derivedType = 'derived';
} else if (isFilter(t)) {
+ var _ParseNode$makeWithAn;
+
const implicit = getImplicitFromFilterTransform(t);
- transformNode = head = ParseNode.makeWithAncestors(head, {}, implicit, ancestorParse) ?? head;
+ transformNode = head = (_ParseNode$makeWithAn = ParseNode.makeWithAncestors(head, {}, implicit, ancestorParse)) !== null && _ParseNode$makeWithAn !== void 0 ? _ParseNode$makeWithAn : head;
head = new FilterNode(head, model, t.filter);
} else if (isBin(t)) {
transformNode = head = BinNode.makeFromTransform(head, t, model);
derivedType = 'number';
} else if (isTimeUnit(t)) {
@@ -23080,11 +22126,13 @@
warn(invalidTransformIgnored(t));
continue;
}
if (transformNode && derivedType !== undefined) {
- for (const field of transformNode.producedFields() ?? []) {
+ for (const field of (_transformNode$produc = transformNode.producedFields()) !== null && _transformNode$produc !== void 0 ? _transformNode$produc : []) {
+ var _transformNode$produc;
+
ancestorParse.set(field, derivedType, false);
}
}
}
@@ -23144,11 +22192,11 @@
v
...Child data...
*/
function parseData(model) {
- var _data$format3;
+ var _data$format3, _ParseNode$makeExplic, _ParseNode$makeWithAn2;
let head = parseRoot(model, model.component.data.sources);
const {
outputNodes,
outputNodeRefCounts
@@ -23170,11 +22218,11 @@
} else if ((data === null || data === void 0 ? void 0 : (_data$format3 = data.format) === null || _data$format3 === void 0 ? void 0 : _data$format3.parse) === null) {
// format.parse: null means disable parsing
ancestorParse.parseNothing = true;
}
- head = ParseNode.makeExplicit(head, model, ancestorParse) ?? head; // Default discrete selections require an identifer transform to
+ head = (_ParseNode$makeExplic = ParseNode.makeExplicit(head, model, ancestorParse)) !== null && _ParseNode$makeExplic !== void 0 ? _ParseNode$makeExplic : head; // Default discrete selections require an identifer transform to
// uniquely identify data points. Add this transform at the head of
// the pipeline such that the identifier field is available for all
// subsequent datasets. During optimization, we will remove this
// transform if it proves to be unnecessary. Additional identifier
// transforms will be necessary when new tuples are constructed
@@ -23185,62 +22233,72 @@
const parentIsLayer = model.parent && isLayerModel(model.parent);
if (isUnitModel(model) || isFacetModel(model)) {
if (parentIsLayer) {
- head = BinNode.makeFromEncoding(head, model) ?? head;
+ var _BinNode$makeFromEnco;
+
+ head = (_BinNode$makeFromEnco = BinNode.makeFromEncoding(head, model)) !== null && _BinNode$makeFromEnco !== void 0 ? _BinNode$makeFromEnco : head;
}
}
if (model.transforms.length > 0) {
head = parseTransformArray(head, model, ancestorParse);
} // create parse nodes for fields that need to be parsed (or flattened) implicitly
const implicitSelection = getImplicitFromSelection(model);
const implicitEncoding = getImplicitFromEncoding(model);
- head = ParseNode.makeWithAncestors(head, {}, { ...implicitSelection,
+ head = (_ParseNode$makeWithAn2 = ParseNode.makeWithAncestors(head, {}, { ...implicitSelection,
...implicitEncoding
- }, ancestorParse) ?? head;
+ }, ancestorParse)) !== null && _ParseNode$makeWithAn2 !== void 0 ? _ParseNode$makeWithAn2 : head;
if (isUnitModel(model)) {
head = GeoJSONNode.parseAll(head, model);
head = GeoPointNode.parseAll(head, model);
}
if (isUnitModel(model) || isFacetModel(model)) {
+ var _TimeUnitNode$makeFro;
+
if (!parentIsLayer) {
- head = BinNode.makeFromEncoding(head, model) ?? head;
+ var _BinNode$makeFromEnco2;
+
+ head = (_BinNode$makeFromEnco2 = BinNode.makeFromEncoding(head, model)) !== null && _BinNode$makeFromEnco2 !== void 0 ? _BinNode$makeFromEnco2 : head;
}
- head = TimeUnitNode.makeFromEncoding(head, model) ?? head;
+ head = (_TimeUnitNode$makeFro = TimeUnitNode.makeFromEncoding(head, model)) !== null && _TimeUnitNode$makeFro !== void 0 ? _TimeUnitNode$makeFro : head;
head = CalculateNode.parseAllForSortIndex(head, model);
} // add an output node pre aggregation
const rawName = model.getDataName(DataSourceType.Raw);
const raw = new OutputNode(head, rawName, DataSourceType.Raw, outputNodeRefCounts);
outputNodes[rawName] = raw;
head = raw;
if (isUnitModel(model)) {
+ var _ImputeNode$makeFromE, _StackNode$makeFromEn;
+
const agg = AggregateNode.makeFromEncoding(head, model);
if (agg) {
head = agg;
if (requiresSelectionId(model)) {
head = new IdentifierNode(head);
}
}
- head = ImputeNode.makeFromEncoding(head, model) ?? head;
- head = StackNode.makeFromEncoding(head, model) ?? head;
+ head = (_ImputeNode$makeFromE = ImputeNode.makeFromEncoding(head, model)) !== null && _ImputeNode$makeFromE !== void 0 ? _ImputeNode$makeFromE : head;
+ head = (_StackNode$makeFromEn = StackNode.makeFromEncoding(head, model)) !== null && _StackNode$makeFromEn !== void 0 ? _StackNode$makeFromEn : head;
}
if (isUnitModel(model)) {
- head = FilterInvalidNode.make(head, model) ?? head;
+ var _FilterInvalidNode$ma;
+
+ head = (_FilterInvalidNode$ma = FilterInvalidNode.make(head, model)) !== null && _FilterInvalidNode$ma !== void 0 ? _FilterInvalidNode$ma : head;
} // output node for marks
const mainName = model.getDataName(DataSourceType.Main);
const main = new OutputNode(head, mainName, DataSourceType.Main, outputNodeRefCounts);
@@ -23253,14 +22311,16 @@
let facetRoot = null;
if (isFacetModel(model)) {
+ var _makeJoinAggregateFro;
+
const facetName = model.getName('facet'); // Derive new aggregate for facet's sort field
// augment data source with new fields for crossed facet
- head = makeJoinAggregateFromFacet(head, model.facet) ?? head;
+ head = (_makeJoinAggregateFro = makeJoinAggregateFromFacet(head, model.facet)) !== null && _makeJoinAggregateFro !== void 0 ? _makeJoinAggregateFro : head;
facetRoot = new FacetNode(head, model, facetName, main.getSource());
outputNodes[facetName] = facetRoot;
}
return { ...model.component.data,
@@ -23284,11 +22344,11 @@
if (((_spec$resolve = spec.resolve) === null || _spec$resolve === void 0 ? void 0 : (_spec$resolve$axis = _spec$resolve.axis) === null || _spec$resolve$axis === void 0 ? void 0 : _spec$resolve$axis.x) === 'shared' || ((_spec$resolve2 = spec.resolve) === null || _spec$resolve2 === void 0 ? void 0 : (_spec$resolve2$axis = _spec$resolve2.axis) === null || _spec$resolve2$axis === void 0 ? void 0 : _spec$resolve2$axis.y) === 'shared') {
warn(CONCAT_CANNOT_SHARE_AXIS);
}
this.children = this.getChildren(spec).map((child, i) => {
- return buildModel(child, this, this.getName(`concat_${i}`), undefined, config);
+ return buildModel(child, this, this.getName("concat_".concat(i)), undefined, config);
});
}
parseData() {
this.component.data = parseData(this);
@@ -23397,11 +22457,11 @@
}
assembleDefaultLayout() {
const columns = this.layout.columns;
return { ...(columns != null ? {
- columns: columns
+ columns
} : {}),
bounds: 'full',
// Use align each so it can work with multiple plots with different size
align: 'each'
};
@@ -23421,11 +22481,14 @@
labelExpr: 1,
encode: 1
};
const AXIS_COMPONENT_PROPERTIES = keys(AXIS_COMPONENT_PROPERTIES_INDEX);
class AxisComponent extends Split {
- constructor(explicit = {}, implicit = {}, mainExtracted = false) {
+ constructor() {
+ let explicit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+ let implicit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ let mainExtracted = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
super();
this.explicit = explicit;
this.implicit = implicit;
this.mainExtracted = mainExtracted;
}
@@ -23454,15 +22517,17 @@
}
}
function labels(model, channel, specifiedLabelsSpec) {
+ var _getFieldOrDatumDef;
+
const {
encoding,
config
} = model;
- const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]) ?? getFieldOrDatumDef(encoding[getSecondaryRangeChannel(channel)]);
+ const fieldOrDatumDef = (_getFieldOrDatumDef = getFieldOrDatumDef(encoding[channel])) !== null && _getFieldOrDatumDef !== void 0 ? _getFieldOrDatumDef : getFieldOrDatumDef(encoding[getSecondaryRangeChannel(channel)]);
const axis = model.axis(channel) || {};
const {
format,
formatType
} = axis;
@@ -23538,12 +22603,14 @@
// skip if the child does not have a particular axis
continue;
}
if (resolve.axis[channel] === 'independent') {
+ var _axes$channel;
+
// If axes are independent, concat the axisComponent array.
- axes[channel] = (axes[channel] ?? []).concat(child.component.axes[channel]); // Automatically adjust orient
+ axes[channel] = ((_axes$channel = axes[channel]) !== null && _axes$channel !== void 0 ? _axes$channel : []).concat(child.component.axes[channel]); // Automatically adjust orient
for (const axisComponent of child.component.axes[channel]) {
const {
value: orient,
explicit
@@ -23681,11 +22748,11 @@
'translate', // translate has dependent logic for bar's bin position and it's 0.5 by default in Vega. If a config overrides this value, we need to know.
// the rest are not axis configs in Vega, but are in VL, so we need to set too.
'format', 'formatType', 'orient', 'labelExpr', 'tickCount', 'position', 'tickMinStep']);
function parseAxis(channel, model) {
- var _axis, _config, _config$axis, _axis2;
+ var _axis, _config, _config$axis, _axis2, _axis$encoding;
let axis = model.axis(channel);
const axisComponent = new AxisComponent();
const fieldOrDatumDef = getFieldOrDatumDef(model.encoding[channel]);
const {
@@ -23733,27 +22800,30 @@
if (hasValue && !hasConfigValue) {
// only set property if it is explicitly set or has no config value (otherwise we will accidentally override config)
axisComponent.set(property, value, explicit);
} else if ( // Cases need implicit values
// 1. Axis config that aren't available in Vega
- !(configFrom === 'vgAxisConfig') || propsToAlwaysIncludeConfig.has(property) && hasConfigValue || // 3. Conditional axis values and signals
+ !(configFrom === 'vgAxisConfig') || // 2. Certain properties are always included (see `propsToAlwaysIncludeConfig`'s declaration for more details)
+ propsToAlwaysIncludeConfig.has(property) && hasConfigValue || // 3. Conditional axis values and signals
isConditionalAxisValue(configValue) || isSignalRef(configValue)) {
// If a config is specified and is conditional, copy conditional value from axis config
axisComponent.set(property, configValue, false);
}
}
} // 2) Add guide encode definition groups
- const axisEncoding = axis.encoding ?? {};
+ const axisEncoding = (_axis$encoding = axis.encoding) !== null && _axis$encoding !== void 0 ? _axis$encoding : {};
const axisEncode = AXIS_PARTS.reduce((e, part) => {
+ var _axisEncoding$part;
+
if (!axisComponent.hasAxisPart(part)) {
// No need to create encode for a disabled part.
return e;
}
- const axisEncodingPart = guideEncodeEntry(axisEncoding[part] ?? {}, model);
+ const axisEncodingPart = guideEncodeEntry((_axisEncoding$part = axisEncoding[part]) !== null && _axisEncoding$part !== void 0 ? _axisEncoding$part : {}, model);
const value = part === 'labels' ? labels(model, channel, axisEncodingPart) : axisEncodingPart;
if (value !== undefined && !isEmpty(value)) {
e[part] = {
update: value
@@ -23768,16 +22838,18 @@
}
return axisComponent;
}
- function initLayoutSize({
- encoding,
- size
- }) {
+ function initLayoutSize(_ref) {
+ let {
+ encoding,
+ size
+ } = _ref;
+
for (const channel of POSITION_SCALE_CHANNELS) {
- const sizeType = getSizeChannel$1(channel);
+ const sizeType = getSizeChannel(channel);
if (isStep(size[sizeType])) {
if (isContinuousFieldOrDatumDef(encoding[channel])) {
delete size[sizeType];
warn(stepDropped(sizeType));
@@ -23849,13 +22921,15 @@
}
return undefined;
}
- function defaultFilled(markDef, config, {
- graticule
- }) {
+ function defaultFilled(markDef, config, _ref) {
+ let {
+ graticule
+ } = _ref;
+
if (graticule) {
return false;
}
const filledConfig = getMarkConfig('filled', markDef, config);
@@ -24006,12 +23080,12 @@
}),
...pointPosition('y', model, {
defaultPos: 'mid'
}),
// arcs are rectangles in polar coordinates
- ...rectPosition(model, 'radius', 'arc'),
- ...rectPosition(model, 'theta', 'arc')
+ ...rectPosition(model, 'radius'),
+ ...rectPosition(model, 'theta')
};
}
};
const area = {
@@ -24049,12 +23123,12 @@
color: 'include',
orient: 'ignore',
size: 'ignore',
theta: 'ignore'
}),
- ...rectPosition(model, 'x', 'bar'),
- ...rectPosition(model, 'y', 'bar')
+ ...rectPosition(model, 'x'),
+ ...rectPosition(model, 'y')
};
}
};
const geoshape = {
@@ -24098,12 +23172,12 @@
color: 'ignore',
orient: 'ignore',
size: 'ignore',
theta: 'ignore'
}),
- ...rectPosition(model, 'x', 'image'),
- ...rectPosition(model, 'y', 'image'),
+ ...rectPosition(model, 'x'),
+ ...rectPosition(model, 'y'),
...text$1(model, 'url')
};
}
};
@@ -24218,12 +23292,12 @@
color: 'include',
orient: 'ignore',
size: 'ignore',
theta: 'ignore'
}),
- ...rectPosition(model, 'x', 'rect'),
- ...rectPosition(model, 'y', 'rect')
+ ...rectPosition(model, 'x'),
+ ...rectPosition(model, 'y')
};
}
};
const rule = {
@@ -24363,29 +23437,31 @@
};
}
};
function defaultSize(model) {
+ var _getMarkPropOrConfig;
+
const {
config,
markDef
} = model;
const {
orient
} = markDef;
const vgSizeChannel = orient === 'horizontal' ? 'width' : 'height';
const scale = model.getScaleComponent(orient === 'horizontal' ? 'x' : 'y');
- const markPropOrConfig = getMarkPropOrConfig('size', markDef, config, {
+ const markPropOrConfig = (_getMarkPropOrConfig = getMarkPropOrConfig('size', markDef, config, {
vgChannel: vgSizeChannel
- }) ?? config.tick.bandSize;
+ })) !== null && _getMarkPropOrConfig !== void 0 ? _getMarkPropOrConfig : config.tick.bandSize;
if (markPropOrConfig !== undefined) {
return markPropOrConfig;
} else {
const scaleRange = scale ? scale.get('range') : undefined;
- if (scaleRange && isVgRangeStep(scaleRange) && vegaUtil.isNumber(scaleRange.step)) {
+ if (scaleRange && isVgRangeStep(scaleRange) && vega.isNumber(scaleRange.step)) {
return scaleRange.step * 3 / 4;
}
const defaultViewStep = getViewConfigDiscreteStep(config.view, vgSizeChannel);
return defaultViewStep * 3 / 4;
@@ -24467,18 +23543,23 @@
* If stack is used and the model doesn't have size encoding, we put the mark into groups,
* and apply cornerRadius properties at the group.
*/
function getGroupsForStackedBarWithCornerRadius(model) {
+ var _model$stack$groupbyC;
+
// Generate the mark
const [mark] = getMarkGroup(model, {
fromPrefix: STACK_GROUP_PREFIX
}); // Get the scale for the stacked field
const fieldScale = model.scaleName(model.stack.fieldChannel);
- const stackField = (opt = {}) => model.vgField(model.stack.fieldChannel, opt); // Find the min/max of the pixel value on the stacked direction
+ const stackField = function () {
+ let opt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+ return model.vgField(model.stack.fieldChannel, opt);
+ }; // Find the min/max of the pixel value on the stacked direction
const stackFieldGroup = (func, expr) => {
const vgFieldMinMax = [stackField({
prefix: 'min',
@@ -24495,11 +23576,11 @@
}), stackField({
prefix: 'max',
suffix: 'end',
expr
})];
- return `${func}(${vgFieldMinMax.map(field => `scale('${fieldScale}',${field})`).join(',')})`;
+ return "".concat(func, "(").concat(vgFieldMinMax.map(field => "scale('".concat(fieldScale, "',").concat(field, ")")).join(','), ")");
};
let groupUpdate;
let innerGroupUpdate; // Build the encoding for group and an inner group
@@ -24593,23 +23674,25 @@
}
}
const groupby = [];
- if (model.stack.groupbyChannel) {
- // For bin and time unit, we have to add bin/timeunit -end channels.
- const groupByField = model.fieldDef(model.stack.groupbyChannel);
- const field = vgField(groupByField);
+ if (((_model$stack$groupbyC = model.stack.groupbyChannels) === null || _model$stack$groupbyC === void 0 ? void 0 : _model$stack$groupbyC.length) > 0) {
+ for (const groupbyChannel of model.stack.groupbyChannels) {
+ // For bin and time unit, we have to add bin/timeunit -end channels.
+ const groupByField = model.fieldDef(groupbyChannel);
+ const field = vgField(groupByField);
- if (field) {
- groupby.push(field);
- }
+ if (field) {
+ groupby.push(field);
+ }
- if (groupByField !== null && groupByField !== void 0 && groupByField.bin || groupByField !== null && groupByField !== void 0 && groupByField.timeUnit) {
- groupby.push(vgField(groupByField, {
- binSuffix: 'end'
- }));
+ if (groupByField !== null && groupByField !== void 0 && groupByField.bin || groupByField !== null && groupByField !== void 0 && groupByField.timeUnit) {
+ groupby.push(vgField(groupByField, {
+ binSuffix: 'end'
+ }));
+ }
}
}
const strokeProperties = ['stroke', 'strokeWidth', 'strokeJoin', 'strokeCap', 'strokeDash', 'strokeDashOffset', 'strokeMiterLimit', 'strokeOpacity']; // Generate stroke properties for the group
@@ -24682,13 +23765,13 @@
markDef,
config
} = model;
const order = encoding.order;
- if (!vegaUtil.isArray(order) && isValueDef(order) && isNullOrFalse(order.value) || !order && isNullOrFalse(getMarkPropOrConfig('order', markDef, config))) {
+ if (!vega.isArray(order) && isValueDef(order) && isNullOrFalse(order.value) || !order && isNullOrFalse(getMarkPropOrConfig('order', markDef, config))) {
return undefined;
- } else if ((vegaUtil.isArray(order) || isFieldDef(order)) && !stack) {
+ } else if ((vega.isArray(order) || isFieldDef(order)) && !stack) {
// Sort by the order field if it is specified and the field is not stacked. (For stacked field, order specify stack order.)
return sortParams(order, {
expr: 'datum'
});
} else if (isPathMark(mark)) {
@@ -24697,11 +23780,11 @@
const dimensionChannelDef = encoding[dimensionChannel];
if (isFieldDef(dimensionChannelDef)) {
const s = dimensionChannelDef.sort;
- if (vegaUtil.isArray(s)) {
+ if (vega.isArray(s)) {
return {
field: vgField(dimensionChannelDef, {
prefix: dimensionChannel,
suffix: 'sort_index',
expr: 'datum'
@@ -24745,13 +23828,14 @@
}
return undefined;
}
- function getMarkGroup(model, opt = {
- fromPrefix: ''
- }) {
+ function getMarkGroup(model) {
+ let opt = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
+ fromPrefix: ''
+ };
const {
mark,
markDef,
encoding,
config
@@ -24801,11 +23885,11 @@
function scaleClip(model) {
const xScale = model.getScaleComponent('x');
const yScale = model.getScaleComponent('y');
- return xScale && xScale.get('selectionExtent') || yScale && yScale.get('selectionExtent') ? true : undefined;
+ return xScale !== null && xScale !== void 0 && xScale.get('selectionExtent') || yScale !== null && yScale !== void 0 && yScale.get('selectionExtent') ? true : undefined;
}
/**
* If we use a custom projection with auto-fitting to the geodata extent,
* we need to clip to ensure the chart size doesn't explode.
*/
@@ -24839,11 +23923,15 @@
/**
* Internal model of Vega-Lite specification for the compiler.
*/
class UnitModel extends ModelWithField {
- constructor(spec, parent, parentGivenName, parentGivenSize = {}, config) {
+ constructor(spec, parent, parentGivenName) {
+ var _spec$params;
+
+ let parentGivenSize = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
+ let config = arguments.length > 4 ? arguments[4] : undefined;
super(spec, 'unit', parent, parentGivenName, config, undefined, isFrameMixins(spec) ? spec.view : undefined);
_defineProperty(this, "markDef", void 0);
_defineProperty(this, "encoding", void 0);
@@ -24875,11 +23963,11 @@
}
const encoding = this.encoding = initEncoding(spec.encoding || {}, mark, markDef.filled, config);
this.markDef = initMarkdef(markDef, encoding, config);
this.size = initLayoutSize({
- encoding: encoding,
+ encoding,
size: isFrameMixins(spec) ? { ...parentGivenSize,
...(spec.width ? {
width: spec.width
} : {}),
...(spec.height ? {
@@ -24892,11 +23980,11 @@
this.specifiedScales = this.initScales(mark, encoding);
this.specifiedAxes = this.initAxes(encoding);
this.specifiedLegends = this.initLegends(encoding);
this.specifiedProjection = spec.projection; // Selections will be initialized upon parse.
- this.selection = (spec.params ?? []).filter(p => isSelectionParameter(p));
+ this.selection = ((_spec$params = spec.params) !== null && _spec$params !== void 0 ? _spec$params : []).filter(p => isSelectionParameter(p));
}
get hasProjection() {
const {
encoding
@@ -24927,11 +24015,13 @@
initScales(mark, encoding) {
return SCALE_CHANNELS.reduce((scales, channel) => {
const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]);
if (fieldOrDatumDef) {
- scales[channel] = this.initScale(fieldOrDatumDef.scale ?? {});
+ var _fieldOrDatumDef$scal;
+
+ scales[channel] = this.initScale((_fieldOrDatumDef$scal = fieldOrDatumDef.scale) !== null && _fieldOrDatumDef$scal !== void 0 ? _fieldOrDatumDef$scal : {});
}
return scales;
}, {});
}
@@ -24942,15 +24032,15 @@
range
} = scale; // TODO: we could simplify this function if we had a recursive replace function
const scaleInternal = replaceExprRef(scale);
- if (vegaUtil.isArray(domain)) {
+ if (vega.isArray(domain)) {
scaleInternal.domain = domain.map(signalRefOrValue);
}
- if (vegaUtil.isArray(range)) {
+ if (vega.isArray(range)) {
scaleInternal.range = range.map(signalRefOrValue);
}
return scaleInternal;
}
@@ -25037,11 +24127,13 @@
assembleLayoutSignals() {
return assembleLayoutSignals(this);
}
assembleMarks() {
- let marks = this.component.mark ?? []; // If this unit is part of a layer, selections should augment
+ var _this$component$mark;
+
+ let marks = (_this$component$mark = this.component.mark) !== null && _this$component$mark !== void 0 ? _this$component$mark : []; // If this unit is part of a layer, selections should augment
// all in concert rather than each unit individually. This
// ensures correct interleaving of clipping and brushed marks.
if (!this.parent || !isLayerModel(this.parent)) {
marks = assembleUnitSelectionMarks(this, marks);
@@ -25111,13 +24203,13 @@
height: spec.height
} : {})
};
this.children = spec.layer.map((layer, i) => {
if (isLayerSpec(layer)) {
- return new LayerModel(layer, this, this.getName(`layer_${i}`), layoutSize, config);
+ return new LayerModel(layer, this, this.getName("layer_".concat(i)), layoutSize, config);
} else if (isUnitSpec(layer)) {
- return new UnitModel(layer, this, this.getName(`layer_${i}`), layoutSize, config);
+ return new UnitModel(layer, this, this.getName("layer_".concat(i)), layoutSize, config);
}
throw new Error(invalidSpec(layer));
});
}
@@ -25182,11 +24274,11 @@
assembleGroupStyle() {
const uniqueStyles = new Set();
for (const child of this.children) {
- for (const style of vegaUtil.array(child.assembleGroupStyle())) {
+ for (const style of vega.array(child.assembleGroupStyle())) {
uniqueStyles.add(style);
}
}
const styles = Array.from(uniqueStyles);
@@ -25273,11 +24365,13 @@
*
* @param inputSpec The Vega-Lite specification.
* @param opt Optional arguments passed to the Vega-Lite compiler.
* @returns An object containing the compiled Vega spec and normalized Vega-Lite spec.
*/
- function compile(inputSpec, opt = {}) {
+ function compile(inputSpec) {
+ let opt = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+
// 0. Augment opt with default opts
if (opt.logger) {
// set the singleton logger to the provided logger
set(opt.logger);
}
@@ -25287,11 +24381,11 @@
setTitleFormatter(opt.fieldTitle);
}
try {
// 1. Initialize config by deep merging default config with the config provided via option and the input spec.
- const config = initConfig(vegaUtil.mergeConfig(opt.config, inputSpec.config)); // 2. Normalize: Convert input spec -> normalized spec
+ const config = initConfig(vega.mergeConfig(opt.config, inputSpec.config)); // 2. Normalize: Convert input spec -> normalized spec
// - Decompose all extended unit specs into composition of unit spec. For example, a box plot get expanded into multiple layers of bars, ticks, and rules. The shorthand row/column channel is also expanded to a facet spec.
// - Normalize autosize and width or height spec
const spec = normalize(inputSpec, config); // 3. Build Model: normalized spec -> Model (a tree structure)
// This phases instantiates the models with default config by doing a top-down traversal. This allows us to pass properties that child models derive from their parents via their constructors.
@@ -25342,11 +24436,11 @@
};
if (model.hasAxisOrientSignalRef()) {
autosize.resize = true;
}
- } else if (vegaUtil.isString(autosize)) {
+ } else if (vega.isString(autosize)) {
autosize = {
type: autosize
};
}
@@ -25381,11 +24475,13 @@
* Note: this couldn't be `model.assemble()` since the top-level model
* needs some special treatment to generate top-level properties.
*/
- function assembleTopLevelModel(model, topLevelProperties, datasets = {}, usermeta) {
+ function assembleTopLevelModel(model, topLevelProperties) {
+ let datasets = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+ let usermeta = arguments.length > 3 ? arguments[3] : undefined;
// Config with Vega-Lite only config removed.
const vgConfig = model.config ? stripAndRedirectConfig(model.config) : undefined;
const data = [].concat(model.assembleSelectionData([]), // only assemble data in the root
assembleRootData(model.component.data, datasets));
const projections = model.assembleProjections();
@@ -25423,11 +24519,11 @@
update: encodeEntry
}
} : {}),
data,
...(projections.length > 0 ? {
- projections: projections
+ projections
} : {}),
...model.assembleGroup([...layoutSignals, ...model.assembleSelectionTopLevelSignals([]), ...assembleParameterSignals(params)]),
...(vgConfig ? {
config: vgConfig
} : {}),
@@ -25461,10 +24557,11 @@
exports.isNullOrFalse = isNullOrFalse;
exports.isNumeric = isNumeric;
exports.keys = keys;
exports.logicalExpr = logicalExpr;
exports.mergeDeep = mergeDeep;
+ exports.never = never;
exports.normalize = normalize;
exports.normalizeAngle = normalizeAngle;
exports.omit = omit;
exports.pick = pick;
exports.prefixGenerator = prefixGenerator;
@@ -25482,6 +24579,6 @@
exports.varName = varName;
exports.version = version;
Object.defineProperty(exports, '__esModule', { value: true });
-})));
+}));